Programs & Examples On #Graphviz

Graphviz, developed by AT&T Research Labs, is the leading application for layout and drawing of graphs (objects comprised of vertices connected by edges). It includes the dot language, a complete syntax for graph description and a set of layout engines. Graphviz is free and open source.

anaconda - graphviz - can't import after installation

On conda:

First install

conda install graphviz

Then the python-library for graphviz python-graphviz

gv_python is a dynamically loaded extension for python that provides access to the graph facilities of graphviz.

conda install python-graphviz

There is also pydot package, which can parse and dump into DOT language, used by GraphViz

conda install pydot

Graphviz: How to go from .dot to a graph?

dot file.dot -Tpng -o image.png

This works on Windows and Linux. Graphviz must be installed.

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

1.install windows package from: https://graphviz.gitlab.io/_pages/Download/Download_windows.html and download msi file

Add in Environmental variables 2. Add C:\Program Files (x86)\Graphviz2.38\bin to User path

  1. Add C:\Program Files (x86)\Graphviz2.38\bin\dot.exe to System Path

  2. Restart your python notebook.

It will work.

Why is pydot unable to find GraphViz's executables in Windows 8?

For windows 8.1 & python 2.7 , I fixed the problem by following below steps

1 . Download and install graphviz-2.38.msi https://graphviz.gitlab.io/_pages/Download/Download_windows.html

2 . Set the path variable

Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit add 'C:\Program Files (x86)\Graphviz2.38\bin'

  1. Restart your currently running application that requires the path

How to use doxygen to create UML class diagrams from C++ source

Hmm, this seems to be a bit of an old question, but since I've been messing about with Doxygen configuration last few days, while my head's still full of current info let's have a stab at it -

I think the previous answers almost have it:

The missing option is to add COLLABORATION_GRAPH = YES in the Doxyfile. I assume you can do the equivalent thing somewhere in the doxywizard GUI (I don't use doxywizard).

So, as a more complete example, typical "Doxyfile" options related to UML output that I tend to use are:

EXTRACT_ALL          = YES
CLASS_DIAGRAMS      = YES
HIDE_UNDOC_RELATIONS = NO
HAVE_DOT             = YES
CLASS_GRAPH          = YES
COLLABORATION_GRAPH  = YES
UML_LOOK             = YES
UML_LIMIT_NUM_FIELDS = 50
TEMPLATE_RELATIONS   = YES
DOT_GRAPH_MAX_NODES  = 100
MAX_DOT_GRAPH_DEPTH  = 0
DOT_TRANSPARENT      = YES

These settings will generate both "inheritance" (CLASS_GRAPH=YES) and "collaboration" (COLLABORATION_GRAPH=YES) diagrams.

Depending on your target for "deployment" of the doxygen output, setting DOT_IMAGE_FORMAT = svg may also be of use. With svg output the diagrams are "scalable" instead of the fixed resolution of bitmap formats such as .png. Apparently, if viewing the output in browsers other than IE, there is also INTERACTIVE_SVG = YES which will allow "interactive zooming and panning" of the generated svg diagrams. I did try this some time ago, and the svg output was very visually attractive, but at the time, browser support for svg was still a bit inconsistent, so hopefully that situation may have improved lately.

As other comments have mentioned, some of these settings (DOT_GRAPH_MAX_NODES in particular) do have potential performance impacts, so YMMV.

I tend to hate "RTFM" style answers, so apologies for this sentence, but in this case the Doxygen documentation really is your friend, so check out the Doxygen docs on the above mentioned settings- last time I looked you can find the details at http://www.doxygen.nl/manual/config.html.

Graphviz's executables are not found (Python 3.4)

Please use pydotplus instead of pydot

  1. Find:C:\Users\zhangqianyuan\AppData\Local\Programs\Python\Python36\Lib\site-packages\pydotplus

  2. Open graphviz.py

  3. Find line 1925 - line 1972, find the function:

    def create(self, prog=None, format='ps'):
    
  4. In the function find:

    if prog not in self.progs:
        raise InvocationException(
            'GraphViz\'s executable "%s" not found' % prog)
    
    if not os.path.exists(self.progs[prog]) or \
            not os.path.isfile(self.progs[prog]):
        raise InvocationException(
            'GraphViz\'s executable "{}" is not'
            ' a file or doesn\'t exist'.format(self.progs[prog])
        )
    
  5. Between the two blocks add this(Your Graphviz's executable path):

      self.progs[prog] = "C:/Program Files (x86)/Graphviz2.38/bin/gvedit.exe"`
    
  6. After adding the result is:

    if prog not in self.progs:
        raise InvocationException(
            'GraphViz\'s executable "%s" not found' % prog)
    
    self.progs[prog] = "C:/Program Files (x86)/Graphviz2.38/bin/gvedit.exe"
    
    if not os.path.exists(self.progs[prog]) or \
            not os.path.isfile(self.progs[prog]):
        raise InvocationException(
            'GraphViz\'s executable "{}" is not'
            ' a file or doesn\'t exist'.format(self.progs[prog])
        )
    
  7. save the changed file then you can run it successfully.

  8. you'd better save it as bmp file because png file will not work. picture is here

store return value of a Python script in a bash script

Python documentation for sys.exit([arg])says:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise.

Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable.

Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this:

outputString=`python myPythonScript arg1 arg2 arg3 | tail -0`

How to detect the end of loading of UITableView

Swift 2 solution:

// willDisplay function
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    let lastRowIndex = tableView.numberOfRowsInSection(0)
    if indexPath.row == lastRowIndex - 1 {
        fetchNewDataFromServer()
    }
}

// data fetcher function
func fetchNewDataFromServer() {
    if(!loading && !allDataFetched) {
        // call beginUpdates before multiple rows insert operation
        tableView.beginUpdates()
        // for loop
        // insertRowsAtIndexPaths
        tableView.endUpdates()
    }
}

Is it possible to declare a variable in Gradle usable in Java?

I'm using this code and working very fine.

def baseUrl = '\"http://patelwala.com/myapi/"'
def googleServerKey = '\"87171841097-opu71rk2ps35ibv96ud57g3ktto6ioio.apps.googleusercontent.com"'
android {
  buildTypes {
  release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id', googleServerKey
    }
    releasedebug {
        initWith debug
        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id' ,googleServerKey
    }
    debug {

        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id', googleServerKey
    }
 }
}

}

Max length UITextField

you can extend UITextField and add an @IBInspectable object for handle it:

SWIFT 5

import UIKit
private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
                return 150 // (global default-limit. or just, Int.max)
            }
            return l
        }
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
        }
    }
    @objc func fix(textField: UITextField) {
        if let t = textField.text {
            textField.text = String(t.prefix(maxLength))
        }
    }
}

and after that define it on attribute inspector

enter image description here

See Swift 4 original Answer

Android notification is not showing

You also need to change the build.gradle file, and add the used Android SDK version into it:

implementation 'com.android.support:appcompat-v7:28.0.0'

This worked like a charm in my case.

How do I output coloured text to a Linux terminal?

try my header here for a quick and easy way to color text: Aedi's Color Header


Escape-Sequence-Color-Header

Color Your Output in Unix using C++!!


Text Attribute Options:

ATTRIBUTES_OFF, BOLD, UNDERSCORE, BLINK, REVERSE_VIDEO, CONCEALED


Color Options:

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE


Format:

General Format, include value you want in $variable$

COLOR_$Foreground_Color$_$Background_Color$
COLOR_$Text_Attribute$_$Foreground_Color$_$Background_Color$
COLOR_NORMAL  // To set color to default

e.g.

COLOR_BLUE_BLACK // Leave Text Attribute Blank if no Text Attribute appied
COLOR_UNDERSCORE_YELLOW_RED
COLOR_NORMAL


Usage:

Just use to stream the color you want before outputting text and use again to set the color to normal after outputting text.

cout << COLOR_BLUE_BLACK << "TEXT" << COLOR_NORMAL << endl;
cout << COLOR_BOLD_YELLOW_CYAN << "TEXT" << COLOR_NORMAL << endl;

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Fixed width buttons with Bootstrap

btn-group-justified and btn-group only work for static content but not on dynamically created buttons, and fixed with of button in css is not practical as it stay on the same width even all content are short.

My solution: put the same class to group of buttons then loop to all of them, get the width of the longest button and apply it to all

var bwidth=0
$("button.btnGroup").each(function(i,v){
    if($(v).width()>bwidth) bwidth=$(v).width();
});
$("button.btnGroup").width(bwidth);

Sample output here

Django: Calling .update() on a single model instance retrieved by .get()?

if you want only to update model if exist (without create it):

Model.objects.filter(id = 223).update(field1 = 2)

mysql query:

UPDATE `model` SET `field1` = 2 WHERE `model`.`id` = 223

CSS background-image not working

In addition to display:block OR display:inline-block

Try giving sufficient padding to your .btn-pToolName and make sure you have the correct values for background-position

Is there any option to limit mongodb memory usage?

One thing you can limit is the amount of memory mongodb uses while building indexes. This is set using the maxIndexBuildMemoryUsageMegabytes setting. An example of how its set is below:

mongo --eval "db.adminCommand( { setParameter: 1, maxIndexBuildMemoryUsageMegabytes: 70000 } )"

Add an index (numeric ID) column to large data frame

You can add a sequence of numbers very easily with

data$ID <- seq.int(nrow(data))

If you are already using library(tidyverse), you can use

data <- tibble::rowid_to_column(data, "ID")

Java String - See if a string contains only numbers and not letters

If you'll be processing the number as text, then change:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){

to:

if (text.matches("[0-9]+") && text.length() > 2) {

Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.

If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


As a side note, it's generally considered bad practice to compare boolean values to true or false. Just use if (condition) or if (!condition).

onclick go full screen

var elem = document.getElementById("myvideo");
function openFullscreen() {
  if (elem.requestFullscreen) {
      elem.requestFullscreen();
  } else if (elem.mozRequestFullScreen) { /* Firefox */
      elem.mozRequestFullScreen();
  } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
      elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) { /* IE/Edge */
      elem.msRequestFullscreen();
  }
}
//Internet Explorer 10 and earlier does not support the msRequestFullscreen() method.

How to find list of possible words from a letter matrix [Boggle Solver]

How about simple sorting and using the binary search in the dictionary?

Returns whole list in 0.35 sec and can be further optimized (by for instance removing words with unused letters etc.).

from bisect import bisect_left

f = open("dict.txt")
D.extend([line.strip() for line in f.readlines()])
D = sorted(D)

def neibs(M,x,y):
    n = len(M)
    for i in xrange(-1,2):
        for j in xrange(-1,2):
            if (i == 0 and j == 0) or (x + i < 0 or x + i >= n or y + j < 0 or y + j >= n):
                continue
            yield (x + i, y + j)

def findWords(M,D,x,y,prefix):
    prefix = prefix + M[x][y]

    # find word in dict by binary search
    found = bisect_left(D,prefix)

    # if found then yield
    if D[found] == prefix: 
        yield prefix

    # if what we found is not even a prefix then return
    # (there is no point in going further)
    if len(D[found]) < len(prefix) or D[found][:len(prefix)] != prefix:
        return

    # recourse
    for neib in neibs(M,x,y):
        for word in findWords(M,D,neib[0], neib[1], prefix):
            yield word

def solve(M,D):
    # check each starting point
    for x in xrange(0,len(M)):
        for y in xrange(0,len(M)):
            for word in findWords(M,D,x,y,""):
                yield word

grid = "fxie amlo ewbx astu".split()
print [x for x in solve(grid,D)]

MySQL duplicate entry error even though there is no duplicate entry

As per your code your "number" and "Name" are primarykey and you are inserting S.NAME in both row so it will make a conflict. we are using primarykey for accessing complete data. here you cant access the data using the primarykey 'name'.

im a beginner and i think it might be the error.

Java multiline string

String.join

Java 8 added a new static method to java.lang.String which offers a slightly better alternative:

String.join( CharSequence delimiter , CharSequence... elements )

Using it:

String s = String.join(
    System.getProperty("line.separator"),
    "First line.",
    "Second line.",
    "The rest.",
    "And the last!"
);

App store link for "rate/review this app"

Everything, written above is correct. Just a sample to insert into the app and change {YOUR APP ID} to actual app id, taken from iTunesconnect to show the Review page. Please note, as it was commented above, that it is not working on the Simulator - just the device.
- Correcting because of ios 7 changes.

NSString * appId = @"{YOUR APP ID}";
NSString * theUrl = [NSString  stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software",appId];
if ([[UIDevice currentDevice].systemVersion integerValue] > 6) theUrl = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@",appId];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:theUrl]];

Check if a string has white space

Your regex won't match anything, as it is. You definitely need to remove the quotes -- the "/" characters are sufficient.

/^\s+$/ is checking whether the string is ALL whitespace:

  • ^ matches the start of the string.
  • \s+ means at least 1, possibly more, spaces.
  • $ matches the end of the string.

Try replacing the regex with /\s/ (and no quotes)

List of installed gems?

Gem::Specification.map {|a| a.name}

However, if your app uses Bundler it will return only list of dependent local gems. To get all installed:

def all_installed_gems
   Gem::Specification.all = nil    
   all = Gem::Specification.map{|a| a.name}  
   Gem::Specification.reset
   all
end

Creating a new empty branch for a new project

On base this answer from Hiery Nomus.

You can create a branch as an orphan:

git checkout --orphan <branchname>

This will create a new branch with no parents. Then, you can clear the working directory with:

git rm --cached -r .

And then you just commit branch with empty commit and then push

git commit -m <commit message> --allow-empty
git push origin <newbranch>

Get selected value of a dropdown's item using jQuery

Yet another tested example:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $('#bonus').change(function() {
    alert($("#bonus option:selected").text());
  });  
});
</script>
</head>

<body>
<select id="bonus">
<option value="1">-$5000</option>
<option value="2">-$2500</option>
<option value="3">$0</option>
<option value="4">$1</option>
<option value="5">We really appreciate your work</option>
</select>
</body>
</html>

Remove Project from Android Studio

If it's Windows, all you need to do is delete the root of that project within the file explorer. Just right click on the name of the app in Android Studio, and then "show in file explorer". Then just delete the project folder all in all.

How to refresh datagrid in WPF

Bind you Datagrid to an ObservableCollection, and update your collection instead.

Ignoring upper case and lower case in Java

The .equalsIgnoreCase() method should help with that.

how to run a winform from console application?

You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application

Can I pass a JavaScript variable to another browser window?

You can pass variables, and reference to things in the parent window quite easily:

// open an empty sample window:
var win = open("");
win.document.write("<html><body><head></head><input value='Trigger handler in other window!' type='button' id='button'></input></body></html>");

// attach to button in target window, and use a handler in this one:
var button = win.document.getElementById('button');

button.onclick = function() {
     alert("I'm in the first frame!");   
}

Java heap terminology: young, old and permanent generations?

What is the young generation?

The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. A young generation full of dead objects is collected very quickly. Some survived objects are aged and eventually move to the old generation.

What is the old generation?

The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection

What is the permanent generation?

The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application.

PermGen has been replaced with Metaspace since Java 8 release.

PermSize & MaxPermSize parameters will be ignored now

How does the three generations interact/relate to each other?

enter image description here

Image source & oracle technetwork tutorial article: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

"The General Garbage Collection Process" in above article explains the interactions between them with many diagrams.

Have a look at summary diagram:

enter image description here

Nesting optgroups in a dropdownlist/select

I know this was quite a while ago, however I have a little extra to add:

This is not possible in HTML5 or any previous specs, nor is it proposed in HTML5.1 yet. I have made a request to the public-html-comments mailing list, but we'll see if anything comes of it.

Regardless, whilst this is not possible using <select> yet, you can achieve a similar effect with the following HTML, plus some CSS for prettiness:

_x000D_
_x000D_
<ul>_x000D_
  <li>_x000D_
 <input type="radio" name="location" value="0" id="loc_0" />_x000D_
 <label for="loc_0">United States</label>_x000D_
 <ul>_x000D_
   <li>_x000D_
  Northeast_x000D_
        <ul>_x000D_
       <li>_x000D_
   <input type="radio" name="location" value="1" id="loc_1" />_x000D_
   <label for="loc_1">New Hampshire</label>_x000D_
    </li>_x000D_
          <li>_x000D_
   <input type="radio" name="location" value="2" id="loc_2" />_x000D_
   <label for="loc_2">Vermont</label>_x000D_
    </li>_x000D_
          <li>_x000D_
    <input type="radio" name="location" value="3" id="loc_3" />_x000D_
    <label for="loc_3">Maine</label>_x000D_
    </li>_x000D_
   </ul>_x000D_
    </li>_x000D_
       <li>_x000D_
     Southeast_x000D_
           <ul>_x000D_
    <li>_x000D_
    <input type="radio" name="location" value="4" id="loc_4" />_x000D_
    <label for="loc_4">Georgia</label>_x000D_
    </li>_x000D_
             <li>_x000D_
    <input type="radio" name="location" value="5" id="loc_5" />_x000D_
    <label for="loc_5">Alabama</label>_x000D_
    </li>_x000D_
     </ul>_x000D_
  </li>_x000D_
   </ul>_x000D_
    </li>_x000D_
    <li>_x000D_
    <input type="radio" name="location" value="6" id="loc_6" />_x000D_
    <label for="loc_6">Canada</label>_x000D_
       <ul>_x000D_
    <li>_x000D_
    <input type="radio" name="location" value="7" id="loc_7" />_x000D_
    <label for="loc_7">Ontario</label>_x000D_
    </li>_x000D_
          <li>_x000D_
     <input type="radio" name="location" value="8" id="loc_8" />_x000D_
        <label for="loc_8">Quebec</label>_x000D_
    </li>_x000D_
          <li>_x000D_
      <input type="radio" name="location" value="9" id="loc_9" />_x000D_
      <label for="loc_9">Manitoba</label>_x000D_
    </li>_x000D_
  </ul>_x000D_
  </li>_x000D_
  </ul>
_x000D_
_x000D_
_x000D_

As an extra added benefit, this also means you can allow selection of the <optgroups> themselves. This might be useful if you had, for example, nested categories where the categories go into heavy detail and you want to allow users to select higher up in the hierarchy.

This will all work without JavaScript, however you might wish to add some to hide the radio buttons and then change the background color of the selected item or something.

Bear in mind, this is far from a perfect solution, but if you absolutely need a nested select with reasonable cross-browser compatibility, this is probably as close as you're going to get.

How to disable Google asking permission to regularly check installed apps on my phone?

If you want to turn off app verification programmatically, you can do so with the following code:

boolean success = true;
boolean enabled = Settings.Secure.getInt(context.getContentResolver(), "package_verifier_enable", 1) == 1;
if (enabled) {
    success = Settings.Secure.putString(context.getContentResolver(), "package_verifier_enable", "0");
}

You will also need the following system permissions:

<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

Also worth noting is that the "package_verifier_enable" string comes from the Settings.Glabal.PACKAGE_VERIFIER_ENABLE member which seems to be inaccessible.

How do I decrease the size of my sql server log file?

  1. Ensure the database's backup mode is set to Simple (see here for an overview of the different modes). This will avoid SQL Server waiting for a transaction log backup before reusing space.

  2. Use dbcc shrinkfile or Management Studio to shrink the log files.

Step #2 will do nothing until the backup mode is set.

How to change password using TortoiseSVN?

Password changes are handled by the subversion server administrator. As a user there is no password change option.

Check with your server admin.

If you are the admin, find your SVN Server installation. If you don't know where it is, it could be listed in Start->Programs, running under services in Start->Control Panel->Services or it could be listed under C:\Program Files.

The SVN Server should have an application to run to add/change/delete authentication and users.

replace all occurrences in a string

As explained here, you can use:

function replaceall(str,replace,with_this)
{
    var str_hasil ="";
    var temp;

    for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
        {
            temp = with_this;
        }
        else
        {
                temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}

... which you can then call using:

var str = "50.000.000";
alert(replaceall(str,'.',''));

The function will alert "50000000"

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

A solution for me:

$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) {
   WriteTraceForTrans "The session configuration MyShellUri is already unregistered."
}
else {        
   #Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore
}
$ErrorActionPreference = $old_ErrorActionPreference 

Or use try-catch

try { 

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)

} 
catch {

}

Grouping functions (tapply, by, aggregate) and the *apply family

I recently discovered the rather useful sweep function and add it here for the sake of completeness:

sweep

The basic idea is to sweep through an array row- or column-wise and return a modified array. An example will make this clear (source: datacamp):

Let's say you have a matrix and want to standardize it column-wise:

dataPoints <- matrix(4:15, nrow = 4)

# Find means per column with `apply()`
dataPoints_means <- apply(dataPoints, 2, mean)

# Find standard deviation with `apply()`
dataPoints_sdev <- apply(dataPoints, 2, sd)

# Center the points 
dataPoints_Trans1 <- sweep(dataPoints, 2, dataPoints_means,"-")

# Return the result
dataPoints_Trans1
##      [,1] [,2] [,3]
## [1,] -1.5 -1.5 -1.5
## [2,] -0.5 -0.5 -0.5
## [3,]  0.5  0.5  0.5
## [4,]  1.5  1.5  1.5

# Normalize
dataPoints_Trans2 <- sweep(dataPoints_Trans1, 2, dataPoints_sdev, "/")

# Return the result
dataPoints_Trans2
##            [,1]       [,2]       [,3]
## [1,] -1.1618950 -1.1618950 -1.1618950
## [2,] -0.3872983 -0.3872983 -0.3872983
## [3,]  0.3872983  0.3872983  0.3872983
## [4,]  1.1618950  1.1618950  1.1618950

NB: for this simple example the same result can of course be achieved more easily by
apply(dataPoints, 2, scale)

Can I edit an iPad's host file?

The easiest way to do this is to run an iPad simulator using XCode and then add an entry in the hosts file (/etc/hosts) on the host system to point to your test site.

Ruby: character to ascii from a string

use "x".ord for a single character or "xyz".sum for a whole string.

Why is `input` in Python 3 throwing NameError: name... is not defined

I'd say the code you need is:

test = input("enter the test")
print(test)

Otherwise it shouldn't run at all, due to a syntax error. The print function requires brackets in python 3. I cannot reproduce your error, though. Are you sure it's those lines causing that error?

Change color of Back button in navigation bar

self.navigationController?.navigationBar.tintColor = UIColor.redColor()

This snippet does the magic. Instead of the redColor, change it to as your wish.

Common MySQL fields and their appropriate data types

In my experience, first name/last name fields should be at least 48 characters -- there are names from some countries such as Malaysia or India that are very long in their full form.

Phone numbers and postcodes you should always treat as text, not numbers. The normal reason given is that there are postcodes that begin with 0, and in some countries, phone numbers can also begin with 0. But the real reason is that they aren't numbers -- they're identifiers that happen to be made up of numerical digits (and that's ignoring countries like Canada that have letters in their postcodes). So store them in a text field.

In MySQL you can use VARCHAR fields for this type of information. Whilst it sounds lazy, it means you don't have to be too concerned about the right minimum size.

How do I rotate the Android emulator display?

I have checked on Windows: Ctrl + F11 and Ctrl + F12 both are working to change the orientation of the Android simulator.

For other shortcut keys:

In the Eclipse toolbar go to "Help-->key Assist.. "

You can also use Ctrl + Shift + L here, so many shortcut keys of Eclipse are given.

Can you issue pull requests from the command line on GitHub?

UPDATE: The hub command is now an official github project and also supports creating pull requests

ORIGINAL:

Seems like a particularly useful thing to add to the hub command: http://github.com/defunkt/hub or the github gem: http://github.com/defunkt/github-gem

I suggest filing an issue with those projects asking for it. The github guys are pretty responsive.

What represents a double in sql server?

Also, here is a good answer for SQL-CLR Type Mapping with a useful chart.

From that post (by David): enter image description here

Windows could not start the Apache2 on Local Computer - problem

Run the httpd.exe from the command line, as Tim mentioned. The path to PostgreSQL changed, nothing else was running on Port 80 and I didn't see anything in the error.log file.

I clone my boot drive/partition once the base is setup so I don't have to spend three days installing and retweaking everything. Turns I had reinstalled my WAPP stack and used very specific names/versions for PostgreSQL. Windows will not return a specific error message unless you run the command from the command line.

What is a good alternative to using an image map generator?

I have found Adobe Dreamweaver to be quite good at that. However, it's not free.

move a virtual machine from one vCenter to another vCenter

A much simpler way to do this is to use vCenter Converter Standalone Client and do a P2V but in this case a V2V. It is much faster than copying the entire VM files onto some storage somewhere and copy it onto your new vCenter. It takes a long time to copy or exporting it to an OVF template and then import it. You can set your vCenter Converter Standalone Client to V2V in one step and synchronize and then have it power up the VM on the new Vcenter and shut off on the old vCenter. Simple.

For me using this method I was able to move a VM from one vCenter to another vCenter in about 30 minutes as compared to copying or exporting which took over 2hrs. Your results may vary.


This process below, from another responder, would work even better if you can present that datastore to ESXi servers on the vCenter and then follow step 2. Eliminating having to copy all the VMs then follow rest of the process.

  1. Copy all of the cloned VM's files from its directory, and place it on its destination datastore.
  2. In the VI client connected to the destination vCenter, go to the Inventory->Datastores view.
  3. Open the datastore browser for the datastore where you placed the VM's files.
  4. Find the .vmx file that you copied over and right-click it.
  5. Choose 'Register Virtual Machine', and follow whatever prompts ensue. (Depending on your version of vCenter, this may be 'Add to Inventory' or some other variant)

Is it valid to have a html form inside another html form?

rather use a custom javascript-method inside the action attribute of the form!

eg

<html>
    <head>
        <script language="javascript" type="text/javascript">
        var input1 = null;
        var input2 = null;
        function InitInputs() {
            if (input1 == null) {
                input1 = document.getElementById("input1");
            }
            if (input2 == null) {
                input2 = document.getElementById("input2");
            }

            if (input1 == null) {
                alert("input1 missing");
            }
            if (input2 == null) {
                alert("input2 missing");
            }
        }
        function myMethod1() {
            InitInputs();
            alert(input1.value + " " + input2.value);
        }
        function myMethod2() {
            InitInputs();
            alert(input1.value);
        }
        </script>
    </head>
    <body>
        <form action="javascript:myMethod1();">
            <input id="input1" type="text" />
            <input id="input2" type="text" />
            <input type="button" onclick="myMethod2()" value="myMethod2"/>
            <input type="submit" value="myMethod1" />
        </form>
    </body>
</html>

How to make a JFrame button open another JFrame class in Netbeans?

new SecondForm().setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

How to create a unique index on a NULL column?

It is possible to use filter predicates to specify which rows to include in the index.

From the documentation:

WHERE <filter_predicate> Creates a filtered index by specifying which rows to include in the index. The filtered index must be a nonclustered index on a table. Creates filtered statistics for the data rows in the filtered index.

Example:

CREATE TABLE Table1 (
  NullableCol int NULL
)

CREATE UNIQUE INDEX IX_Table1 ON Table1 (NullableCol) WHERE NullableCol IS NOT NULL;

How can I get a Unicode character's code?

dear friend, Jon Skeet said you can find character Decimal codebut it is not character Hex code as it should mention in unicode, so you should represent character codes via HexCode not in Deciaml.

there is an open source tool at http://unicode.codeplex.com that provides complete information about a characer or a sentece.

so it is better to create a parser that give a char as a parameter and return ahexCode as string

public static String GetHexCode(char character)
    {
        return String.format("{0:X4}", GetDecimal(character));
    }//end

hope it help

What's the difference between HEAD, working tree and index, in Git?

This is an inevitably long yet easy to follow explanation from ProGit book:

Note: For reference you can read Chapter 7.7 of the book, Reset Demystified

Git as a system manages and manipulates three trees in its normal operation:

  • HEAD: Last commit snapshot, next parent
  • Index: Proposed next commit snapshot
  • Working Directory: Sandbox

The HEAD

HEAD is the pointer to the current branch reference, which is in turn a pointer to the last commit made on that branch. That means HEAD will be the parent of the next commit that is created. It’s generally simplest to think of HEAD as the snapshot of your last commit on that branch.

What does it contain?
To see what that snapshot looks like run the following in root directory of your repository:

                                 git ls-tree -r HEAD

it would result in something like this:

                       $ git ls-tree -r HEAD  
                       100644 blob a906cb2a4a904a152... README  
                       100644 blob 8f94139338f9404f2... Rakefile  
                       040000 tree 99f1a6d12cb4b6f19... lib  

The Index

Git populates this index with a list of all the file contents that were last checked out into your working directory and what they looked like when they were originally checked out. You then replace some of those files with new versions of them, and git commit converts that into the tree for a new commit.

What does it contain?
Use git ls-files -s to see what it looks like. You should see something like this:

                 100644 a906cb2a4a904a152e80877d4088654daad0c859 0 README   
                 100644 8f94139338f9404f26296befa88755fc2598c289 0 Rakefile  
                 100644 47c6340d6459e05787f644c2447d2595f5d3a54b 0 lib/simplegit.rb  

The Working Directory

This is where your files reside and where you can try changes out before committing them to your staging area (index) and then into history.

Visualized Sample

Let's see how do these three trees (As the ProGit book refers to them) work together?
Git’s typical workflow is to record snapshots of your project in successively better states, by manipulating these three trees. Take a look at this picture:

enter image description here

To get a good visualized understanding consider this scenario. Say you go into a new directory with a single file in it. Call this v1 of the file. It is indicated in blue. Running git init will create a Git repository with a HEAD reference which points to the unborn master branch

enter image description here

At this point, only the working directory tree has any content. Now we want to commit this file, so we use git add to take content in the working directory and copy it to the index.

enter image description here

Then we run git commit, which takes the contents of the index and saves it as a permanent snapshot, creates a commit object which points to that snapshot, and updates master to point to that commit.

enter image description here

If we run git status, we’ll see no changes, because all three trees are the same.

The beautiful point

git status shows the difference between these trees in the following manner:

  • If the Working Tree is different from index, then git status will show there are some changes not staged for commit
  • If the Working Tree is the same as index, but they are different from HEAD, then git status will show some files under changes to be committed section in its result
  • If the Working Tree is different from the index, and index is different from HEAD, then git status will show some files under changes not staged for commit section and some other files under changes to be committed section in its result.

For the more curious

Note about git reset command
Hopefully, knowing how reset command works will further brighten the reason behind the existence of these three trees.

reset command is your Time Machine in git which can easily take you back in time and bring some old snapshots for you to work on. In this manner, HEAD is the wormhole through which you can travel in time. Let's see how it works with an example from the book:

Consider the following repository which has a single file and 3 commits which are shown in different colours and different version numbers:

enter image description here

The state of trees is like the next picture:

enter image description here

Step 1: Moving HEAD (--soft):

The first thing reset will do is move what HEAD points to. This isn’t the same as changing HEAD itself (which is what checkout does). reset moves the branch that HEAD is pointing to. This means if HEAD is set to the master branch, running git reset 9e5e6a4 will start by making master point to 9e5e6a4. If you call reset with --soft option it will stop here, without changing index and working directory. Our repo will look like this now:
Notice: HEAD~ is the parent of HEAD

enter image description here

Looking a second time at the image, we can see that the command essentially undid the last commit. As the working tree and the index are the same but different from HEAD, git status will now show changes in green ready to be committed.

Step 2: Updating the index (--mixed):

This is the default option of the command

Running reset with --mixed option updates the index with the contents of whatever snapshot HEAD points to currently, leaving Working Directory intact. Doing so, your repository will look like when you had done some work that is not staged and git status will show that as changes not staged for commit in red. This option will also undo the last commit and also unstage all the changes. It's like you made changes but have not called git add command yet. Our repo would look like this now:

enter image description here

Step 3: Updating the Working Directory (--hard)

If you call reset with --hard option it will copy contents of the snapshot HEAD is pointing to into HEAD, index and Working Directory. After executing reset --hard command, it would mean like you got back to a previous point in time and haven't done anything after that at all. see the picture below:

enter image description here

Conclusion

I hope now you have a better understanding of these trees and have a great idea of the power they bring to you by enabling you to change your files in your repository to undo or redo things you have done mistakenly.

Is it possible to get a history of queries made in postgres

Not logging but if you're troubleshooting slow running queries in realtime, you can query the pg_stat_activity view to see which queries are active, the user/connection they came from, when they started, etc. Eg...

SELECT *
FROM pg_stat_activity
WHERE state = 'active'

See the pg_stat_activity view docs.

What is the best way to connect and use a sqlite database from C#

Here I am trying to help you do the job step by step: (this may be the answer to other questions)

  1. Go to this address , down the page you can see something like "List of Release Packages". Based on your system and .net framework version choose the right one for you. for example if your want to use .NET Framework 4.6 on a 64-bit Windows, choose this version and download it.
  2. Then install the file somewhere on your hard drive, just like any other software.
  3. Open Visual studio and your project. Then in solution explorer, right-click on "References" and choose "add Reference...".
  4. Click the browse button and choose where you install the previous file and go to .../bin/System.Data.SQLite.dll and click add and then OK buttons.

that is pretty much it. now you can use SQLite in your project. to use it in your project on the code level you may use this below example code:

  1. make a connection string:

    string connectionString = @"URI=file:{the location of your sqlite database}";

  2. establish a sqlite connection:

    SQLiteConnection theConnection = new SQLiteConnection(connectionString );

  3. open the connection:

    theConnection.Open();

  4. create a sqlite command:

    SQLiteCommand cmd = new SQLiteCommand(theConnection);

  5. Make a command text, or better said your SQLite statement:

    cmd.CommandText = "INSERT INTO table_name(col1, col2) VALUES(val1, val2)";

  6. Execute the command

    cmd.ExecuteNonQuery();

that is it.

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

The mysql_install_db script also needs the datadir parameter:

mysql_install_db --user=root --datadir=$db_datapath

On Maria DB you use the install script mysql_install_db to install and initialize. In my case I use an environment variable for the data path. Not only does mysqld need to know where the data is (specified via commandline), but so does the install script.

Why use multiple columns as primary keys (composite primary key)

The W3Schools example isn't saying when you should use compound primary keys, and is only giving example syntax using the same example table as for other keys.

Their choice of example is perhaps misleading you by combining a meaningless key (P_Id) and a natural key (LastName). This odd choice of primary key says that the following rows are valid according to the schema and are necessary to uniquely identify a student. Intuitively this doesn't make sense.

1234     Jobs
1234     Gates

Further Reading: The great primary-key debate or just Google meaningless primary keys or even peruse this SO question

FWIW - My 2 cents is to avoid multi-column primary keys and use a single generated id field (surrogate key) as the primary key and add additional (unique) constraints where necessary.

CSS table layout: why does table-row not accept a margin?

If you want a specific margin e.g. 20px, you can put the table inside a div.

<div id="tableDiv">
    <table>
      <tr>
        <th> test heading </th>
      </tr>
      <tr>
        <td> test data </td>
      </tr>
    </table>
</div>

So the #tableDiv has a margin of 20px but the table itself has a width of 100%, forcing the table to be the full width except for the margin on either sides.

#tableDiv {
  margin: 20px;
}

table {
  width: 100%;
}

How to count the number of rows in excel with data?

Dim RowNumber As Integer
RowNumber = ActiveSheet.Range("A65536").End(xlUp).Row

In your case it should return #9

How to format a number as percentage in R?

You can use the scales package just for this operation (without loading it with require or library)

scales::percent(m)

How to tell if UIViewController's view is visible

There are a couple of issues with the above solutions. If you are using, for example, a UISplitViewController, the master view will always return true for

if(viewController.isViewLoaded && viewController.view.window) {
    //Always true for master view in split view controller
}

Instead, take this simple approach which seems to work well in most, if not all cases:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    //We are now invisible
    self.visible = false;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //We are now visible
    self.visible = true;
}

Running script upon login mac

Follow this:

  • start Automator.app
  • select Application
  • click Show library in the toolbar (if hidden)
  • add Run shell script (from the Actions/Utilities)
  • copy & paste your script into the window
  • test it
  • save somewhere (for example you can make an Applications folder in your HOME, you will get an your_name.app)

  • go to System Preferences -> Accounts -> Login items

  • add this app
  • test & done ;)

EDIT:

I've recently earned a "Good answer" badge for this answer. While my solution is simple and working, the cleanest way to run any program or shell script at login time is described in @trisweb's answer, unless, you want interactivity.

With automator solution you can do things like next: automator screenshot login application

so, asking to run a script or quit the app, asking passwords, running other automator workflows at login time, conditionally run applications at login time and so on...

Linux command line howto accept pairing for bluetooth device without pin

This worked like a charm for me, of-course it requires super-user privileges :-)

# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>

To get <target-bdaddr> you may issue below command:
$ hcitool scan

Note: Exclude # & $ as they are command line prompts.

Courtesy

How to compile C++ under Ubuntu Linux?

g++ is the C++ compiler under linux. The code looks right. It is possible that you are missing a library reference which is used as such:

g++ -l{library name here (math fns use "m")} codefile.cpp

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.

import java.text.SimpleDateFormat;
import java.util.Date;

public class test {
    public static void main(String argv[]){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date now = new Date();
        String strDate = sdf.format(now);
        System.out.println(strDate);
    }
}

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

What is the difference between Scala's case class and class?

Technically, there is no difference between a class and a case class -- even if the compiler does optimize some stuff when using case classes. However, a case class is used to do away with boiler plate for a specific pattern, which is implementing algebraic data types.

A very simple example of such types are trees. A binary tree, for instance, can be implemented like this:

sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[A](value: A) extends Tree
case object EmptyLeaf extends Tree

That enable us to do the following:

// DSL-like assignment:
val treeA = Node(EmptyLeaf, Leaf(5))
val treeB = Node(Node(Leaf(2), Leaf(3)), Leaf(5))

// On Scala 2.8, modification through cloning:
val treeC = treeA.copy(left = treeB.left)

// Pretty printing:
println("Tree A: "+treeA)
println("Tree B: "+treeB)
println("Tree C: "+treeC)

// Comparison:
println("Tree A == Tree B: %s" format (treeA == treeB).toString)
println("Tree B == Tree C: %s" format (treeB == treeC).toString)

// Pattern matching:
treeA match {
  case Node(EmptyLeaf, right) => println("Can be reduced to "+right)
  case Node(left, EmptyLeaf) => println("Can be reduced to "+left)
  case _ => println(treeA+" cannot be reduced")
}

// Pattern matches can be safely done, because the compiler warns about
// non-exaustive matches:
def checkTree(t: Tree) = t match {
  case Node(EmptyLeaf, Node(left, right)) =>
  // case Node(EmptyLeaf, Leaf(el)) =>
  case Node(Node(left, right), EmptyLeaf) =>
  case Node(Leaf(el), EmptyLeaf) =>
  case Node(Node(l1, r1), Node(l2, r2)) =>
  case Node(Leaf(e1), Leaf(e2)) =>
  case Node(Node(left, right), Leaf(el)) =>
  case Node(Leaf(el), Node(left, right)) =>
  // case Node(EmptyLeaf, EmptyLeaf) =>
  case Leaf(el) =>
  case EmptyLeaf =>
}

Note that trees construct and deconstruct (through pattern match) with the same syntax, which is also exactly how they are printed (minus spaces).

And they can also be used with hash maps or sets, since they have a valid, stable hashCode.

AngularJS Multiple ng-app within a page

Here's an example of two applications in one html page and two conrollers in one application :

    <div ng-app = "myapp">
      <div  ng-controller = "C1" id="D1">
         <h2>controller 1 in app 1 <span id="titre">{{s1.title}}</span> !</h2>
      </div>

      <div  ng-controller = "C2" id="D2">
         <h2>controller 2 in app 1 <span id="titre">{{s2.valeur}}</span> !</h2>
      </div>
    </div>
    <script>
        var A1 = angular.module("myapp", [])

        A1.controller("C1", function($scope) {
            $scope.s1 = {};
            $scope.s1.title = "Titre 1";
         });

        A1.controller("C2", function($scope) {
            $scope.s2 = {};
            $scope.s2.valeur = "Valeur 2";
         });
    </script>

    <div ng-app="toapp" ng-controller="C1" id="App2">
        <br>controller 1 in app 2
        <br>First Name: <input type = "text" ng-model = "student.firstName">
        <br>Last Name : <input type="text" ng-model="student.lastName">
        <br>Hello : {{student.fullName()}}
        <br>
    </div>

    <script>
        var A2 = angular.module("toapp", []);
        A2.controller("C1", function($scope) {
            $scope.student={
                firstName:"M",
                lastName:"E",
                fullName:function(){
                    var so=$scope.student;
                    return so.firstName+" "+so.lastName;
                }
            };
        });
        angular.bootstrap(document.getElementById("App2"), ['toapp']);
    </script>
<style>
    #titre{color:red;}
    #D1{ background-color:gray; width:50%; height:20%;}
    #D2{ background-color:yellow; width:50%; height:20%;}
    input{ font-weight: bold; }
</style>

How to set div's height in css and html

To write inline styling use:

<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>

Inline styling serves a purpose however, it is not recommended in most situations.

The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.

if you have the file structure:

index.html
>>/css/
>>/css/styles.css

Then in your HTML document between <head> and </head> write:

<link href="css/styles.css" rel="stylesheet" />

Then, change your div structure to be:

<div id="someidname" class="someclassname">
    asdfashdjkfhaskjdf
</div>

In css, you can reference your div from the ID or the CLASS.

To do so write:

.someclassname { height: 100px; }

OR

#someidname { height: 100px; }

Note that if you do both, the one that comes further down the file structure will be the one that actually works.

For example... If you have:

.someclassname { height: 100px; }

.someclassname { height: 150px; }

Then in this situation the height will be 150px.

EDIT:

To answer your secondary question from your edit, probably need overflow: hidden; or overflow: visible; . You could also do this:

<div class="span12">
    <div style="height:100px;">
        asdfashdjkfhaskjdf
    </div>
</div>

How to delete from select in MySQL?

If you want to delete all duplicates, but one out of each set of duplicates, this is one solution:

DELETE posts
FROM posts
LEFT JOIN (
    SELECT id
    FROM posts
    GROUP BY id
    HAVING COUNT(id) = 1

    UNION

    SELECT id
    FROM posts
    GROUP BY id
    HAVING COUNT(id) != 1
) AS duplicate USING (id)
WHERE duplicate.id IS NULL;

Android scale animation on view

In XML, this what I use for achieving the same result. May be this is more intuitive.

scale_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

<scale
    android:duration="200"
    android:fromXScale="1.0"
    android:fromYScale="0.0"
    android:pivotX="50%"
    android:pivotY="100%"
    android:toXScale="1.0"
    android:toYScale="1.0" />

</set>

scale_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

<scale
    android:duration="200"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:pivotX="50%"
    android:pivotY="100%"
    android:toXScale="1.0"
    android:toYScale="0.0" />

</set>

See the animation on the X axis is from 1.0 -> 1.0 which means you don't have any scaling up in that direction and stays at the full width while, on the Y axis you get 0.0 -> 1.0 scaling, as shown in the graphic in the question. Hope this helps someone.

Some might want to know the java code as we see one requested.

Place the animation files in anim folder and then load and set animation files something like.

Animation scaleDown = AnimationUtils.loadAnimation(youContext, R.anim.scale_down);
ImagView v = findViewById(R.id.your_image_view);
v.startAnimation(scaleDown);

CSS3 animate border color

If you need the transition to run infinitely, try the below example:

_x000D_
_x000D_
#box {_x000D_
  position: relative;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: gray;_x000D_
  border: 5px solid black;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#box:hover {_x000D_
  border-color: red;_x000D_
  animation-name: flash_border;_x000D_
  animation-duration: 2s;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-name: flash_border;_x000D_
  -webkit-animation-duration: 2s;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
  -moz-animation-name: flash_border;_x000D_
  -moz-animation-duration: 2s;_x000D_
  -moz-animation-timing-function: linear;_x000D_
  -moz-animation-iteration-count: infinite;_x000D_
}_x000D_
_x000D_
@keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-moz-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}
_x000D_
<div id="box">roll over me</div>
_x000D_
_x000D_
_x000D_

Get integer value of the current year in Java

In my case none of the above is worked. So After trying lot of solutions i found below one and it worked for me

import java.util.Scanner;
import java.util.Date;

public class Practice
{   
    public static void main(String[] args)
    {
        Date d=new Date();  
        int year=d.getYear();
        int currentYear=year+1900;    

        System.out.println(currentYear);

    }

}

Setting up SSL on a local xampp/apache server

I did all of the suggested stuff here and my code still did not work because I was using curl

If you are using curl in the php file, curl seems to reject all ssl traffic by default. A quick-fix that worked for me was to add:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

before calling:

 curl_exec():

in the php file.

I believe that this disables all verification of SSL certificates.

Set value to currency in <input type="number" />

In the end I made a jQuery plugin that will format the <input type="number" /> appropriately for me. I also noticed on some mobile devices the min and max attributes don't actually prevent you from entering lower or higher numbers than specified, so the plugin will account for that too. Below is the code and an example:

_x000D_
_x000D_
(function($) {_x000D_
  $.fn.currencyInput = function() {_x000D_
    this.each(function() {_x000D_
      var wrapper = $("<div class='currency-input' />");_x000D_
      $(this).wrap(wrapper);_x000D_
      $(this).before("<span class='currency-symbol'>$</span>");_x000D_
      $(this).change(function() {_x000D_
        var min = parseFloat($(this).attr("min"));_x000D_
        var max = parseFloat($(this).attr("max"));_x000D_
        var value = this.valueAsNumber;_x000D_
        if(value < min)_x000D_
          value = min;_x000D_
        else if(value > max)_x000D_
          value = max;_x000D_
        $(this).val(value.toFixed(2)); _x000D_
      });_x000D_
    });_x000D_
  };_x000D_
})(jQuery);_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('input.currency').currencyInput();_x000D_
});
_x000D_
.currency {_x000D_
  padding-left:12px;_x000D_
}_x000D_
_x000D_
.currency-symbol {_x000D_
  position:absolute;_x000D_
  padding: 2px 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="number" class="currency" min="0.01" max="2500.00" value="25.00" />
_x000D_
_x000D_
_x000D_

Android camera intent

Try the following I found here

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Django: List field in model?

If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine library, there is a built in ListField that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.

How can I perform a reverse string search in Excel without using VBA?

I found this on google, tested in Excel 2003 & it works for me:

=IF(COUNTIF(A1,"* *"),RIGHT(A1,LEN(A1)-LOOKUP(LEN(A1),FIND(" ",A1,ROW(INDEX($A:$A,1,1):INDEX($A:$A,LEN(A1),1))))),A1)

[edit] I don't have enough rep to comment, so this seems the best place...BradC's answer also doesn't work with trailing spaces or empty cells...
[2nd edit] actually, it doesn't work for single words either...

How to find if element with specific id exists or not

Use typeof for elements checks.

if(typeof(element) === 'undefined')
{
// then field does not exist
}

Get full path of the files in PowerShell

I am using below script to extact all folder path:

Get-ChildItem -path "C:\" -Recurse -Directory -Force -ErrorAction SilentlyContinue | Select-Object FullName | Out-File "Folder_List.csv"

Full folder path is not coming. After 113 characters, is coming:

Example - C:\ProgramData\Microsoft\Windows\DeviceMetadataCache\dmrccache\en-US\ec4d5fdd-aa12-400f-83e2-7b0ea6023eb7\Windows...

getResources().getColor() is deprecated

well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor function. You can get current theme with getTheme().

This will do the trick in fragment, you can replace getActivity() with getBaseContext(), yourContext, etc which hold your current context

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}

*p.s : color is deprecated in M, but drawable is deprecated in L

How exactly does the python any() function work?

(x > 0 for x in list) in that function call creates a generator expression eg.

>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
        print x


True
True
False
True
False

Which any uses, and shortcircuits on encountering the first object that evaluates True

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

I think the point of those different types of logging is if you want your app to basically self filter its own logs. So Verbose could be to log absolutely everything of importance in your app, then the debug level would log a subset of the verbose logs, and then Info level will log a subset of the debug logs. When you get down to the Error logs, then you just want to log any sort of errors that may have occured. There is also a debug level called Fatal for when something really hits the fan in your app.

In general, you're right, it's basically arbitrary, and it's up to you to define what is considered a debug log versus informational, versus and error, etc. etc.

Using PHP Replace SPACES in URLS with %20

    public static function normalizeUrl(string $url) {
        $parts = parse_url($url);
        return $parts['scheme'] .
            '://' .
            $parts['host'] .
            implode('/', array_map('rawurlencode', explode('/', $parts['path'])));

    }

stop all instances of node.js server

If you are using Windows, follow this:

  1. Open task manager, look for this process: Task manager showing Node process - Node.js Server-side JavaScript

  2. Then just right click and "End task" it.

  3. That's it, now all the npm commands run form the start.

How do I make bootstrap table rows clickable?

That code transforms any bootstrap table row that has data-href attribute set into a clickable element

Note: data-href attribute is a valid tr attribute (HTML5), href attributes on tr element are not.

$(function(){
    $('.table tr[data-href]').each(function(){
        $(this).css('cursor','pointer').hover(
            function(){ 
                $(this).addClass('active'); 
            },  
            function(){ 
                $(this).removeClass('active'); 
            }).click( function(){ 
                document.location = $(this).attr('data-href'); 
            }
        );
    });
});

! [rejected] master -> master (fetch first)

First, You should use git pull, then command do a git fetch and next do the git merge.

If you use a git push origin master --force command, you may have problems in the future.

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

go to iis -> application pools -> find your application pool used in application

enter image description here

select your application pool used for the application right click select advanced settings

enter image description here

Select application pool identity enter image description here

select built in as Local System and click ok

See whether an item appears more than once in a database column

How about:

select salesid from AXDelNotesNoTracking group by salesid having count(*) > 1;

How to change the style of alert box?

I tried to use script for alert() boxes styles using java-script.Here i used those JS and CSS.

Refer this coding JS functionality.

var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";

if(document.getElementById) {
    window.alert = function(txt) {
        createCustomAlert(txt);
    }
}

function createCustomAlert(txt) {
    d = document;

    if(d.getElementById("modalContainer")) return;

    mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
    mObj.id = "modalContainer";
    mObj.style.height = d.documentElement.scrollHeight + "px";

    alertObj = mObj.appendChild(d.createElement("div"));
    alertObj.id = "alertBox";
    if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
    alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
    alertObj.style.visiblity="visible";

    h1 = alertObj.appendChild(d.createElement("h1"));
    h1.appendChild(d.createTextNode(ALERT_TITLE));

    msg = alertObj.appendChild(d.createElement("p"));
    //msg.appendChild(d.createTextNode(txt));
    msg.innerHTML = txt;

    btn = alertObj.appendChild(d.createElement("a"));
    btn.id = "closeBtn";
    btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
    btn.href = "#";
    btn.focus();
    btn.onclick = function() { removeCustomAlert();return false; }

    alertObj.style.display = "block";

}

function removeCustomAlert() {
    document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}

And CSS for alert() Box

#modalContainer {
    background-color:rgba(0, 0, 0, 0.3);
    position:absolute;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
    z-index:10000;
    background-image:url(tp.png); /* required by MSIE to prevent actions on lower z-index elements */
}

#alertBox {
    position:relative;
    width:300px;
    min-height:100px;
    margin-top:50px;
    border:1px solid #666;
    background-color:#fff;
    background-repeat:no-repeat;
    background-position:20px 30px;
}

#modalContainer > #alertBox {
    position:fixed;
}

#alertBox h1 {
    margin:0;
    font:bold 0.9em verdana,arial;
    background-color:#3073BB;
    color:#FFF;
    border-bottom:1px solid #000;
    padding:2px 0 2px 5px;
}

#alertBox p {
    font:0.7em verdana,arial;
    height:50px;
    padding-left:5px;
    margin-left:55px;
}

#alertBox #closeBtn {
    display:block;
    position:relative;
    margin:5px auto;
    padding:7px;
    border:0 none;
    width:70px;
    font:0.7em verdana,arial;
    text-transform:uppercase;
    text-align:center;
    color:#FFF;
    background-color:#357EBD;
    border-radius: 3px;
    text-decoration:none;
}

/* unrelated styles */

#mContainer {
    position:relative;
    width:600px;
    margin:auto;
    padding:5px;
    border-top:2px solid #000;
    border-bottom:2px solid #000;
    font:0.7em verdana,arial;
}

h1,h2 {
    margin:0;
    padding:4px;
    font:bold 1.5em verdana;
    border-bottom:1px solid #000;
}

code {
    font-size:1.2em;
    color:#069;
}

#credits {
    position:relative;
    margin:25px auto 0px auto;
    width:350px; 
    font:0.7em verdana;
    border-top:1px solid #000;
    border-bottom:1px solid #000;
    height:90px;
    padding-top:4px;
}

#credits img {
    float:left;
    margin:5px 10px 5px 0px;
    border:1px solid #000000;
    width:80px;
    height:79px;
}

.important {
    background-color:#F5FCC8;
    padding:2px;
}

code span {
    color:green;
}

And HTML file:

<input type="button" value = "Test the alert" onclick="alert('Alert this pages');" />

And also View this DEMO: JSFIDDLE and DEMO RESULT IMAGE

enter image description here

"No backupset selected to be restored" SQL Server 2012

For me, it was because the backup file was still open by another process. Here's the event log:

BackupDiskFile::OpenMedia: Backup device 'X:\Backups\MyDatabase\MyDatabase_backup_2014_08_22_132234_8270986.bak' failed to open. Operating system error 32(The process cannot access the file because it is being used by another process.).

Simply closing and reopening Sql Server Management Studio resolved it (so obviously it was ssms.exe that had the handle..)

ArrayList initialization equivalent to array initialization

Yes.

new ArrayList<String>(){{
   add("A");
   add("B");
}}

What this is actually doing is creating a class derived from ArrayList<String> (the outer set of braces do this) and then declare a static initialiser (the inner set of braces). This is actually an inner class of the containing class, and so it'll have an implicit this pointer. Not a problem unless you want to serialise it, or you're expecting the outer class to be garbage collected.

I understand that Java 7 will provide additional language constructs to do precisely what you want.

EDIT: recent Java versions provide more usable functions for creating such collections, and are worth investigating over the above (provided at a time prior to these versions)

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

std::string + const char* results in another std::string. system does not take a std::string, and you cannot concatenate char*'s with the + operator. If you want to use the code this way you will need:

std::string name = "john";
std::string tmp = 
    "quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '" + 
    name + ".jpg'";
system(tmp.c_str());

See std::string operator+(const char*)

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

It could be due to the architecture of your OS. Is your OS 64 Bit and have you installed 64 bit version of Python? It may help to install both 32 bit version Python 3.1 and Pygame, which is available officially only in 32 bit and you won't face this problem.

I see that 64 bit pygame is maintained here, you might also want to try uninstalling Pygame only and install the 64 bit version on your existing python3.1, if not choose go for both 32-bit version.

Creating stored procedure with declare and set variables

I assume you want to pass the Order ID in. So:

CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

How does a Java HashMap handle different objects with the same hash code?

It gonna be a long answer , grab a drink and read on …

Hashing is all about storing a key-value pair in memory that can be read and written faster. It stores keys in an array and values in a LinkedList .

Lets Say I want to store 4 key value pairs -

{
“girl” => “ahhan” , 
“misused” => “Manmohan Singh” , 
“horsemints” => “guess what”, 
“no” => “way”
}

So to store the keys we need an array of 4 element . Now how do I map one of these 4 keys to 4 array indexes (0,1,2,3)?

So java finds the hashCode of individual keys and map them to a particular array index . Hashcode Formulae is -

1) reverse the string.

2) keep on multiplying ascii of each character with increasing power of 31 . then add the components .

3) So hashCode() of girl would be –(ascii values of  l,r,i,g are 108, 114, 105 and 103) . 

e.g. girl =  108 * 31^0  + 114 * 31^1  + 105 * 31^2 + 103 * 31^3  = 3173020

Hash and girl !! I know what you are thinking. Your fascination about that wild duet might made you miss an important thing .

Why java multiply it with 31 ?

It’s because, 31 is an odd prime in the form 2^5 – 1 . And odd prime reduces the chance of Hash Collision

Now how this hash code is mapped to an array index?

answer is , Hash Code % (Array length -1) . So “girl” is mapped to (3173020 % 3) = 1 in our case . which is second element of the array .

and the value “ahhan” is stored in a LinkedList associated with array index 1 .

HashCollision - If you try to find hasHCode of the keys “misused” and “horsemints” using the formulae described above you’ll see both giving us same 1069518484. Whooaa !! lesson learnt -

2 equal objects must have same hashCode but there is no guarantee if the hashCode matches then the objects are equal . So it should store both values corresponding to “misused” and “horsemints” to bucket 1 (1069518484 % 3) .

Now the hash map looks like –

Array Index 0 –
Array Index 1 - LinkedIst (“ahhan” , “Manmohan Singh” , “guess what”)
Array Index 2 – LinkedList (“way”)
Array Index 3 – 

Now if some body tries to find the value for the key “horsemints” , java quickly will find the hashCode of it , module it and start searching for it’s value in the LinkedList corresponding index 1 . So this way we need not search all the 4 array indexes thus making data access faster.

But , wait , one sec . there are 3 values in that linkedList corresponding Array index 1, how it finds out which one was was the value for key “horsemints” ?

Actually I lied , when I said HashMap just stores values in LinkedList .

It stores both key value pair as map entry. So actually Map looks like this .

Array Index 0 –
Array Index 1 - LinkedIst (<”girl” => “ahhan”> , <” misused” => “Manmohan Singh”> , <”horsemints” => “guess what”>)
Array Index 2 – LinkedList (<”no” => “way”>)
Array Index 3 – 

Now you can see While traversing through the linkedList corresponding to ArrayIndex1 it actually compares key of each entry to of that LinkedList to “horsemints” and when it finds one it just returns the value of it .

Hope you had fun while reading it :)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

Just putting .encode('utf-8') at the end of object will do the job in recent versions of Python.

How to detect incoming calls, in an Android device?

With Android P - Api Level 28: You need to get READ_CALL_LOG permission

Restricted access to call logs

Android P moves the CALL_LOG, READ_CALL_LOG, WRITE_CALL_LOG, and PROCESS_OUTGOING_CALLS permissions from the PHONE permission group to the new CALL_LOG permission group. This group gives users better control and visibility to apps that need access to sensitive information about phone calls, such as reading phone call records and identifying phone numbers.

To read numbers from the PHONE_STATE intent action, you need both the READ_CALL_LOG permission and the READ_PHONE_STATE permission. To read numbers from onCallStateChanged(), you now need the READ_CALL_LOG permission only. You no longer need the READ_PHONE_STATE permission.

How to have css3 animation to loop forever

Whilst Elad's solution will work, you can also do it inline:

   -moz-animation: fadeinphoto 7s 20s infinite;
-webkit-animation: fadeinphoto 7s 20s infinite;
     -o-animation: fadeinphoto 7s 20s infinite;
        animation: fadeinphoto 7s 20s infinite;

How to convert string to double with proper cultureinfo

Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture

TryParse does not allway work as we would expect There are change request in .net in this area:

https://github.com/dotnet/runtime/issues/25868

Remove Last Comma from a string

long shot here

var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true)  {    
  currentIndex=pattern.lastIndex;
 }
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
 alert(sentence);

how to change language for DataTable

If you are using Angular and Firebase, you can also use the DTOptionsBuilder :

angular.module('your_module', [
'ui.router',
'oc.lazyLoad',
'ui.bootstrap',
'ngSanitize',
'firebase']).controller("your_controller", function ($scope, $firebaseArray, DTOptionsBuilder) {

var ref = firebase.database().ref().child("your_database_table");

// create a synchronized array
$scope.your_database_table = $firebaseArray(ref);

ref.on('value', snap => {

    $scope.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('language',
        {
            "sProcessing": "Traitement en cours...",
            "sSearch": "Rechercher&nbsp;:",
            "sLengthMenu": "Afficher _MENU_ &eacute;l&eacute;ments",
            "sInfo": "Affichage de l'&eacute;l&eacute;ment _START_ &agrave; _END_ sur _TOTAL_ &eacute;l&eacute;ments",
            "sInfoEmpty": "Affichage de l'&eacute;l&eacute;ment 0 &agrave; 0 sur 0 &eacute;l&eacute;ment",
            "sInfoFiltered": "(filtr&eacute; de _MAX_ &eacute;l&eacute;ments au total)",
            "sInfoPostFix": "",
            "sLoadingRecords": "Chargement en cours...",
            "sZeroRecords": "Aucun &eacute;l&eacute;ment &agrave; afficher",
            "sEmptyTable": "Aucune donn&eacute;e disponible dans le tableau",
            "oPaginate": {
                "sFirst": "Premier",
                "sPrevious": "Pr&eacute;c&eacute;dent",
                "sNext": "Suivant",
                "sLast": "Dernier"
            },
            "oAria": {
                "sSortAscending": ": activer pour trier la colonne par ordre croissant",
                "sSortDescending": ": activer pour trier la colonne par ordre d&eacute;croissant"
            }
        }
        )

});})

I hope this will help.

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

The patch is here: https://code.ros.org/trac/opencv/attachment/ticket/862/OpenCV-2.2-nov4l1.patch

By adding #ifdef HAVE_CAMV4L around

#include <linux/videodev.h>

in OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp and removing || defined (HAVE_CAMV4L2) from line 174 allowed me to compile.

How to increase buffer size in Oracle SQL Developer to view all records?

press f5 for running queries instead of f9. It will give you all the results in one go...

how to put focus on TextBox when the form load?

The reason you can't get it to work is because the Load event is called before the form is drawn or rendered.

It like telling a pizza place how to make your pizza, and then asking them to send you a picture of how much pepperoni is on your pizza before they made it.

using System;
using System.Windows.Forms;

namespace Testing
{
    public partial class TestForm : Form
    {
        public TestForm()
        {
            InitializeComponent();

            Load += TestForm_Load;

            VisibleChanged += TestForm_VisibleChanged;

            Shown += TestForm_Shown;

            Show();

        }

        private void TestForm_Load(object sender, EventArgs e)
        {
            MessageBox.Show("This event is called before the form is rendered.");
        }

        private void TestForm_VisibleChanged(object sender, EventArgs e)
        {
            MessageBox.Show("This event is called before the form is rendered.");
        }

        private void TestForm_Shown(object sender, EventArgs e)
        {
            MessageBox.Show("This event is called after the form is rendered.");
            txtFirstName.Focus();
        }
    }
}

Display rows with one or more NaN values in pandas dataframe

You can use DataFrame.any with parameter axis=1 for check at least one True in row by DataFrame.isna with boolean indexing:

df1 = df[df.isna().any(axis=1)]

d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')

print (df)
                             alpha1  alpha2    gamma1    gamma2       chi2min
filename                                                                     
M66_MI_NSRh35d32kpoints.dat  0.8016  0.9283  1.000000  0.074804  3.985599e+01
F71_sMI_DMRI51d.dat          0.0000  0.0000       NaN  0.000000  1.000000e+25
F62_sMI_St22d7.dat           1.7210  3.8330  0.237480  0.150000  1.091832e+01
F41_Car_HOC498d.dat          1.1670  2.8090  0.364190  0.300000  7.966335e+00
F78_MI_547d.dat              1.8970  5.4590  0.095319       NaN  2.593468e+01

Explanation:

print (df.isna())
                            alpha1 alpha2 gamma1 gamma2 chi2min
filename                                                       
M66_MI_NSRh35d32kpoints.dat  False  False  False  False   False
F71_sMI_DMRI51d.dat          False  False   True  False   False
F62_sMI_St22d7.dat           False  False  False  False   False
F41_Car_HOC498d.dat          False  False  False  False   False
F78_MI_547d.dat              False  False  False   True   False

print (df.isna().any(axis=1))
filename
M66_MI_NSRh35d32kpoints.dat    False
F71_sMI_DMRI51d.dat             True
F62_sMI_St22d7.dat             False
F41_Car_HOC498d.dat            False
F78_MI_547d.dat                 True
dtype: bool

df1 = df[df.isna().any(axis=1)]
print (df1)
                     alpha1  alpha2    gamma1  gamma2       chi2min
filename                                                           
F71_sMI_DMRI51d.dat   0.000   0.000       NaN     0.0  1.000000e+25
F78_MI_547d.dat       1.897   5.459  0.095319     NaN  2.593468e+01

Windows 8.1 gets Error 720 on connect VPN

Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:

why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.

Solution:

  1. check write permissions on registers

    a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it

    b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log

    c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"

    d. run the following command netsh int ipv6 reset reset.log and repeat step c)

  2. unistall all not-working miniports

    a. go to device managers (windows+x -> device manager)

    b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)

    c. unistall these not working devices

    d. reboot your computer

    e. Repeat steps a) - d) until you will not see any yellow mark on miniports

  3. delete your vpn connection and create a new one.

that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)

references:

http://en.remontka.pro/error-720-windows-8-and-8-1-solved/

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

MySQL select where column is not empty

SELECT phone, phone2 
FROM jewishyellow.users 
WHERE phone like '813%' and (phone2 <> "");

May need some tweakage depending on what your default value is. If you allowed Null fill, then you can do "Not NULL" instead, which is obviously better.

How to parse a CSV file using PHP

A bit shorter answer since PHP >= 5.3.0:

    $csvFile = file('../somefile.csv');
    $data = [];
    foreach ($csvFile as $line) {
        $data[] = str_getcsv($line);
    }

Shell script to capture Process ID and kill it if exist

You probably wanted to write

`ps -ef | grep syncapp | awk '{print $2}'`

but I will endorse @PaulR's answer - killall -9 syncapp is a much better alternative.

How to get the query string by javascript?

If you're referring to the URL in the address bar, then

window.location.search

will give you just the query string part. Note that this includes the question mark at the beginning.

If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:

url.substring(url.indexOf("?"))

That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.

How to vertically align text with icon font?

Adding to the spans

vertical-align:baseline;

Didn't work for me but

vertical-align:baseline;
vertical-align:-webkit-baseline-middle;

did work (tested on Chrome)

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){

convert string to date in sql server

if you datatype is datetime of the table.col , then database store data contain two partial : 1 (date) 2 (time)

Just in display data use convert or cast.

Example:

create table #test(part varchar(10),lastTime datetime)
go

insert into #test (part ,lastTime )
values('A','2012-11-05 ')

insert into #test (part ,lastTime )
values('B','2012-11-05 10:30')


go

select * from #test 

A   2012-11-05 00:00:00.000
B   2012-11-05 10:30:00.000

select part,CONVERT (varchar,lastTime,111) from #test

A   2012/11/05
B   2012/11/05

select part,CONVERT (varchar(10),lastTime,20) from #test 

A   2012-11-05
B   2012-11-05

In VBA get rid of the case sensitivity when comparing words?

It is a bit of hack but will do the task.

Function equalsIgnoreCase(str1 As String, str2 As String) As Boolean
    equalsIgnoreCase = LCase(str1) = LCase(str2)
End Function

How to sort a list of strings numerically?

Python's sort isn't weird. It's just that this code:

for item in list1:
   item=int(item)

isn't doing what you think it is - item is not replaced back into the list, it is simply thrown away.

Anyway, the correct solution is to use key=int as others have shown you.

Get IP address of visitors using Flask for Python

I have Nginx and With below Nginx Config:

server {
    listen 80;
    server_name xxxxxx;
    location / {
               proxy_set_header   Host                 $host;
               proxy_set_header   X-Real-IP            $remote_addr;
               proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
               proxy_set_header   X-Forwarded-Proto    $scheme;

               proxy_pass http://x.x.x.x:8000;
        }
}

@tirtha-r solution worked for me

#!flask/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/', methods=['GET'])
def get_tasks():
    if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
        return jsonify({'ip': request.environ['REMOTE_ADDR']}), 200
    else:
        return jsonify({'ip': request.environ['HTTP_X_FORWARDED_FOR']}), 200

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port=8000)

My Request and Response:

curl -X GET http://test.api

{
    "ip": "Client Ip......"
}

How to read numbers separated by space using scanf

I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.

scanf("%d %d %d", &var1, &var2, &var3);

Similarly if you want to read comma separated values use :

scanf("%d,%d,%d", &var1, &var2, &var3);

Cannot make a static reference to the non-static method

Since getText() is non-static you cannot call it from a static method.

To understand why, you have to understand the difference between the two.

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass();

To call an instance method, you call it on the instance (myObject):

myObject.getText(...)

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

... = SomeClass.final

And the two cannot work together as they operate on different data spaces (instance data and class data)

Let me try and explain. Consider this class (psuedocode):

class Test {
     string somedata = "99";
     string getText() { return somedata; } 
     static string TTT = "0";
}

Now I have the following use case:

Test item1 = new Test();
 item1.somedata = "200";

 Test item2 = new Test();

 Test.TTT = "1";

What are the values?

Well

in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test {
         string somedata = "99";
         string getText() { return somedata; } 
  static string TTT = getText(); // error there is is no somedata at this point 
}

So the question is why is TTT static or why is getText() not static?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

If you are enabled minifyEnabled and shrinkResources to true in your app gradle file. You need to add the following line in proguard-rules.pro file

-keep class com.yourpackage_name.** { *; }

because minification is removed some important classes in our apk file.

How to know the version of pip itself

First, open a command prompt After type a bellow commands.

check a version itself Easily :

Form Windows:

pip installation :

pip install pip

pip Version check:

pip --version 

Processing Symbol Files in Xcode

Annoying error. I solved it by plugging the cable directly into the iPad. For some reason the process would never finish if I had the iPad in Apple's pass-through stand.

Produce a random number in a range using C#

You can try

Random r = new Random();
int rInt = r.Next(0, 100); //for ints
int range = 100;
double rDouble = r.NextDouble()* range; //for doubles

Have a look at

Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method

Android - Pulling SQlite database android device

Most of the answers here are way more complicated than they have to be. If you just want to copy the database of your app from your phone to your computer then you just need this command:

adb -d shell "run-as your.package.name cat databases/database.name" > target.sqlite

All you need to fill in in the above command is the package name of your app, what the database is called and optionally what/where you want the database to be copied to.

Please note that this specific command will only work if you have only one device connected to your computer. The -d parameter means that the only connected device will be targeted. But there are other parameters which you can use instead:

  • -e will target the only running emulator
  • -s <serialnumber> will target a device with a specific serial number.

Getting the current date in visual Basic 2008

If you need exact '/' delimiters, for example: 09/20/2013 rather than 09.20.2013, use escape sequence '/':

Dim regDate As Date = Date.Now()
Dim strDate As String = regDate.ToString("MM\/dd\/yyyy")

How to programmatically add controls to a form in VB.NET

You can get your Button1 location and than increase the Y value every time you click on it.

Public Class Form1
    Dim BtnCoordinate As Point
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim btn As Button = New Button
        BtnCoordinate.Y += Button1.Location.Y + 4
        With btn
            .Location = New Point(BtnCoordinate)
            .Text = TextBox1.Text
            .ForeColor = Color.Black
        End With
        Me.Controls.Add(btn)
        Me.StartPosition = FormStartPosition.CenterScreen
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Button1Coordinate = Button1.Location
    End Sub
End Class

If statement with String comparison fails

Strings in java are objects, so when comparing with ==, you are comparing references, rather than values. The correct way is to use equals().

However, there is a way. If you want to compare String objects using the == operator, you can make use of the way the JVM copes with strings. For example:

String a = "aaa";
String b = "aaa";
boolean b = a == b;

b would be true. Why?

Because the JVM has a table of String constants. So whenever you use string literals (quotes "), the virtual machine returns the same objects, and therefore == returns true.

You can use the same "table" even with non-literal strings by using the intern() method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:

String a = new String("aa");
String b = new String("aa");
boolean check1 = a == b; // false
boolean check1 = a.intern() == b.intern(); // true

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

Select records from NOW() -1 Day

Sure you can:

SELECT * FROM table
WHERE DateStamp > DATE_ADD(NOW(), INTERVAL -1 DAY)

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

Chart.js - Formatting Y axis

As Nevercom said the scaleLable should contain javascript so to manipulate the y value just apply the required formatting.

Note the the value is a string.

var options = {      
    scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>"
};

jsFiddle example

if you wish to set a manual y scale you can use scaleOverride

var options = {      
    scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>",

    scaleOverride: true,
    scaleSteps: 10,
    scaleStepWidth: 10,
    scaleStartValue: 0

};

jsFiddle example

Using LIMIT within GROUP BY to get N results per group?

Took some working, but I thougth my solution would be something to share as it is seems elegant as well as quite fast.

SELECT h.year, h.id, h.rate 
  FROM (
    SELECT id, 
      SUBSTRING_INDEX(GROUP_CONCAT(CONCAT(id, '-', year) ORDER BY rate DESC), ',' , 5) AS l
      FROM h
      WHERE year BETWEEN 2000 AND 2009
      GROUP BY id
      ORDER BY id
  ) AS h_temp
    LEFT JOIN h ON h.id = h_temp.id 
      AND SUBSTRING_INDEX(h_temp.l, CONCAT(h.id, '-', h.year), 1) != h_temp.l

Note that this example is specified for the purpose of the question and can be modified quite easily for other similar purposes.

jQuery and AJAX response header

+1 to PleaseStand and here is my other hack:

after searching and found that the "cross ajax request" could not get response headers from XHR object, I gave up. and use iframe instead.

1. <iframe style="display:none"></iframe>
2. $("iframe").attr("src", "http://the_url_you_want_to_access")
//this is my aim!!!
3. $("iframe").contents().find('#someID').html()  

Getting user input

Use the raw_input() function to get input from users (2.x):

print "Enter a file name:",
filename = raw_input()

or just:

filename = raw_input('Enter a file name: ')

or if in Python 3.x:

filename = input('Enter a file name: ')

How to find EOF through fscanf?

fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF.

You should check for EOF when you call fscanf, not check the array slot for EOF.

Java Garbage Collection Log messages

I just wanted to mention that one can get the detailed GC log with the

-XX:+PrintGCDetails 

parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.

Also -Xloggc:gc.log seems to generate the same output like -verbose:gc but you can specify an output file in the first.

Example usage:

java -Xloggc:./memory.log -XX:+PrintGCDetails Memory

To visualize the data better you can try gcviewer (a more recent version can be found on github).

Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!

Datatables - Setting column width

I have tried in many ways. The only way that worked for me was:

The Yush0 CSS solution:

#yourTable{
    table-layout: fixed !important;
    word-wrap:break-word;
}

Together with Roy Jackson HTML Solution:

    <th style='width: 5%;'>ProjectId</th>
    <th style='width: 15%;'>Title</th>
    <th style='width: 40%;'>Abstract</th>
    <th style='width: 20%;'>Keywords</th>
    <th style='width: 10%;'>PaperName</th>
    <th style='width: 10%;'>PaperURL</th>
</tr>

How do I copy items from list to list without foreach?

And this is if copying a single property to another list is needed:

targetList.AddRange(sourceList.Select(i => i.NeededProperty));

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

if (combo1.SelectedIndex > -1)
{
    // do something
}

if any item is selected selected index will be greater than -1

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

Outline effect to text

Working with thicker strokes gets a bit messy, if you have the pleasure of sass try this mixin, not perfect and depending on stroke weight it generates a fair amount of css.

 @mixin stroke($width, $colour: #000000) {
      $shadow: 0 0 0 $colour; // doesn't do anything but I couldn't work out how to create a blank string and maintain commas
      @for $i from 0 through $width {
          $shadow: $shadow,
          -$i + px -$width + px 0 $colour,
          $i + px -$width + px 0 $colour,
          -$i + px $width + px 0 $colour,
          $i + px $width + px 0 $colour,
          -$width + px -$i + px 0 $colour,
          $width + px -$i + px 0 $colour,
          -$width + px $i + px 0 $colour,
          $width + px $i + px 0 $colour,
      }
      text-shadow: $shadow;
}

How to iterate std::set?

You must dereference the iterator in order to retrieve the member of your set.

std::set<unsigned long>::iterator it;
for (it = SERVER_IPS.begin(); it != SERVER_IPS.end(); ++it) {
    u_long f = *it; // Note the "*" here
}

If you have C++11 features, you can use a range-based for loop:

for(auto f : SERVER_IPS) {
  // use f here
}    

Regular expression to extract numbers from a string

if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use

\d+

jQuery Scroll To bottom of the page

something like this:

var $target = $('html,body'); 
$target.animate({scrollTop: $target.height()}, 1000);

How to set selectedIndex of select element using display text?

<script type="text/javascript">
     function SelectAnimal(){
         //Set selected option of Animals based on AnimalToFind value...
         var animalTofind = document.getElementById('AnimalToFind');
         var selection = document.getElementById('Animals');

        // select element
        for(var i=0;i<selection.options.length;i++){
            if (selection.options[i].innerHTML == animalTofind.value) {
                selection.selectedIndex = i;
                break;
            }
        }
     }
</script>

setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces

selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;

or using .match(/regular expression/)

ssl.SSLError: tlsv1 alert protocol version

For Mac OS X

1) Update to Python 3.6.5 using the native app installer downloaded from the official Python language website https://www.python.org/downloads/

I've found that the installer is taking care of updating the links and symlinks for the new Python a lot better than homebrew.

2) Install a new certificate using "./Install Certificates.command" which is in the refreshed Python 3.6 directory

> cd "/Applications/Python 3.6/"
> sudo "./Install Certificates.command"

How to get the next auto-increment id in mysql

You can use

SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'table_name'
AND table_schema = DATABASE( ) ;

or if you do not wish to use information_schema you can use this

SHOW TABLE STATUS LIKE 'table_name'

Where does linux store my syslog?

On my Ubuntu machine, I can see the output at /var/log/syslog.

On a RHEL/CentOS machine, the output is found in /var/log/messages.

This is controlled by the rsyslog service, so if this is disabled for some reason you may need to start it with systemctl start rsyslog.

As noted by others, your syslog() output would be logged by the /var/log/syslog file.
You can see system, user, and other logs at /var/log.

For more details: here's an interesting link.

What does the variable $this mean in PHP?

when you create a class you have (in many cases) instance variables and methods (aka. functions). $this accesses those instance variables so that your functions can take those variables and do what they need to do whatever you want with them.

another version of meder's example:

class Person {

    protected $name;  //can't be accessed from outside the class

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}
// this line creates an instance of the class Person setting "Jack" as $name.  
// __construct() gets executed when you declare it within the class.
$jack = new Person("Jack"); 

echo $jack->getName();

Output:

Jack

How to display Woocommerce Category image?

get_woocommerce_term_meta is depricated since Woo 3.6.0.

so change

$thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );

into: ($value->term_id should be woo category id)

get_term_meta($value->term_id, 'thumbnail_id', true)

see docs for details: https://docs.woocommerce.com/wc-apidocs/function-get_woocommerce_term_meta.html

include antiforgerytoken in ajax post ASP.NET MVC

I know this is an old question. But I will add my answer anyway, might help someone like me.

If you dont want to process the result from the controller's post action, like calling the LoggOff method of Accounts controller, you could do as the following version of @DarinDimitrov 's answer:

@using (Html.BeginForm("LoggOff", "Accounts", FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<!-- this could be a button -->
<a href="#" id="ajaxSubmit">Submit</a>

<script type="text/javascript">
    $('#ajaxSubmit').click(function () {

        $('#__AjaxAntiForgeryForm').submit();

        return false;
    });
</script>

Adding form action in html in laravel

{{ Form::open(array('action' => "WelcomeController@log_in")) }}
...
{{ Form::close() }}

How to stop java process gracefully?

Here is a bit tricky, but portable solution:

  • In your application implement a shutdown hook
  • When you want to shut down your JVM gracefully, install a Java Agent that calls System.exit() using the Attach API.

I implemented the Java Agent. It is available on Github: https://github.com/everit-org/javaagent-shutdown

Detailed description about the solution is available here: https://everitorg.wordpress.com/2016/06/15/shutting-down-a-jvm-process/

changing kafka retention period during runtime

The correct config key is retention.ms

$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".

Custom checkbox image android

If you have Android open source code, you can find the styles definition under:
src/frameworks/base/core/res/res/values

<style name="Widget.CompoundButton.CheckBox">
    <item name="android:background">
        @android:drawable/btn_check_label_background
    </item>
    <item name="android:button">
        ?android:attr/listChoiceIndicatorMultiple
    </item>
</style>

Installing Java 7 on Ubuntu

I think you should consider Java installation procedure carefully. Following is the detailed process which covers almost all possible failures.

Installing Java with apt-get is easy. First, update the package index:

sudo apt-get update

Then, check if Java is not already installed:

java -version

If it returns "The program java can be found in the following packages", Java hasn't been installed yet, so execute the following command:

sudo apt-get install default-jre

You are fine till now as I assume.

This will install the Java Runtime Environment (JRE). If you instead need the Java Development Kit (JDK), which is usually needed to compile Java applications (for example Apache Ant, Apache Maven, Eclipse and IntelliJ IDEA execute the following command:

sudo apt-get install default-jdk

That is everything that is needed to install Java.

Installing OpenJDK 7:

To install OpenJDK 7, execute the following command:

sudo apt-get install openjdk-7-jre 

This will install the Java Runtime Environment (JRE). If you instead need the Java Development Kit (JDK), execute the following command:

sudo apt-get install openjdk-7-jdk

Installing Oracle JDK:

The Oracle JDK is the official JDK; however, it is no longer provided by Oracle as a default installation for Ubuntu.

You can still install it using apt-get. To install any version, first execute the following commands:

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

Then, depending on the version you want to install, execute one of the following commands:

Oracle JDK 7:

sudo apt-get install oracle-java7-installer

Oracle JDK 8:

sudo apt-get install oracle-java8-installer

Read XLSX file in Java

I had to do this in .NET and I couldn't find any API's out there. My solution was to unzip the .xlsx, and dive right into manipulating the XML. It's not so bad once you create your helper classes and such.

There are some "gotchas" like the nodes all have to be sorted according to the way excel expects them, that I didn't find in the official docs. Excel has its own date timestamping, so you'll need to make a conversion formula.

how to draw directed graphs using networkx in python?

I only put this in for completeness. I've learned plenty from marius and mdml. Here are the edge weights. Sorry about the arrows. Looks like I'm not the only one saying it can't be helped. I couldn't render this with ipython notebook I had to go straight from python which was the problem with getting my edge weights in sooner.

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab

G = nx.DiGraph()

G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)
G.add_edges_from([('B','C'),('E','F')], weight=3)
G.add_edges_from([('C','F')], weight=4)


val_map = {'A': 1.0,
                   'D': 0.5714285714285714,
                              'H': 0.0}

values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v,),d['weight'])
                 for u,v,d in G.edges(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]

pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()

enter image description here

How to use android emulator for testing bluetooth application?

Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

Remove space above and below <p> tag HTML

<p> elements generally have margins and / or padding. You can set those to zero in a stylesheet.

li p {
    margin: 0;
    padding: 0;
}

Semantically speaking, however, it is fairly unusual to have a list of paragraphs.

adb command not found in linux environment

I was getting this error also and Ubuntu suggested me to install it so I installed* it and this worked in my case.
* - sudo apt-get install android-tools-adb

Note:x64 architecture

Scroll event listener javascript

Is there a js listener for when a user scrolls in a certain textbox that can be used?

DOM L3 UI Events spec gave the initial definition but is considered obsolete.

To add a single handler you can do:

  let isTicking;
  const debounce = (callback, evt) => {
    if (isTicking) return;
    requestAnimationFrame(() => {
      callback(evt);
      isTicking = false;
    });
    isTicking = true;
  };
  const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
  document.defaultView.onscroll = evt => debounce(handleScroll, evt);

For multiple handlers or, if preferable for style reasons, you may use addEventListener as opposed to assigning your handler to onscroll as shown above.

If using something like _.debounce from lodash you could probably get away with:

const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
document.defaultView.onscroll = evt => _.debounce(() => handleScroll(evt));

Review browser compatibility and be sure to test on some actual devices before calling it done.

Simple parse JSON from URL on Android and display in listview

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following


Async task has three primary methods:

  1. onPreExecute() - most commonly used for setting up and starting a progress dialog

  2. doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).

  3. onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.

First we will start the class, initialize a String to hold the results outside of the methods but inside the class, then run the onPreExecute() method setting up a simple progress dialog.

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Downloading your data...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

Then we need to set up the connection and how we want to handle the response:

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post

            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)

Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:

    protected void onPostExecute(Void v) {
        //parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);    
            for(i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");

            } // End Loop
            this.progressDialog.dismiss();
        } catch (JSONException e) {
            Log.e("JSONException", "Error: " + e.toString());
        } // catch (JSONException e)
    } // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>

Jquery Date picker Default Date

Use the defaultDate option

$( ".selector" ).datepicker({ defaultDate: '01/01/01' });

If you change your date format, make sure to change the input into defaultDate (e.g. '01-01-2001')

Java - Search for files in a directory

I have used a different approach to search for a file using stack.. keeping in mind that there could be folders inside a folder. Though its not faster than windows search(and I was not expecting that though) but it definitely gives out correct result. Please modify the code as you wish to. This code was originally made to extract the file path of certain file extension :). Feel free to optimize.

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Deepankar Sinha
 */
public class GetList {
    public List<String> stack;
    static List<String> lnkFile;
    static List<String> progName;

    int index=-1;
    public static void main(String args[]) throws IOException
    {

        //var-- progFile:Location of the file to be search. 
        String progFile="C:\\";
        GetList obj=new GetList();
        String temp=progFile;
        int i;
        while(!"&%@#".equals(temp))
        {
            File dir=new File(temp);
            String[] directory=dir.list();
            if(directory!=null){
            for(String name: directory)
            {
                if(new File(temp+name).isDirectory())
                    obj.push(temp+name+"\\");
                else
                    if(new File(temp+name).isFile())
                    {
                        try{
                            //".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
                        if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
                        {
                            //obj.addFile(temp+name,name);
                            System.out.println(temp+name);
                        }
                        }catch(StringIndexOutOfBoundsException e)
                        {
                            //debug purpose
                            System.out.println("ERROR******"+temp+name);
                        }

                    }
            }}
            temp=obj.pop();
        }
        obj.display();

//        for(int i=0;i<directory.length;i++)
//        System.out.println(directory[i]);
    }

    public GetList() {
        this.stack = new ArrayList<>();
        this.lnkFile=new ArrayList<>();
        this.progName=new ArrayList<>();
    }
    public void push(String dir)
    {
        index++;
        //System.out.println("PUSH : "+dir+" "+index);
        this.stack.add(index,dir);

    }
    public String pop()
    {
        String dir="";
        if(index==-1)
            return "&%@#";
        else
        {
            dir=this.stack.get(index);
            //System.out.println("POP : "+dir+" "+index);
            index--;

        }
        return dir;
    }

    public void addFile(String name,String name2)
    {
        lnkFile.add(name);
        progName.add(name2);
    }

    public void display()
    {
        GetList.lnkFile.stream().forEach((lnkFile1) -> {
            System.out.println(lnkFile1);
        });
    }

}

Android Studio: Default project directory

In android studio 2.3.3 (windows) you must go to C:\User\ (Name)\ .AndroidStudio2.3\config\option open recentProjects.xml And change your directory

<option name="lastProjectLocation" value="YOUR DIRECTORY" />

Where can I set path to make.exe on Windows?

The path is in the registry but usually you edit through this interface:

  1. Go to Control Panel -> System -> System settings -> Environment Variables.
  2. Scroll down in system variables until you find PATH.
  3. Click edit and change accordingly.
  4. BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2
  5. Launch a new console for the settings to take effect.

For..In loops in JavaScript - key value pairs

If you can use ES6 natively or with Babel (js compiler) then you could do the following:

_x000D_
_x000D_
const test = {a: 1, b: 2, c: 3};_x000D_
_x000D_
for (const [key, value] of Object.entries(test)) {_x000D_
  console.log(key, value);_x000D_
}
_x000D_
_x000D_
_x000D_

Which will print out this output:

a 1
b 2
c 3

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Hope it helps! =)

Can I escape a double quote in a verbatim string literal?

There is a proposal open in GitHub for the C# language about having better support for raw string literals. One valid answer, is to encourage the C# team to add a new feature to the language (such as triple quote - like Python).

see https://github.com/dotnet/csharplang/discussions/89#discussioncomment-257343

How to show "Done" button on iPhone number pad

Below is an overhaul of Luda's answer with the following changes:

  • the accessory view is automatically sized to the width of the application frame

  • the deprecated constant UIBarButtonItemStyleBordered is avoided

  • the "Done" button is instantiated as a UIBarButtonSystemItemDone

Currently the "Done" button is centered in the accessory view. You can position it at left or right by deleting the space on the pertinent side.

I have omitted a "Cancel" button because the default keyboard doesn't have one either. If you do want a "Cancel" button, I suggest that you instantiate it as a UIBarButtonSystemItemCancel and that you make sure you're not discarding the original value in your text field. The "Cancel" behavior implemented in Luda's answer, which overwrites the value with a blank string, may not be what you want.

- (void)viewDidLoad {
  [super viewDidLoad];
  float appWidth = CGRectGetWidth([UIScreen mainScreen].applicationFrame);
  UIToolbar *accessoryView = [[UIToolbar alloc]
                              initWithFrame:CGRectMake(0, 0, appWidth, 0.1 * appWidth)];
  UIBarButtonItem *space = [[UIBarButtonItem alloc]
                            initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                            target:nil
                            action:nil];
  UIBarButtonItem *done = [[UIBarButtonItem alloc]
                           initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                           target:self
                           action:@selector(selectDoneButton)];
  accessoryView.items = @[space, done, space];
  self.valueField.inputAccessoryView = accessoryView;
}

- (void)selectDoneButton {
  [self.valueField resignFirstResponder];
}

For more information about building accessory views, see the Apple documentation on custom views for data input. You will probably want to consult the reference pages on UIToolbar and UIBarButtonItem as well.

HTML Mobile -forcing the soft keyboard to hide

Those answers aren't bad, but they are limited in that they don't actually allow you to enter data. We had a similar problem where we were using barcode readers to enter data into a field, but we wanted to suppress the keyboard.

This is what I put together, it works pretty well:

https://codepen.io/bobjase/pen/QrQQvd/

<!-- must be a select box with no children to suppress the keyboard -->
input: <select id="hiddenField" /> 
<span id="fakecursor" />

<input type="text" readonly="readonly" id="visibleField" />
<div id="cursorMeasuringDiv" />

#hiddenField {
  height:17px; 
  width:1px;
  position:absolute;
  margin-left:3px;
  margin-top:2px;
  border:none;
  border-width:0px 0px 0px 1px;
}

#cursorMeasuringDiv {
  position:absolute;
  visibility:hidden;
  margin:0px;
  padding:0px;
}

#hiddenField:focus {
  border:1px solid gray;  
  border-width:0px 0px 0px 1px;
  outline:none;
  animation-name: cursor;
  animation-duration: 1s;
  animation-iteration-count: infinite;
}

@keyframes cursor {
    from {opacity:0;}
    to {opacity:1;}
}

// whenever the visible field gets focused
$("#visibleField").bind("focus", function(e) {
  // silently shift the focus to the hidden select box
  $("#hiddenField").focus();
  $("#cursorMeasuringDiv").css("font", $("#visibleField").css("font"));
});

// whenever the user types on his keyboard in the select box
// which is natively supported for jumping to an <option>
$("#hiddenField").bind("keypress",function(e) {
  // get the current value of the readonly field
  var currentValue = $("#visibleField").val();

  // and append the key the user pressed into that field
  $("#visibleField").val(currentValue + e.key);
  $("#cursorMeasuringDiv").text(currentValue + e.key);

  // measure the width of the cursor offset
  var offset = 3;
  var textWidth = $("#cursorMeasuringDiv").width();
  $("#hiddenField").css("marginLeft",Math.min(offset+textWidth,$("#visibleField").width()));

});

When you click in the <input> box, it simulates a cursor in that box but really puts the focus on an empty <select> box. Select boxes naturally allow for keypresses to support jumping to an element in the list so it was only a matter of rerouting the keypress to the original input and offsetting the simulated cursor.

This won't work for backspace, delete, etc... but we didn't need those. You could probably use jQuery's trigger to send the keyboard event directly to another input box somewhere but we didn't need to bother with that so I didn't do it.

Getting index value on razor foreach

In case you want to count the references from your model( ie: Client has Address as reference so you wanna count how many address would exists for a client) in a foreach loop at your view such as:

 @foreach (var item in Model)
                        {
                            <tr>
                                <td>
                                    @Html.DisplayFor(modelItem => item.DtCadastro)
                                </td>

                                <td style="width:50%">
                                    @Html.DisplayFor(modelItem => item.DsLembrete)
                                </td>
                                <td>
                                    @Html.DisplayFor(modelItem => item.DtLembrete)
                                </td>
                                <td>
                                    @{ 
                                        var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();
                                    }
                                    <button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
                                    <button class="btn-link associar" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Create/@item.IdLembrete"><i class="fas fa-plus"></i></button>
                                </td>
                                <td class="text-right">
                                    <button class="btn-link delete" data-id="@item.IdLembrete" data-path="/Lembretes/Delete/@item.IdLembrete">Excluir</button>
                                </td>
                            </tr>
                        }

do as coded:

@{ var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();}

and use it like this:

<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>

ps: don't forget to add INCLUDE to that reference at you DbContext inside, for example, your Index action controller, in case this is an IEnumerable model.

VBA Go to last empty row

This does it:

Do
   c = c + 1
Loop While Cells(c, "A").Value <> ""

'prints the last empty row
Debug.Print c

How do I select last 5 rows in a table without sorting?

The way your question is phrased makes it sound like you think you have to physically resort the data in the table in order to get it back in the order you want. If so, this is not the case, the ORDER BY clause exists for this purpose. The physical order in which the records are stored remains unchanged when using ORDER BY. The records are sorted in memory (or in temporary disk space) before they are returned.

Note that the order that records get returned is not guaranteed without using an ORDER BY clause. So, while any of the the suggestions here may work, there is no reason to think they will continue to work, nor can you prove that they work in all cases with your current database. This is by design - I am assuming it is to give the database engine the freedom do as it will with the records in order to obtain best performance in the case where there is no explicit order specified.

Assuming you wanted the last 5 records sorted by the field Name in ascending order, you could do something like this, which should work in either SQL 2000 or 2005:

select Name 
from (
    select top 5 Name 
    from MyTable 
    order by Name desc
) a 
order by Name asc

"pip install unroll": "python setup.py egg_info" failed with error code 1

That means some packages in pip are old or not correctly installed.

  1. Try checking version and then upgrading pip.Use auto remove if that works.

  2. If the pip command shows an error all the time for any command or it freezes, etc.

  3. The best solution is to uninstall it or remove it completely.

  4. Install a fresh pip and then update and upgrade your system.

  5. I have given a solution to installing pip fresh here - python: can't open file get-pip.py error 2] no such file or directory

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

How to set UTF-8 encoding for a PHP file

Html:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="x" content="xx" />

vs Php:

<?php header('Content-type: text/html; charset=ISO-8859-1'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta name="x" content="xx" />

Auto Increment after delete in MySQL

Its definitely not recommendable. If you have a large database with multiple tables, you may probably have saved a userid as id in table 2. if you rearrange table 1 then probably the intended userid will not end up being the intended table 2 id.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

For Intellij Idea sometime localhost.log file generated at different location. For e.g. you can find it at homedirectory\ .IntelliJIdea14\system\tomcat.

IF you are using spring then start ur server in debug mode and put debug point in catch block of org.springframework.context.support.AbstractApplicationContext's refresh() method. If bean creation fails you would be able to see the exception.

How to disable all div content

Browsers tested: IE 9, Chrome, Firefox and jquery-1.7.1.min.js

    $(document).ready(function () {
        $('#chkDisableEnableElements').change(function () {
            if ($('#chkDisableEnableElements').is(':checked')) {
                enableElements($('#divDifferentElements').children());
            }
            else {
                disableElements($('#divDifferentElements').children());
            }
        });
    });

    function disableElements(el) {
        for (var i = 0; i < el.length; i++) {
            el[i].disabled = true;

            disableElements(el[i].children);
        }
    }

    function enableElements(el) {
        for (var i = 0; i < el.length; i++) {
            el[i].disabled = false;

            enableElements(el[i].children);
        }
    }

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

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

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

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

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

How do you create an asynchronous HTTP request in JAVA?

Apache HttpComponents also have an async http client now too:

/**
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpasyncclient</artifactId>
      <version>4.0-beta4</version>
    </dependency>
**/

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.protocol.HttpContext;

public class HttpTest {

  public static void main(final String[] args) throws Exception {

    final CloseableHttpAsyncClient httpclient = HttpAsyncClients
        .createDefault();
    httpclient.start();
    try {
      final Future<Boolean> future = httpclient.execute(
          HttpAsyncMethods.createGet("http://www.google.com/"),
          new MyResponseConsumer(), null);
      final Boolean result = future.get();
      if (result != null && result.booleanValue()) {
        System.out.println("Request successfully executed");
      } else {
        System.out.println("Request failed");
      }
      System.out.println("Shutting down");
    } finally {
      httpclient.close();
    }
    System.out.println("Done");
  }

  static class MyResponseConsumer extends AsyncCharConsumer<Boolean> {

    @Override
    protected void onResponseReceived(final HttpResponse response) {
    }

    @Override
    protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl)
        throws IOException {
      while (buf.hasRemaining()) {
        System.out.print(buf.get());
      }
    }

    @Override
    protected void releaseResources() {
    }

    @Override
    protected Boolean buildResult(final HttpContext context) {
      return Boolean.TRUE;
    }
  }
}

Abort a Git Merge

Truth be told there are many, many resources explaining how to do this already out on the web:

Git: how to reverse-merge a commit?

Git: how to reverse-merge a commit?

Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)

So I guess I'll just summarize some of these:

  1. git revert <merge commit hash>
    This creates an extra "revert" commit saying you undid a merge

  2. git reset --hard <commit hash *before* the merge>
    This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick them on to afterwards.

But honestly this guide here is better than anything I can explain, with diagrams! :)

How to set default value for HTML select?

You first need to add values to your select options and for easy targetting give the select itself an id.

Let's make option b the default:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.

Excel: Use a cell value as a parameter for a SQL query

The SQL is somewhat like the syntax of MS SQL.

SELECT * FROM [table$] WHERE *;

It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.

If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:

SELECT Name FROM [Users$] WHERE id = 1;

Hope this helps.

how to run or install a *.jar file in windows?

Open up a command prompt and type java -jar jbpm-installer-3.2.7.jar

Is there a “not in” operator in JavaScript for checking object properties?

As already said by Jordão, just negate it:

if (!(id in tutorTimes)) { ... }

Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example "valueOf" in tutorTimes returns true because it is defined in Object.prototype.

If you want to test if a property doesn't exist in the current object, use hasOwnProperty:

if (!tutorTimes.hasOwnProperty(id)) { ... }

Or if you might have a key that is hasOwnPropery you can use this:

if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }

How to pass a value from one Activity to another in Android?

Standard way of passing data from one activity to another:

If you want to send large number of data from one activity to another activity then you can put data in a bundle and then pass it using putExtra() method.

//Create the `intent`
 Intent i = new Intent(this, ActivityTwo.class);
String one="xxxxxxxxxxxxxxx";
String two="xxxxxxxxxxxxxxxxxxxxx";
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“ONE”, one);
bundle.putString(“TWO”, two);  
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);

otherwise you can use putExtra() directly with intent to send data and getExtra() to get data.

Intent i=new Intent(this, ActivityTwo.class);
i.putExtra("One",one);
i.putExtra("Two",two);
startActivity(i);

How to use environment variables in docker compose

add env to .env file

Such as

VERSION=1.0.0

then save it to deploy.sh

INPUTFILE=docker-compose.yml
RESULT_NAME=docker-compose.product.yml
NAME=test

prepare() {
        local inFile=$(pwd)/$INPUTFILE
        local outFile=$(pwd)/$RESULT_NAME
        cp $inFile $outFile
        while read -r line; do
            OLD_IFS="$IFS"
            IFS="="
            pair=($line)
            IFS="$OLD_IFS"
               sed -i -e "s/\${${pair[0]}}/${pair[1]}/g" $outFile
            done <.env
     }
       
deploy() {
        docker stack deploy -c $outFile $NAME
}

        
prepare
deploy
    

SQL Query for Logins

Select * From Master..SysUsers Where IsSqlUser = 1

How do you find the sum of all the numbers in an array in Java?

Use below logic:

static int sum()
     {
         int sum = 0; // initialize sum
         int i;

         // Iterate through all elements summing them up
         for (i = 0; i < arr.length; i++)
            sum +=  arr[i];

         return sum;
     }

jQuery get mouse position within an element

I would suggest this:

e.pageX - this.getBoundingClientRect().left

Why Doesn't C# Allow Static Methods to Implement an Interface?

Conceptually there is no reason why an interface could not define a contract that includes static methods.

For the current C# language implementation, the restriction is due to the allowance of inheritance of a base class and interfaces. If "class SomeBaseClass" implements "interface ISomeInterface" and "class SomeDerivedClass : SomeBaseClass, ISomeInterface" also implements the interface, a static method to implement an interface method would fail compile because a static method cannot have same signature as an instance method (which would be present in base class to implement the interface).

A static class is functionally identical to a singleton and serves the same purpose as a singleton with cleaner syntax. Since a singleton can implement an interface, interface implementations by statics are conceptually valid.

So it simply boils down to the limitation of C# name conflict for instance and static methods of the same name across inheritance. There is no reason why C# could not be "upgraded" to support static method contracts (interfaces).

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Using grep to search for a string that has a dot in it

Escape dot. Sample command will be.

grep '0\.00'

Setting a windows batch file variable to the day of the week

few more ways:

1.Robocopy not available in XP but can be downloaded form with win 2003 resource tool kit .Also might depend on localization:

@echo off
setlocal 
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * \ \ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
 set "dow=%%D"
 set "month=%%E"
 set "day=%%F"
 set "HH=%%G"
 set "MM=%%H"
 set "SS=%%I"
 set "year=%%J"
)

echo Day of the week: %dow%
endlocal

2.MAKECAB - works on every windows machine (but creates a small temp file).Function provided by carlos:

@Echo Off


Call :GetDate.Init
Rem :GetDate.Init should be called one time in the code before call to :Getdate
Call :GetDate
Echo weekday:%weekday%

Goto :EOF

:GetDate.Init
Set /A "jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12"
Set /A "mon=1,tue=2,wed=3,thu=4,fri=5,sat=6,sun=7"
(
Echo .Set InfHeader=""
Echo .Set InfSectionOrder=""
Echo .Set InfFooter="%%2"
Echo .Set InfFooter1=""
Echo .Set InfFooter2=""
Echo .Set InfFooter3=""
Echo .Set InfFooter4=""
Echo .Set Cabinet="OFF"
Echo .Set Compress="OFF"
Echo .Set DoNotCopyFiles="ON"
Echo .Set RptFileName="NUL"
) >"%Temp%\~foo.ddf"
Goto :Eof

:GetDate
Set "tf=%Temp%\~%random%"
Makecab /D InfFileName="%tf%" /F "%Temp%\~foo.ddf" >NUL
For /F "usebackq tokens=1-7 delims=: " %%a In ("%tf%") Do (
Set /A "year=%%g,month=%%b,day=1%%c-100,weekday=%%a"
Set /A "hour=1%%d-100,minute=1%%e-100,second=1%%f-100")
Del "%tf%" >NUL 2>&1
Goto :Eof

3.W32TM - uses command switches introduced in Vista so will not work on windows 2003/XP:

@echo off
setlocal
call :w32dow day_ow
echo %day_ow%
pause
exit /b 0
endlocal
:w32dow [RrnVar]
setlocal

rem :: prints the day of the week
rem :: works on Vista and above


rem :: getting ansi date ( days passed from 1st jan 1601 ) , timer server hour and current hour
FOR /F "tokens=4,5 delims=:( " %%D in ('w32tm /stripchart /computer:localhost  /samples:1  /period:1 /dataonly /packetinfo^|find "Transmit Timestamp:" ') do (
 set "ANSI_DATE=%%D"
 set  "TIMESERVER_HOURS=%%E"
)

set  "LOCAL_HOURS=%TIME:~0,2%"
if "%TIMESERVER_HOURS:~0,1%0" EQU "00" set TIMESERVER_HOURS=%TIMESERVER_HOURS:~1,1%
if "%LOCAL_HOURS:~0,1%0" EQU "00" set LOCAL_HOURS=%LOCAL_HOURS:~1,1%
set /a OFFSET=TIMESERVER_HOURS-LOCAL_HOURS

rem :: day of the week will be the modulus of 7 of local ansi date +1
rem :: we need need +1 because Monday will be calculated as 0
rem ::  1st jan 1601 was Monday

rem :: if abs(offset)>12 we are in different days with the time server

IF %OFFSET%0 GTR 120 set /a DOW=(ANSI_DATE+1)%%7+1
IF %OFFSET%0 LSS -120 set /a DOW=(ANSI_DATE-1)%%7+1
IF %OFFSET%0 LEQ 120 IF %OFFSET%0 GEQ -120 set /a DOW=ANSI_DATE%%7+1


rem echo Day of the week: %DOW% 
endlocal & if "%~1" neq "" (set "%~1=%DOW%") else echo %DOW%

4..bat/jscript hybrid (must be saved as .bat):

 @if (@x)==(@y) @end /***** jscript comment ******
 @echo off
 for /f  %%d in ('cscript //E:JScript //nologo "%~f0"') do echo %%d
 exit /b 0
 *****  end comment *********/
 WScript.Echo((new Date).getDay());

5..bat/vbscript hybrid (must be saved as .bat)

 :sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%\System32\doskey.exe '.exe >nul

'& echo/ 
'& for /f %%w in ('cscript /nologo /E:vbscript %~dpfn0') do echo day of the week %%w
'& echo/
'& del /q "'.exe" >nul 2>&1
'& exit /b

WScript.Echo Weekday(Date)
WScript.Quit

6.powershell can be downloaded from microsoft.Available by default in everything form win7 and above:

@echo off
setlocal
for /f %%d in ('"powershell (Get-Date).DayOfWeek.Value__"') do set dow=%%d

echo day of the week : %dow%
endlocal

7.WMIC already used as an answer but just want to have a full reference.And with cleared <CR>:

@echo off
setlocal
for /f "delims=" %%a in ('wmic path win32_localtime get dayofweek /format:list ') do for /f "delims=" %%d in ("%%a") do set %%d

echo day of the week : %dayofweek%
endlocal

9.Selfcompiled jscript.net (must be saved as .bat):

@if (@X)==(@Y) @end /****** silent line that start jscript comment ******

@echo off
::::::::::::::::::::::::::::::::::::
:::       compile the script    ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation

set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
    if exist "%%v\jsc.exe" (
        rem :: the javascript.net compiler
        set "jsc=%%~dpsnfxv\jsc.exe"
        goto :break_loop
    )
)
echo jsc.exe not found && exit /b 0
:break_loop


call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
:::       end of compilation    ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation

"%~n0.exe"

exit /b 0


****** end of jscript comment ******/
import System;
import System.IO;

var dt=DateTime.Now;
 Console.WriteLine(dt.DayOfWeek);

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

  1. The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.

  2. The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)


<div>
    <canvas id="chartDiv" height="400" width="600"></canvas>
    <div id="legendDiv"></div>
</div>

<script>
   var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "The Flash's Speed",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "Superman's Speed",
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
    document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>

Excel: last character/string match in a string

You could use this function I created to find the last instance of a string within a string.

Sure the accepted Excel formula works, but it's much too difficult to read and use. At some point you have to break out into smaller chunks so it's maintainable. My function below is readable, but that's irrelevant because you call it in a formula using named parameters. This makes using it simple.

Public Function FindLastCharOccurence(fromText As String, searchChar As String) As Integer
Dim lastOccur As Integer
lastOccur = -1
Dim i As Integer
i = 0
For i = Len(fromText) To 1 Step -1
    If Mid(fromText, i, 1) = searchChar Then
        lastOccur = i
        Exit For
    End If
Next i

FindLastCharOccurence = lastOccur
End Function

I use it like this:

=RIGHT(A2, LEN(A2) - FindLastCharOccurence(A2, "\"))