Programs & Examples On #Class dbi

Relative div height

The div take the height of its parent, but since it has no content (expecpt for your divs) it will only be as height as its content.

You need to set the height of the body and html:

HTML:

<div class="block12">
    <div class="block1">1</div>
    <div class="block2">2</div>
</div>
<div class="block3">3</div>

CSS:

body, html {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.block12 {
    width: 100%;
    height: 50%;
    background: yellow;
    overflow: auto;
}
.block1, .block2 {
    width: 50%;
    height: 100%;
    display: inline-block;
    margin-right: -4px;
    background: lightgreen;
}
.block2 { background: lightgray }
.block3 {
    width: 100%;
    height: 50%;
    background: lightblue;
}

And a JSFiddle

How to watch for a route change in AngularJS?

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //..do something
  //event.stopPropagation();  //if you don't want event to bubble up 
});

Update int column in table with unique incrementing values

You can try :

DECLARE @counter int
SET @counter = 0
UPDATE [table]
SET [column] = @counter, @counter = @counter + 1```

Is there functionality to generate a random character in Java?

   Random randomGenerator = new Random();

   int i = randomGenerator.nextInt(256);
   System.out.println((char)i);

Should take care of what you want, assuming you consider '0,'1','2'.. as characters.

Find what 2 numbers add to something and multiply to something

Here is how I would do that:

$sum = 5;
$product = 6;

$found = FALSE;
for ($a = 1; $a < $sum; $a++) {
  $b = $sum - $a;
  if ($a * $b == $product) {
    $found = TRUE;
    break;
  }
}

if ($found) {
  echo "The answer is a = $a, b = $b.";
} else {
  echo "There is no answer where a and b are both integers.";
}

Basically, start at $a = 1 and $b = $sum - $a, step through it one at a time since we know then that $a + $b == $sum is always true, and multiply $a and $b to see if they equal $product. If they do, that's the answer.

See it working

Whether that is the most efficient method is very much debatable.

Delete specific values from column with where condition?

UPDATE myTable 
   SET myColumn = NULL 
 WHERE myCondition

How to set a default Value of a UIPickerView

TL:DR version:

//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)

Either you didn't set your picker to select the row (which you say you seem to have done but anyhow):

- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated

OR you didn't use the the following method to get the selected item from your picker

- (NSInteger)selectedRowInComponent:(NSInteger)component

This will get the selected row as Integer from your picker and do as you please with it. This should do the trick for yah. Good luck.

Anyhow read the ref: https://developer.apple.com/documentation/uikit/uipickerview


EDIT:

An example of manually setting and getting of a selected row in a UIPickerView:

the .h file:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *picker;
    NSMutableArray *source;
}

@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;

-(void)pressed;

@end

the .m file:

#import "ViewController.h"

@interface ViewController ()

@end
@implementation ViewController

@synthesize picker;
@synthesize source;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

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

    self.view.backgroundColor = [UIColor yellowColor];

    self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];

    UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
    [pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
    pressme.backgroundColor = [UIColor lightGrayColor];
    [pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pressme];

    self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
    self.picker.delegate = self;
    self.picker.dataSource = self;
    [self.view addSubview:self.picker];

    //This is how you manually SET(!!) a selection!
    [self.picker selectRow:2 inComponent:0 animated:YES];
}

//logs the current selection of the picker manually
-(void)pressed
{
    //This is how you manually GET(!!) a selection
    int row = [self.picker selectedRowInComponent:0];

    NSLog(@"%@", [source objectAtIndex:row]);
}

- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    return [source count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    return [source objectAtIndex:row];
}

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{
//    NSLog(@"%@", [source objectAtIndex:row]);
}

@end

EDIT for Swift solution (Source: Dan Beaulieu's answer)

Define an Outlet:

@IBOutlet weak var pickerView: UIPickerView!  // for example

Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

If you inspect the Swift 2.0 framework you'll see .selectRow defined as:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

option clicking .selectRow in Xcode displays the following:

Getting the 'external' IP address in Java

An alternative solution is to execute an external command, obviously, this solution limits the portability of the application.

For example, for an application that runs on Windows, a PowerShell command can be executed through jPowershell, as shown in the following code:

public String getMyPublicIp() {
    // PowerShell command
    String command = "(Invoke-WebRequest ifconfig.me/ip).Content.Trim()";
    String powerShellOut = PowerShell.executeSingleCommand(command).getCommandOutput();

    // Connection failed
    if (powerShellOut.contains("InvalidOperation")) {
        powerShellOut = null;
    }
    return powerShellOut;
}

What are the alternatives now that the Google web search API has been deprecated?

I have just come across this from Common Crawl.

http://www.commoncrawl.org/

Might be the answer we are all looking for!!

How to make a div 100% height of the browser window

Here's a fix for the height.

In your CSS use:

#your-object: height: 100vh;

For browser that don't support vh-units, use modernizr.

Add this script (to add detection for vh-units)

// https://github.com/Modernizr/Modernizr/issues/572
// Similar to http://jsfiddle.net/FWeinb/etnYC/
Modernizr.addTest('cssvhunit', function() {
    var bool;
    Modernizr.testStyles("#modernizr { height: 50vh; }", function(elem, rule) {   
        var height = parseInt(window.innerHeight/2,10),
            compStyle = parseInt((window.getComputedStyle ?
                      getComputedStyle(elem, null) :
                      elem.currentStyle)["height"],10);

        bool= !!(compStyle == height);
    });
    return bool;
});

Finally use this function to add the height of the viewport to #your-object if the browser doesn't support vh-units:

$(function() {
    if (!Modernizr.cssvhunit) {
        var windowH = $(window).height();
        $('#your-object').css({'height':($(window).height())+'px'});
    }
});

node.js Error: connect ECONNREFUSED; response from server

just run the following command in the node project

npm install

its worked for me

PHP Redirect to another page after form submit

If your redirect is in PHP, nothing should be echoed to the user before the redirect instruction.

See header for more info.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Otherwise, you can use Javascript to redirect the user.

Just use

window.location = "http://www.google.com/"

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

Typescript

function lengthToExcelColumn(len: number): string {

    let dividend: number = len;
    let columnName: string = '';
    let modulo: number = 0;

    while (dividend > 0) {
        modulo = (dividend - 1) % 26;
        columnName = String.fromCharCode(65 + modulo).toString() + columnName;
        dividend = Math.floor((dividend - modulo) / 26);
    }
    return columnName;
}

Convert string to date then format the date

In one line:

String date=new SimpleDateFormat("MM-dd-yyyy").format(new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01"));

Where:

String date=new SimpleDateFormat("FinalFormat").format(new SimpleDateFormat("InitialFormat").parse("StringDate"));

print call stack in C or C++

Is there any way to dump the call stack in a running process in C or C++ every time a certain function is called?

No there is not, although platform-dependent solutions might exist.

Tab key == 4 spaces and auto-indent after curly braces in Vim

Related, if you open a file that uses both tabs and spaces, assuming you've got

set expandtab ts=4 sw=4 ai

You can replace all the tabs with spaces in the entire file with

:%retab

Understanding ibeacon distancing

The distance estimate provided by iOS is based on the ratio of the beacon signal strength (rssi) over the calibrated transmitter power (txPower). The txPower is the known measured signal strength in rssi at 1 meter away. Each beacon must be calibrated with this txPower value to allow accurate distance estimates.

While the distance estimates are useful, they are not perfect, and require that you control for other variables. Be sure you read up on the complexities and limitations before misusing this.

When we were building the Android iBeacon library, we had to come up with our own independent algorithm because the iOS CoreLocation source code is not available. We measured a bunch of rssi measurements at known distances, then did a best fit curve to match our data points. The algorithm we came up with is shown below as Java code.

Note that the term "accuracy" here is iOS speak for distance in meters. This formula isn't perfect, but it roughly approximates what iOS does.

protected static double calculateAccuracy(int txPower, double rssi) {
  if (rssi == 0) {
    return -1.0; // if we cannot determine accuracy, return -1.
  }

  double ratio = rssi*1.0/txPower;
  if (ratio < 1.0) {
    return Math.pow(ratio,10);
  }
  else {
    double accuracy =  (0.89976)*Math.pow(ratio,7.7095) + 0.111;    
    return accuracy;
  }
}   

Note: The values 0.89976, 7.7095 and 0.111 are the three constants calculated when solving for a best fit curve to our measured data points. YMMV

Table Naming Dilemma: Singular vs. Plural Names

If you go there will be trouble, but if you stay it will be double.

I'd much rather go against some supposed non-plurals naming convention than name my table after something which might be a reserved word.

Java generics - why is "extends T" allowed but not "implements T"?

It's sort of arbitrary which of the terms to use. It could have been either way. Perhaps the language designers thought of "extends" as the most fundamental term, and "implements" as the special case for interfaces.

But I think implements would make slightly more sense. I think that communicates more that the parameter types don't have to be in an inheritance relationship, they can be in any kind of subtype relationship.

The Java Glossary expresses a similar view.

Strings and character with printf

The thing is that the printf function needs a pointer as parameter. However a char is a variable that you have directly acces. A string is a pointer on the first char of the string, so you don't have to add the * because * is the identifier for the pointer of a variable.

Apache HttpClient Android (Gradle)

I resolved problem by adding following to my build.gradle file

android {
useLibrary 'org.apache.http.legacy'}

However this only works if you are using gradle 1.3.0-beta2 or greater, so you will have to add this to buildscript dependencies if you are on a lower version:

classpath 'com.android.tools.build:gradle:1.3.0-beta2'

How do I fix a Git detached head?

Detached head means you have not checked out your branch properly or you have just checked out a single commit.

If you encounter such an issue then first stash your local changes so that you won't lose your changes.

After that... checkout your desired branch using the command:

Let's say you want branch MyOriginalBranch:

git checkout -b someName origin/MyOriginalBranch

Where do alpha testers download Google Play Android apps?

It should be noted that releasing an alpha app for the first time may take up to a few hours before an opt-in link is available and invitations are sent out to the email addresses in your testers list.

From Google support:

After publishing an alpha/beta app for the first time, it may take a few hours for your test link to be available to testers. If you publish additional changes, they may take several hours to be available for testers. [source]

You may want to wait until you have an initial opt-in link before publishing more changes to the app because doing so is likely to increase your wait time for receiving your tester link; or, may lead to your testers testing with the incorrect version.

Hope that clears things up for anyone confused about why they don't have an opt-in link as depicted in screenshots in this SO thread!

Is it safe to delete the "InetPub" folder?

IIS will create it again AFAIK.

How to create a timeline with LaTeX?

Tim Storer wrote a more flexible and nicer looking timeline.sty (Internet Archive Wayback Machine link, as original is gone). In addition, the line is horizontal rather than vertical. So for instance:

\begin{timeline}{2008}{2010}{50}{250}
  \MonthAndYearEvent{4}{2008}{First Podcast}
  \MonthAndYearEvent{7}{2008}{Private Beta}
  \MonthAndYearEvent{9}{2008}{Public Beta}
  \YearEvent{2009}{IPO?}
\end{timeline}

produces a timeline that looks like this:

2008                              2010
 · · April, 2008 First Podcast    ·
       · July, 2008 Private Beta
           · September, 2008 Public Beta
                · 2009 IPO?

Personally, I find this a more pleasing solution than the other answers. But I also find myself modifying the code to get something closer to what I think a timeline should look like. So there's not definitive solution in my opinion.

How to force a WPF binding to refresh?

MultiBinding friendly version...

private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
    BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
}

How to align a <div> to the middle (horizontally/width) of the page

<body>
    <div style=" display: table; margin: 250 auto;">
        In center
    </div>
</body>

If you want to change the vertical position, change the value of 250 and you can arrange the content as per your need. There is no need to give the width and other parameters.

How to extract multiple JSON objects from one file?

Use a json array, in the format:

[
{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes",
  "Code":[{"event1":"A","result":"1"},…]},
{"ID":"1A35B","Timestamp":"20140102", "Usefulness":"No",
  "Code":[{"event1":"B","result":"1"},…]},
{"ID":"AA356","Timestamp":"20140103", "Usefulness":"No",
  "Code":[{"event1":"B","result":"0"},…]},
...
]

Then import it into your python code

import json

with open('file.json') as json_file:

    data = json.load(json_file)

Now the content of data is an array with dictionaries representing each of the elements.

You can access it easily, i.e:

data[0]["ID"]

How to insert data into elasticsearch

If you are using KIBANA with elasticsearch then you can use below RESt request to create and put in the index.

CREATING INDEX:

http://localhost:9200/company
PUT company
{
  "settings": {
    "index": {
      "number_of_shards": 1,
      "number_of_replicas": 1
    },
    "analysis": {
      "analyzer": {
        "analyzer-name": {
          "type": "custom",
          "tokenizer": "keyword",
          "filter": "lowercase"
        }
      }
    }
  },
  "mappings": {
    "employee": {
      "properties": {
        "age": {
          "type": "long"
        },
        "experience": {
          "type": "long"
        },
        "name": {
          "type": "text",
          "analyzer": "analyzer-name"
        }
      }
    }
  }
}

CREATING DOCUMENT:

POST http://localhost:9200/company/employee/2/_create
{
"name": "Hemani",
"age" : 23,
"experienceInYears" : 2
}

Vue - Deep watching an array of objects and calculating the change?

This is what I use to deep watch an object. My requirement was watching the child fields of the object.

new Vue({
    el: "#myElement",
    data:{
        entity: {
            properties: []
        }
    },
    watch:{
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected.    
            },
            deep: true
        }
    }
});

How to close a JavaFX application on window close?

The application automatically stops when the last Stage is closed. At this moment, the stop() method of your Application class is called, so you don't need an equivalent to setDefaultCloseOperation()

If you want to stop the application before that, you can call Platform.exit(), for example in your onCloseRequest call.

You can have all these information on the javadoc page of Application : http://docs.oracle.com/javafx/2/api/javafx/application/Application.html

Binding objects defined in code-behind

While Guy's answer is correct (and probably fits 9 out of 10 cases), it's worth noting that if you are attempting to do this from a control that already has its DataContext set further up the stack, you'll resetting this when you set DataContext back to itself:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

This will of course then break your existing bindings.

If this is the case, you should set the RelativeSource on the control you are trying to bind, rather than its parent.

i.e. for binding to a UserControl's properties:

Binding Path=PropertyName, 
        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}

Given how difficult it can be currently to see what's going on with data binding, it's worth bearing this in mind even if you find that setting RelativeSource={RelativeSource Self} currently works :)

Can I use GDB to debug a running process?

Yes. Use the attach command. Check out this link for more information. Typing help attach at a GDB console gives the following:

(gdb) help attach

Attach to a process or file outside of GDB. This command attaches to another target, of the same type as your last "target" command ("info files" will show your target stack). The command may take as argument a process id, a process name (with an optional process-id as a suffix), or a device file. For a process id, you must have permission to send the process a signal, and it must have the same effective uid as the debugger. When using "attach" to an existing process, the debugger finds the program running in the process, looking first in the current working directory, or (if not found there) using the source file search path (see the "directory" command). You can also use the "file" command to specify the program, and to load its symbol table.


NOTE: You may have difficulty attaching to a process due to improved security in the Linux kernel - for example attaching to the child of one shell from another.

You'll likely need to set /proc/sys/kernel/yama/ptrace_scope depending on your requirements. Many systems now default to 1 or higher.

The sysctl settings (writable only with CAP_SYS_PTRACE) are:

0 - classic ptrace permissions: a process can PTRACE_ATTACH to any other
    process running under the same uid, as long as it is dumpable (i.e.
    did not transition uids, start privileged, or have called
    prctl(PR_SET_DUMPABLE...) already). Similarly, PTRACE_TRACEME is
    unchanged.

1 - restricted ptrace: a process must have a predefined relationship
    with the inferior it wants to call PTRACE_ATTACH on. By default,
    this relationship is that of only its descendants when the above
    classic criteria is also met. To change the relationship, an
    inferior can call prctl(PR_SET_PTRACER, debugger, ...) to declare
    an allowed debugger PID to call PTRACE_ATTACH on the inferior.
    Using PTRACE_TRACEME is unchanged.

2 - admin-only attach: only processes with CAP_SYS_PTRACE may use ptrace
    with PTRACE_ATTACH, or through children calling PTRACE_TRACEME.

3 - no attach: no processes may use ptrace with PTRACE_ATTACH nor via
    PTRACE_TRACEME. Once set, this sysctl value cannot be changed.

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

jQuery - Detect value change on hidden input field

Building off of Viktar's answer, here's an implementation you can call once on a given hidden input element to ensure that subsequent change events get fired whenever the value of the input element changes:

/**
 * Modifies the provided hidden input so value changes to trigger events.
 *
 * After this method is called, any changes to the 'value' property of the
 * specified input will trigger a 'change' event, just like would happen
 * if the input was a text field.
 *
 * As explained in the following SO post, hidden inputs don't normally
 * trigger on-change events because the 'blur' event is responsible for
 * triggering a change event, and hidden inputs aren't focusable by virtue
 * of being hidden elements:
 * https://stackoverflow.com/a/17695525/4342230
 *
 * @param {HTMLInputElement} inputElement
 *   The DOM element for the hidden input element.
 */
function setupHiddenInputChangeListener(inputElement) {
  const propertyName = 'value';

  const {get: originalGetter, set: originalSetter} =
    findPropertyDescriptor(inputElement, propertyName);

  // We wrap this in a function factory to bind the getter and setter values
  // so later callbacks refer to the correct object, in case we use this
  // method on more than one hidden input element.
  const newPropertyDescriptor = ((_originalGetter, _originalSetter) => {
    return {
      set: function(value) {
        const currentValue = originalGetter.call(inputElement);

        // Delegate the call to the original property setter
        _originalSetter.call(inputElement, value);

        // Only fire change if the value actually changed.
        if (currentValue !== value) {
          inputElement.dispatchEvent(new Event('change'));
        }
      },

      get: function() {
        // Delegate the call to the original property getter
        return _originalGetter.call(inputElement);
      }
    }
  })(originalGetter, originalSetter);

  Object.defineProperty(inputElement, propertyName, newPropertyDescriptor);
};

/**
 * Search the inheritance tree of an object for a property descriptor.
 *
 * The property descriptor defined nearest in the inheritance hierarchy to
 * the class of the given object is returned first.
 *
 * Credit for this approach:
 * https://stackoverflow.com/a/38802602/4342230
 *
 * @param {Object} object
 * @param {String} propertyName
 *   The name of the property for which a descriptor is desired.
 *
 * @returns {PropertyDescriptor, null}
 */
function findPropertyDescriptor(object, propertyName) {
  if (object === null) {
    return null;
  }

  if (object.hasOwnProperty(propertyName)) {
    return Object.getOwnPropertyDescriptor(object, propertyName);
  }
  else {
    const parentClass = Object.getPrototypeOf(object);

    return findPropertyDescriptor(parentClass, propertyName);
  }
}

Call this on document ready like so:

$(document).ready(function() {
  setupHiddenInputChangeListener($('myinput')[0]);
});

java- reset list iterator to first element of the list

What you may actually want to use is an Iterable that can return a fresh Iterator multiple times by calling iterator().

//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
    Iterator<Type> it = ible.iterator(); //Gets an iterator
    while (it.hasNext()) {
        it.next();
    }
    it = ible.iterator(); //Gets a NEW iterator, also from the beginning
    while (it.hasNext()) {
        it.next();
    }
}

You must define what the iterator() method does just once beforehand:

void main() {
    LinkedList<String> list; //This could be any type of object that has an iterator
    //Define an Iterable that knows how to retrieve a fresh iterator
    Iterable<Type> ible = new Iterable<Type>() {
        @Override
        public Iterator<Type> iterator() {
            return list.listIterator(); //Define how to get a fresh iterator from any object
        }
    };
    //Now with a single instance of an Iterable,
    func(ible); //you can iterate through it multiple times.
}

How to turn a string formula into a "real" formula

Evaluate might suit:

http://www.mrexcel.com/forum/showthread.php?t=62067

Function Eval(Ref As String)
    Application.Volatile
    Eval = Evaluate(Ref)
End Function

How do I compare strings in GoLang?

For the Platform Independent Users or Windows users, what you can do is:

import runtime:

import (
    "runtime"
    "strings"
)

and then trim the string like this:

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")
}

now you can compare it like that:

if strings.Compare(input, "a") == 0 {
  //....yourCode
}

This is a better approach when you're making use of STDIN on multiple platforms.

Explanation

This happens because on windows lines end with "\r\n" which is known as CRLF, but on UNIX lines end with "\n" which is known as LF and that's why we trim "\n" on unix based operating systems while we trim "\r\n" on windows.

Linq Select Group By

You should try it like this:

var result =
        from priceLog in PriceLogList
        group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
        select new {
            LogDateTime = dateGroup.Key,
            AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
        };

How can I exclude directories from grep -R?

Many correct answers have been given here, but I'm adding this one to emphasize one point which caused some rushed attempts to fail before: exclude-dir takes a pattern, not a path to a directory.

Say your search is:

grep -r myobject

And you notice that your output is cluttered with results from the src/other/objects-folder. This command will not give you the intended result:

grep -r myobject --exclude-dir=src/other/objects-folder

And you may wonder why exclude-dir isn't working! To actually exclude results from the objects-folder, simply do this:

grep -r myobject --exclude-dir=objects-folder

In other words, just use the folder name, not the path. Obvious once you know it.

From the man page:

--exclude-dir=GLOB
Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB.

How to do INSERT into a table records extracted from another table

No "VALUES", no parenthesis:

INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;

Where are include files stored - Ubuntu Linux, GCC

Karl answered your search-path question, but as far as the "source of the files" goes, one thing to be aware of is that if you install the libfoo package and want to do some development with it (i.e., use its headers), you will also need to install libfoo-dev. The standard library header files are already in /usr/include, as you saw.

Note that some libraries with a lot of headers will install them to a subdirectory, e.g., /usr/include/openssl. To include one of those, just provide the path without the /usr/include part, for example:

#include <openssl/aes.h>

Mockito test a void method throws an exception

The parentheses are poorly placed.

You need to use:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                          ^

and NOT use:

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                   ^

This is explained in the documentation

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

How to get File Created Date and Modified Date

File.GetLastWriteTime Method

Returns the date and time the specified file or directory was last written to.

string path = @"c:\Temp\MyTest.txt";
DateTime dt = File.GetLastWriteTime(path);

For create time File.GetCreationTime Method

DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
Console.WriteLine("file created: " + fileCreatedDate);

Javascript negative number

How about something as simple as:

function negative(number){
    return number < 0;
}

The * 1 part is to convert strings to numbers.

Unable to install boto3

I had a similar problem, but the accepted answer did not resolve it - I was not using a virtual environment. This is what I had to do:

sudo python -m pip install boto3

I do not know why this behaved differently from sudo pip install boto3.

How to output JavaScript with PHP

You need to escape your quotes.

You can do this:

echo "<script type=\"text/javascript\">";

or this:

echo "<script type='text/javascript'>";

or this:

echo '<script type="text/javascript">';

Or just stay out of php

<script type="text/javascript">

What is AF_INET, and why do I need it?

The primary purpose of AF_INET was to allow for other possible network protocols or address families (AF is for address family; PF_INET is for the (IPv4) internet protocol family). For example, there probably are a few Netware SPX/IPX networks around still; there were other network systems like DECNet, StarLAN and SNA, not to mention the ill-begotten ISO OSI (Open Systems Interconnection), and these did not necessarily use the now ubiquitous IP address to identify the peer host in network connections.

The ubiquitous alternative to AF_INET (which, in retrospect, should have been named AF_INET4) is AF_INET6, for the IPv6 address family. IPv4 uses 32-bit addresses; IPv6 uses 128-bit addresses.

You may see some other values - but they are unusual. It is there to allow for alternatives and future directions. The sockets interface is actually very general indeed - which is one of the reasons it has thrived where other networking interfaces have withered.

Life has (mostly) gotten simpler - be grateful.

How to navigate to a directory in C:\ with Cygwin?

On a related note, you may also like:

shopt -s autocd

This allows you to cd a dir by just typing in the dir

[user@host ~]$ /cygdrive/d
cd /cygdrive/d
[user@host /cygdrive/d]$ 

To make is persistent you should add it to your ~/.bashrc

Why do people hate SQL cursors so much?

The answers above have not emphasized enough the importance of locking. I'm not a big fan of cursors because they often result in table level locks.

Best way to restrict a text field to numbers only?

Just use regex to get rid of any non number characters whenever a key is pressed or the textbox loses focus.

var numInput;
window.onload = function () {   
    numInput = document.getElementById('numonly');
    numInput.onkeydown = numInput.onblur = numInput.onkeyup = function()
    {
        numInput.value = numInput.value.replace(/[^0-9]+/,"");
    }
}

Android Webview gives net::ERR_CACHE_MISS message

Android WebView fix ERR_CACHE_MISS error solution

you just need add one line code <uses-permission android:name="android.permission.INTERNET"/> in your app/src/main/AndroidManifest.xml file as below screenshots shows.

enter image description here

  1. before

enter image description here

  1. after

enter image description here

Using Sockets to send and receive data

I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream:

Client:

Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data

// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data

// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data

// Send the exit message
dOut.writeByte(-1);
dOut.flush();

dOut.close();

Server:

Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());

boolean done = false;
while(!done) {
  byte messageType = dIn.readByte();

  switch(messageType)
  {
  case 1: // Type A
    System.out.println("Message A: " + dIn.readUTF());
    break;
  case 2: // Type B
    System.out.println("Message B: " + dIn.readUTF());
    break;
  case 3: // Type C
    System.out.println("Message C [1]: " + dIn.readUTF());
    System.out.println("Message C [2]: " + dIn.readUTF());
    break;
  default:
    done = true;
  }
}

dIn.close();

Obviously, you can send all kinds of data, not just bytes and strings (UTF).

Note that writeUTF writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535 bytes to send. This makes it possible for readUTF to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.

Getting a "This application is modifying the autolayout engine from a background thread" error?

I had the same problem. Turns out I was using UIAlerts that needed the main queue. But, they've been deprecated.
When I changed the UIAlerts to the UIAlertController, I no longer had the problem and did not have to use any dispatch_async code. The lesson - pay attention to warnings. They help even when you don't expect it.

How to count the number of set bits in a 32-bit integer?

The Hacker's Delight bit-twiddling becomes so much clearer when you write out the bit patterns.

unsigned int bitCount(unsigned int x)
{
  x = ((x >> 1) & 0b01010101010101010101010101010101)
     + (x       & 0b01010101010101010101010101010101);
  x = ((x >> 2) & 0b00110011001100110011001100110011)
     + (x       & 0b00110011001100110011001100110011); 
  x = ((x >> 4) & 0b00001111000011110000111100001111)
     + (x       & 0b00001111000011110000111100001111); 
  x = ((x >> 8) & 0b00000000111111110000000011111111)
     + (x       & 0b00000000111111110000000011111111); 
  x = ((x >> 16)& 0b00000000000000001111111111111111)
     + (x       & 0b00000000000000001111111111111111); 
  return x;
}

The first step adds the even bits to the odd bits, producing a sum of bits in each two. The other steps add high-order chunks to low-order chunks, doubling the chunk size all the way up, until we have the final count taking up the entire int.

How to read string from keyboard using C?

You need to have the pointer to point somewhere to use it.

Try this code:

char word[64];
scanf("%s", word);

This creates a character array of lenth 64 and reads input to it. Note that if the input is longer than 64 bytes the word array overflows and your program becomes unreliable.

As Jens pointed out, it would be better to not use scanf for reading strings. This would be safe solution.

char word[64]
fgets(word, 63, stdin);
word[63] = 0;

Returning binary file from controller in ASP.NET Web API

For those using .NET Core:

You can make use of the IActionResult interface in an API controller method, like so...

    [HttpGet("GetReportData/{year}")]
    public async Task<IActionResult> GetReportData(int year)
    {
        // Render Excel document in memory and return as Byte[]
        Byte[] file = await this._reportDao.RenderReportAsExcel(year);

        return File(file, "application/vnd.openxmlformats", "fileName.xlsx");
    }

This example is simplified, but should get the point across. In .NET Core this process is so much simpler than in previous versions of .NET - i.e. no setting response type, content, headers, etc.

Also, of course the MIME type for the file and the extension will depend on individual needs.

Reference: SO Post Answer by @NKosi

Escape regex special characters in a Python string

I'm surprised no one has mentioned using regular expressions via re.sub():

import re
print re.sub(r'([\"])',    r'\\\1', 'it\'s "this"')  # it's \"this\"
print re.sub(r"([\'])",    r'\\\1', 'it\'s "this"')  # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"')  # it\'s\ \"this\"

Important things to note:

  • In the search pattern, include \ as well as the character(s) you're looking for. You're going to be using \ to escape your characters, so you need to escape that as well.
  • Put parentheses around the search pattern, e.g. ([\"]), so that the substitution pattern can use the found character when it adds \ in front of it. (That's what \1 does: uses the value of the first parenthesized group.)
  • The r in front of r'([\"])' means it's a raw string. Raw strings use different rules for escaping backslashes. To write ([\"]) as a plain string, you'd need to double all the backslashes and write '([\\"])'. Raw strings are friendlier when you're writing regular expressions.
  • In the substitution pattern, you need to escape \ to distinguish it from a backslash that precedes a substitution group, e.g. \1, hence r'\\\1'. To write that as a plain string, you'd need '\\\\\\1' — and nobody wants that.

How can I get log4j to delete old rotating log files?

You can achieve it using custom log4j appender.
MaxNumberOfDays - possibility to set amount of days of rotated log files.
CompressBackups - possibility to archive old logs with zip extension.

package com.example.package;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CustomLog4jAppender extends FileAppender {

    private static final int TOP_OF_TROUBLE = -1;
    private static final int TOP_OF_MINUTE = 0;
    private static final int TOP_OF_HOUR = 1;
    private static final int HALF_DAY = 2;
    private static final int TOP_OF_DAY = 3;
    private static final int TOP_OF_WEEK = 4;
    private static final int TOP_OF_MONTH = 5;

    private String datePattern = "'.'yyyy-MM-dd";
    private String compressBackups = "false";
    private String maxNumberOfDays = "7";
    private String scheduledFilename;
    private long nextCheck = System.currentTimeMillis() - 1;
    private Date now = new Date();
    private SimpleDateFormat sdf;
    private RollingCalendar rc = new RollingCalendar();

    private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");

    public CustomLog4jAppender() {
    }

    public CustomLog4jAppender(Layout layout, String filename, String datePattern) throws IOException {
        super(layout, filename, true);
        this.datePattern = datePattern;
        activateOptions();
    }

    public void setDatePattern(String pattern) {
        datePattern = pattern;
    }

    public String getDatePattern() {
        return datePattern;
    }

    @Override
    public void activateOptions() {
        super.activateOptions();
        if (datePattern != null && fileName != null) {
            now.setTime(System.currentTimeMillis());
            sdf = new SimpleDateFormat(datePattern);
            int type = computeCheckPeriod();
            printPeriodicity(type);
            rc.setType(type);
            File file = new File(fileName);
            scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
        } else {
            LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
        }
    }

    private void printPeriodicity(int type) {
        String appender = "Log4J Appender: ";
        switch (type) {
            case TOP_OF_MINUTE:
                LogLog.debug(appender + name + " to be rolled every minute.");
                break;
            case TOP_OF_HOUR:
                LogLog.debug(appender + name + " to be rolled on top of every hour.");
                break;
            case HALF_DAY:
                LogLog.debug(appender + name + " to be rolled at midday and midnight.");
                break;
            case TOP_OF_DAY:
                LogLog.debug(appender + name + " to be rolled at midnight.");
                break;
            case TOP_OF_WEEK:
                LogLog.debug(appender + name + " to be rolled at start of week.");
                break;
            case TOP_OF_MONTH:
                LogLog.debug(appender + name + " to be rolled at start of every month.");
                break;
            default:
                LogLog.warn("Unknown periodicity for appender [" + name + "].");
        }
    }

    private int computeCheckPeriod() {
        RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.ENGLISH);
        Date epoch = new Date(0);
        if (datePattern != null) {
            for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
                simpleDateFormat.setTimeZone(gmtTimeZone);
                String r0 = simpleDateFormat.format(epoch);
                rollingCalendar.setType(i);
                Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
                String r1 = simpleDateFormat.format(next);
                if (!r0.equals(r1)) {
                    return i;
                }
            }
        }
        return TOP_OF_TROUBLE;
    }

    private void rollOver() throws IOException {
        if (datePattern == null) {
            errorHandler.error("Missing DatePattern option in rollOver().");
            return;
        }
        String datedFilename = fileName + sdf.format(now);
        if (scheduledFilename.equals(datedFilename)) {
            return;
        }
        this.closeFile();
        File target = new File(scheduledFilename);
        if (target.exists()) {
            Files.delete(target.toPath());
        }
        File file = new File(fileName);
        boolean result = file.renameTo(target);
        if (result) {
            LogLog.debug(fileName + " -> " + scheduledFilename);
        } else {
            LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
        }
        try {
            this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
        } catch (IOException e) {
            errorHandler.error("setFile(" + fileName + ", false) call failed.");
        }
        scheduledFilename = datedFilename;
    }

    @Override
    protected void subAppend(LoggingEvent event) {
        long n = System.currentTimeMillis();
        if (n >= nextCheck) {
            now.setTime(n);
            nextCheck = rc.getNextCheckMillis(now);
            try {
                cleanupAndRollOver();
            } catch (IOException ioe) {
                LogLog.error("cleanupAndRollover() failed.", ioe);
            }
        }
        super.subAppend(event);
    }

    public String getCompressBackups() {
        return compressBackups;
    }

    public void setCompressBackups(String compressBackups) {
        this.compressBackups = compressBackups;
    }

    public String getMaxNumberOfDays() {
        return maxNumberOfDays;
    }

    public void setMaxNumberOfDays(String maxNumberOfDays) {
        this.maxNumberOfDays = maxNumberOfDays;
    }

    protected void cleanupAndRollOver() throws IOException {
        File file = new File(fileName);
        Calendar cal = Calendar.getInstance();
        int maxDays = 7;
        try {
            maxDays = Integer.parseInt(getMaxNumberOfDays());
        } catch (Exception e) {
            // just leave it at 7.
        }
        cal.add(Calendar.DATE, -maxDays);
        Date cutoffDate = cal.getTime();
        if (file.getParentFile().exists()) {
            File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false));
            int nameLength = file.getName().length();
            for (File value : Optional.ofNullable(files).orElse(new File[0])) {
                String datePart;
                try {
                    datePart = value.getName().substring(nameLength);
                    Date date = sdf.parse(datePart);
                    if (date.before(cutoffDate)) {
                        Files.delete(value.toPath());
                    } else if (getCompressBackups().equalsIgnoreCase("YES") || getCompressBackups().equalsIgnoreCase("TRUE")) {
                        zipAndDelete(value);
                    }
                } catch (Exception pe) {
                    // This isn't a file we should touch (it isn't named correctly)
                }
            }
        }
        rollOver();
    }

    private void zipAndDelete(File file) throws IOException {
        if (!file.getName().endsWith(".zip")) {
            File zipFile = new File(file.getParent(), file.getName() + ".zip");
            try (FileInputStream fis = new FileInputStream(file);
                 FileOutputStream fos = new FileOutputStream(zipFile);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                byte[] buffer = new byte[4096];
                while (true) {
                    int bytesRead = fis.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    } else {
                        zos.write(buffer, 0, bytesRead);
                    }
                }
                zos.closeEntry();
            }
            Files.delete(file.toPath());
        }
    }

    class StartsWithFileFilter implements FileFilter {
        private String startsWith;
        private boolean inclDirs;

        StartsWithFileFilter(String startsWith, boolean includeDirectories) {
            super();
            this.startsWith = startsWith.toUpperCase();
            inclDirs = includeDirectories;
        }

        public boolean accept(File pathname) {
            if (!inclDirs && pathname.isDirectory()) {
                return false;
            } else {
                return pathname.getName().toUpperCase().startsWith(startsWith);
            }
        }
    }

    class RollingCalendar extends GregorianCalendar {
        private static final long serialVersionUID = -3560331770601814177L;

        int type = CustomLog4jAppender.TOP_OF_TROUBLE;

        RollingCalendar() {
            super();
        }

        RollingCalendar(TimeZone tz, Locale locale) {
            super(tz, locale);
        }

        void setType(int type) {
            this.type = type;
        }

        long getNextCheckMillis(Date now) {
            return getNextCheckDate(now).getTime();
        }

        Date getNextCheckDate(Date now) {
            this.setTime(now);

            switch (type) {
                case CustomLog4jAppender.TOP_OF_MINUTE:
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MINUTE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_HOUR:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.HOUR_OF_DAY, 1);
                    break;
                case CustomLog4jAppender.HALF_DAY:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    int hour = get(Calendar.HOUR_OF_DAY);
                    if (hour < 12) {
                        this.set(Calendar.HOUR_OF_DAY, 12);
                    } else {
                        this.set(Calendar.HOUR_OF_DAY, 0);
                        this.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    break;
                case CustomLog4jAppender.TOP_OF_DAY:
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.DATE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_WEEK:
                    this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.WEEK_OF_YEAR, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_MONTH:
                    this.set(Calendar.DATE, 1);
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MONTH, 1);
                    break;
                default:
                    throw new IllegalStateException("Unknown periodicity type.");
            }
            return getTime();
        }
    }    
}

And use this properties in your log4j config file:

log4j.appender.[appenderName]=com.example.package.CustomLog4jAppender
log4j.appender.[appenderName].File=/logs/app-daily.log
log4j.appender.[appenderName].Append=true
log4j.appender.[appenderName].encoding=UTF-8
log4j.appender.[appenderName].layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.[appenderName].layout.ConversionPattern=%-5.5p %d %C{1.} - %m%n
log4j.appender.[appenderName].DatePattern='.'yyyy-MM-dd
log4j.appender.[appenderName].MaxNumberOfDays=7
log4j.appender.[appenderName].CompressBackups=true

How to get the ASCII value of a character

From here:

The function ord() gets the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick.

>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>

In Python 2, there was also the unichr function, returning the Unicode character whose ordinal is the unichr argument:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'

In Python 3 you can use chr instead of unichr.


ord() - Python 3.6.5rc1 documentation

ord() - Python 2.7.14 documentation

How to determine whether a substring is in a different string

If you're looking for more than a True/False, you'd be best suited to use the re module, like:

import re
search="please help me out"
fullstring="please help me out so that I could solve this"
s = re.search(search,fullstring)
print(s.group())

s.group() will return the string "please help me out".

What is HEAD in Git?

These two may confusing you:

head

Pointing to named references a branch recently submitted. Unless you use the package reference , heads typically stored in $ GIT_DIR/refs/heads/.

HEAD

Current branch, or your working tree is usually generated from the tree HEAD is pointing to. HEAD must point to a head, except you are using a detached HEAD.

Making a POST call instead of GET using urllib2

Have a read of the urllib Missing Manual. Pulled from there is the following simple example of a POST request.

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age'  : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print response.read()

As suggested by @Michael Kent do consider requests, it's great.

EDIT: This said, I do not know why passing data to urlopen() does not result in a POST request; It should. I suspect your server is redirecting, or misbehaving.

Input length must be multiple of 16 when decrypting with padded cipher

I know this message is old and was a long time ago - but i also had problem with with the exact same error:

the problem I had was relates to the fact the encrypted text was converted to String and to byte[] when trying to DECRYPT it.

    private Key getAesKey() throws Exception {
    return new SecretKeySpec(Arrays.copyOf(key.getBytes("UTF-8"), 16), "AES");
}

private Cipher getMutual() throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    return cipher;// cipher.doFinal(pass.getBytes());
}

public byte[] getEncryptedPass(String pass) throws Exception {
    Cipher cipher = getMutual();
    cipher.init(Cipher.ENCRYPT_MODE, getAesKey());
    byte[] encrypted = cipher.doFinal(pass.getBytes("UTF-8"));
    return encrypted;

}

public String getDecryptedPass(byte[] encrypted) throws Exception {
    Cipher cipher = getMutual();
    cipher.init(Cipher.DECRYPT_MODE, getAesKey());
    String realPass = new String(cipher.doFinal(encrypted));
    return realPass;
}

How to duplicate sys.stdout to a log file?

I'm writing a script to run cmd-line scripts. ( Because in some cases, there just is no viable substitute for a Linux command -- such as the case of rsync. )

What I really wanted was to use the default python logging mechanism in every case where it was possible to do so, but to still capture any error when something went wrong that was unanticipated.

This code seems to do the trick. It may not be particularly elegant or efficient ( although it doesn't use string+=string, so at least it doesn't have that particular potential bottle- neck ). I'm posting it in case it gives someone else any useful ideas.

import logging
import os, sys
import datetime

# Get name of module, use as application name
try:
  ME=os.path.split(__file__)[-1].split('.')[0]
except:
  ME='pyExec_'

LOG_IDENTIFIER="uuu___( o O )___uuu "
LOG_IDR_LENGTH=len(LOG_IDENTIFIER)

class PyExec(object):

  # Use this to capture all possible error / output to log
  class SuperTee(object):
      # Original reference: http://mail.python.org/pipermail/python-list/2007-May/442737.html
      def __init__(self, name, mode):
          self.fl = open(name, mode)
          self.fl.write('\n')
          self.stdout = sys.stdout
          self.stdout.write('\n')
          self.stderr = sys.stderr

          sys.stdout = self
          sys.stderr = self

      def __del__(self):
          self.fl.write('\n')
          self.fl.flush()
          sys.stderr = self.stderr
          sys.stdout = self.stdout
          self.fl.close()

      def write(self, data):
          # If the data to write includes the log identifier prefix, then it is already formatted
          if data[0:LOG_IDR_LENGTH]==LOG_IDENTIFIER:
            self.fl.write("%s\n" % data[LOG_IDR_LENGTH:])
            self.stdout.write(data[LOG_IDR_LENGTH:])

          # Otherwise, we can give it a timestamp
          else:

            timestamp=str(datetime.datetime.now())
            if 'Traceback' == data[0:9]:
              data='%s: %s' % (timestamp, data)
              self.fl.write(data)
            else:
              self.fl.write(data)

            self.stdout.write(data)


  def __init__(self, aName, aCmd, logFileName='', outFileName=''):

    # Using name for 'logger' (context?), which is separate from the module or the function
    baseFormatter=logging.Formatter("%(asctime)s \t %(levelname)s \t %(name)s:%(module)s:%(lineno)d \t %(message)s")
    errorFormatter=logging.Formatter(LOG_IDENTIFIER + "%(asctime)s \t %(levelname)s \t %(name)s:%(module)s:%(lineno)d \t %(message)s")

    if logFileName:
      # open passed filename as append
      fl=logging.FileHandler("%s.log" % aName)
    else:
      # otherwise, use log filename as a one-time use file
      fl=logging.FileHandler("%s.log" % aName, 'w')

    fl.setLevel(logging.DEBUG)
    fl.setFormatter(baseFormatter)

    # This will capture stdout and CRITICAL and beyond errors

    if outFileName:
      teeFile=PyExec.SuperTee("%s_out.log" % aName)
    else:
      teeFile=PyExec.SuperTee("%s_out.log" % aName, 'w')

    fl_out=logging.StreamHandler( teeFile )
    fl_out.setLevel(logging.CRITICAL)
    fl_out.setFormatter(errorFormatter)

    # Set up logging
    self.log=logging.getLogger('pyExec_main')
    log=self.log

    log.addHandler(fl)
    log.addHandler(fl_out)

    print "Test print statement."

    log.setLevel(logging.DEBUG)

    log.info("Starting %s", ME)
    log.critical("Critical.")

    # Caught exception
    try:
      raise Exception('Exception test.')
    except Exception,e:
      log.exception(str(e))

    # Uncaught exception
    a=2/0


PyExec('test_pyExec',None)

Obviously, if you're not as subject to whimsy as I am, replace LOG_IDENTIFIER with another string that you're not like to ever see someone write to a log.

How to select the rows with maximum values in each group with dplyr?

df %>% group_by(A,B) %>% slice(which.max(value))

How to leave space in HTML

After, or in-between your text, use the &nbsp; (non-breaking space) extended HTML character.

  • EG 1 :

    This is an example paragraph. &nbsp;&nbsp; This is the next line.

How do I change the figure size for a seaborn plot?

You can set the context to be poster or manually set fig_size.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10


# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)    
sns.despine()

fig.savefig('example.png')

enter image description here

How to make picturebox transparent?

you can set the PictureBox BackColor proprty to Transparent

The difference between Classes, Objects, and Instances

Any kind of data your computer stores and processes is in its most basic representation a row of bits. The way those bits are interpreted is done through data types. Data types can be primitive or complex. Primitive data types are - for instance - int or double. They have a specific length and a specific way of being interpreted. In the case of an integer, usually the first bit is used for the sign, the others are used for the value.

Complex data types can be combinations of primitive and other complex data types and are called "Class" in Java.

You can define the complex data type PeopleName consisting of two Strings called first and last name. Each String in Java is another complex data type. Strings in return are (probably) implemented using the primitive data type char for which Java knows how many bits they take to store and how to interpret them.

When you create an instance of a data type, you get an object and your computers reserves some memory for it and remembers its location and the name of that instance. An instance of PeopleName in memory will take up the space of the two String variables plus a bit more for bookkeeping. An integer takes up 32 bits in Java.

Complex data types can have methods assigned to them. Methods can perform actions on their arguments or on the instance of the data type you call this method from. If you have two instances of PeopleName called p1 and p2 and you call a method p1.getFirstName(), it usually returns the first name of the first person but not the second person's.

How to check file MIME type with javascript before upload?

Here is an extension of Roberto14's answer that does the following:

THIS WILL ONLY ALLOW IMAGES

Checks if FileReader is available and falls back to extension checking if it is not available.

Gives an error alert if not an image

If it is an image it loads a preview

** You should still do server side validation, this is more a convenience for the end user than anything else. But it is handy!

<form id="myform">
    <input type="file" id="myimage" onchange="readURL(this)" />
    <img id="preview" src="#" alt="Image Preview" />
</form>

<script>
function readURL(input) {
    if (window.FileReader && window.Blob) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var img = new Image();
                img.onload = function() {
                    var preview = document.getElementById('preview');
                    preview.src = e.target.result;
                    };
                img.onerror = function() { 
                    alert('error');
                    input.value = '';
                    };
                img.src = e.target.result;
                }
            reader.readAsDataURL(input.files[0]);
            }
        }
    else {
        var ext = input.value.split('.');
        ext = ext[ext.length-1].toLowerCase();      
        var arrayExtensions = ['jpg' , 'jpeg', 'png', 'bmp', 'gif'];
        if (arrayExtensions.lastIndexOf(ext) == -1) {
            alert('error');
            input.value = '';
            }
        else {
            var preview = document.getElementById('preview');
            preview.setAttribute('alt', 'Browser does not support preview.');
            }
        }
    }
</script>

Adding to an ArrayList Java

Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)

Recommended reading. Lists in the Java Tutorial

git checkout all the files

  • If you are in base directory location of your tracked files then git checkout . will works otherwise it won't work

Getting json body in aws Lambda via API gateway

I am using lambda with Zappa; I am sending data with POST in json format:

My code for basic_lambda_pure.py is:

import time
import requests
import json
def my_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    print("Log stream name:", context.log_stream_name)
    print("Log group name:",  context.log_group_name)
    print("Request ID:", context.aws_request_id)
    print("Mem. limits(MB):", context.memory_limit_in_mb)
    # Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value.
    print("Time remaining (MS):", context.get_remaining_time_in_millis())

    if event["httpMethod"] == "GET":
        hub_mode = event["queryStringParameters"]["hub.mode"]
        hub_challenge = event["queryStringParameters"]["hub.challenge"]
        hub_verify_token = event["queryStringParameters"]["hub.verify_token"]
        return {'statusCode': '200', 'body': hub_challenge, 'headers': 'Content-Type': 'application/json'}}

    if event["httpMethod"] == "post":
        token = "xxxx"
    params = {
        "access_token": token
    }
    headers = {
        "Content-Type": "application/json"
    }
        _data = {"recipient": {"id": 1459299024159359}}
        _data.update({"message": {"text": "text"}})
        data = json.dumps(_data)
        r = requests.post("https://graph.facebook.com/v2.9/me/messages",params=params, headers=headers, data=data, timeout=2)
        return {'statusCode': '200', 'body': "ok", 'headers': {'Content-Type': 'application/json'}}

I got the next json response:

{
"resource": "/",
"path": "/",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Content-Type": "application/json",
"Host": "ox53v9d8ug.execute-api.us-east-1.amazonaws.com",
"Via": "1.1 f1836a6a7245cc3f6e190d259a0d9273.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "LVcBZU-YqklHty7Ii3NRFOqVXJJEr7xXQdxAtFP46tMewFpJsQlD2Q==",
"X-Amzn-Trace-Id": "Root=1-59ec25c6-1018575e4483a16666d6f5c5",
"X-Forwarded-For": "69.171.225.87, 52.46.17.84",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
"X-Hub-Signature": "sha1=10504e2878e56ea6776dfbeae807de263772e9f2"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"path": "/dev",
"accountId": "001513791584",
"resourceId": "i6d2tyihx7",
"stage": "dev",
"requestId": "d58c5804-b6e5-11e7-8761-a9efcf8a8121",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"apiKey": "",
"sourceIp": "69.171.225.87",
"accessKey": null,
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": null,
"user": null
},
"resourcePath": "/",
"httpMethod": "POST",
"apiId": "ox53v9d8ug"
},
"body": "eyJvYmplY3QiOiJwYWdlIiwiZW50cnkiOlt7ImlkIjoiMTA3OTk2NDk2NTUxMDM1IiwidGltZSI6MTUwODY0ODM5MDE5NCwibWVzc2FnaW5nIjpbeyJzZW5kZXIiOnsiaWQiOiIxNDAzMDY4MDI5ODExODY1In0sInJlY2lwaWVudCI6eyJpZCI6IjEwNzk5NjQ5NjU1MTAzNSJ9LCJ0aW1lc3RhbXAiOjE1MDg2NDgzODk1NTUsIm1lc3NhZ2UiOnsibWlkIjoibWlkLiRjQUFBNHo5RmFDckJsYzdqVHMxZlFuT1daNXFaQyIsInNlcSI6MTY0MDAsInRleHQiOiJob2xhIn19XX1dfQ==",
"isBase64Encoded": true
}

my data was on body key, but is code64 encoded, How can I know this? I saw the key isBase64Encoded

I copy the value for body key and decode with This tool and "eureka", I get the values.

I hope this help you. :)

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Use a virtual machine. Start fresh as often as you want, and stop doing these hacks that may or may not simulate a clean machine.

Seriously, use VMWare or VirtualPC.

How to update values in a specific row in a Python Pandas DataFrame?

There are probably a few ways to do this, but one approach would be to merge the two dataframes together on the filename/m column, then populate the column 'n' from the right dataframe if a match was found. The n_x, n_y in the code refer to the left/right dataframes in the merge.

In[100] : df = pd.merge(df1, df2, how='left', on=['filename','m'])

In[101] : df
Out[101]: 
    filename   m   n_x  n_y
0  test0.dat  12  None  NaN
1  test2.dat  13  None   16

In[102] : df['n'] = df['n_y'].fillna(df['n_x'])

In[103] : df = df.drop(['n_x','n_y'], axis=1)

In[104] : df
Out[104]: 
    filename   m     n
0  test0.dat  12  None
1  test2.dat  13    16

"Line contains NULL byte" in CSV reader (Python)

I've recently fixed this issue and in my instance it was a file that was compressed that I was trying to read. Check the file format first. Then check that the contents are what the extension refers to.

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

How about playing with these two properties?

disableClose: boolean - Whether the user can use escape or clicking on the backdrop to close the modal.

hasBackdrop: boolean - Whether the dialog has a backdrop.

https://material.angular.io/components/dialog/api

How to have comments in IntelliSense for function in Visual Studio?

What you need is xml comments - basically, they follow this syntax (as vaguely described by Solmead):

C#

///<summary>
///This is a description of my function.
///</summary>
string myFunction() {
     return "blah";
}

VB

'''<summary>
'''This is a description of my function.
'''</summary>
Function myFunction() As String
    Return "blah"
End Function

Use of Application.DoEvents()

Yes.

However, if you need to use Application.DoEvents, this is mostly an indication of a bad application design. Perhaps you'd like to do some work in a separate thread instead?

specifying goal in pom.xml

I am facing same Issue after run my build.

The error message tell us to specify your goal

Jenkins Issue related to goal for build

So I specify the goal Ex:-test.

Now It's running fine

How to escape a JSON string containing newline characters using JavaScript?

As per user667073 suggested, except reordering the backslash replacement first, and fixing the quote replacement

escape = function (str) {
  return str
    .replace(/[\\]/g, '\\\\')
    .replace(/[\"]/g, '\\\"')
    .replace(/[\/]/g, '\\/')
    .replace(/[\b]/g, '\\b')
    .replace(/[\f]/g, '\\f')
    .replace(/[\n]/g, '\\n')
    .replace(/[\r]/g, '\\r')
    .replace(/[\t]/g, '\\t');
};

Error: Module not specified (IntelliJ IDEA)

Faced the same issue. To solve it,

Running Composer returns: "Could not open input file: composer.phar"

enter image description here

your composer.phar should be placed in above way.

Query to check index on a table

Simply you can find index name and column names of a particular table using below command

SP_HELPINDEX 'tablename'

It work's for me

How does strcmp() work?

This is how I implemented my strcmp: it works like this: it compares first letter of the two strings, if it is identical, it continues to the next letter. If not, it returns the corresponding value. It is very simple and easy to understand: #include

//function declaration:
int strcmp(char string1[], char string2[]);

int main()
{
    char string1[]=" The San Antonio spurs";
    char string2[]=" will be champins again!";
    //calling the function- strcmp
    printf("\n number returned by the strcmp function: %d", strcmp(string1, string2));
    getch();
    return(0);
}

/**This function calculates the dictionary value of the string and compares it to another string.
it returns a number bigger than 0 if the first string is bigger than the second
it returns a number smaller than 0 if the second string is bigger than the first
input: string1, string2
output: value- can be 1, 0 or -1 according to the case*/
int strcmp(char string1[], char string2[])
{
    int i=0;
    int value=2;    //this initialization value could be any number but the numbers that can be      returned by the function
    while(value==2)
    {
        if (string1[i]>string2[i])
        {
            value=1;
        }
        else if (string1[i]<string2[i])
        {
            value=-1;
        }
        else
        {
            i++;
        }
    }
    return(value);
}

Script to get the HTTP status code of a list of urls?

I found a tool "webchk” written in Python. Returns a status code for a list of urls. https://pypi.org/project/webchk/

Output looks like this:

? webchk -i ./dxieu.txt | grep '200'
http://salesforce-case-status.dxi.eu/login ... 200 OK (0.108)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.389)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.401)

Hope that helps!

How to get a URL parameter in Express?

If you want to grab the query parameter value in the URL, follow below code pieces

//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid

If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;

next();
});

// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});

Get all Attributes from a HTML element with Javascript/jQuery

Element.prototype.getA = function (a) {
        if (a) {
            return this.getAttribute(a);
        } else {
            var o = {};
            for(let a of this.attributes){
                o[a.name]=a.value;
            }
            return o;
        }
    }

having <div id="mydiv" a='1' b='2'>...</div> can use

mydiv.getA() // {id:"mydiv",a:'1',b:'2'}

How to display .svg image using swift

You can use SVGKit for example.

1) Integrate it according to instructions. Drag&dropping the .framework file is fast and easy.

2) Make sure you have an Objective-C to Swift bridge file bridging-header.h with import code in it:

#import <SVGKit/SVGKit.h>
#import <SVGKit/SVGKImage.h>

3) Use the framework like this, assuming that dataFromInternet is NSData, previously downloaded from network:

let anSVGImage: SVGKImage = SVGKImage(data: dataFromInternet)
myIUImageView.image = anSVGImage.UIImage

The framework also allows to init an SVGKImage from other different sources, for example it can download image for you when you provide it with URL. But in my case it was crashing in case of unreachable url, so it turned out to be better to manage networking by myself. More info on it here.

What does ENABLE_BITCODE do in xcode 7?

Bitcode (iOS, watchOS)

Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.


Basically this concept is somewhat similar to java where byte code is run on different JVM's and in this case the bitcode is placed on iTune store and instead of giving the intermediate code to different platforms(devices) it provides the compiled code which don't need any virtual machine to run.

Thus we need to create the bitcode once and it will be available for existing or coming devices. It's the Apple's headache to compile an make it compatible with each platform they have.

Devs don't have to make changes and submit the app again to support new platforms.

Let's take the example of iPhone 5s when apple introduced x64 chip in it. Although x86 apps were totally compatible with x64 architecture but to fully utilise the x64 platform the developer has to change the architecture or some code. Once s/he's done the app is submitted to the app store for the review.

If this bitcode concept was launched earlier then we the developers doesn't have to make any changes to support the x64 bit architecture.

Can't use SURF, SIFT in OpenCV

Install Python opencv

pip install opencv-python

and instead of using ..

cv2.SIFT()

Use

cv2.SIFT_create()

working code using opencv-python below

import cv2
img1 = cv2.imread('yourimg.png',0)
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None) #keypoint and descriptors
...

you can also install "opencv-contrib-python" and use "cv2.xfeatures2d.SIFT_create()" but that is secondary and up to you.. working code using the python package opencv-contrib-python

import cv2
img1 = cv2.imread('yourimg.png',0)
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None) #keypoint and descriptors

Thanks

How to write a confusion matrix in Python?

Scikit-Learn provides a confusion_matrix function

from sklearn.metrics import confusion_matrix
y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]
y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]
confusion_matrix(y_actu, y_pred)

which output a Numpy array

array([[3, 0, 0],
       [0, 1, 2],
       [2, 1, 3]])

But you can also create a confusion matrix using Pandas:

import pandas as pd
y_actu = pd.Series([2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2], name='Actual')
y_pred = pd.Series([0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2], name='Predicted')
df_confusion = pd.crosstab(y_actu, y_pred)

You will get a (nicely labeled) Pandas DataFrame:

Predicted  0  1  2
Actual
0          3  0  0
1          0  1  2
2          2  1  3

If you add margins=True like

df_confusion = pd.crosstab(y_actu, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True)

you will get also sum for each row and column:

Predicted  0  1  2  All
Actual
0          3  0  0    3
1          0  1  2    3
2          2  1  3    6
All        5  2  5   12

You can also get a normalized confusion matrix using:

df_conf_norm = df_confusion / df_confusion.sum(axis=1)

Predicted         0         1         2
Actual
0          1.000000  0.000000  0.000000
1          0.000000  0.333333  0.333333
2          0.666667  0.333333  0.500000

You can plot this confusion_matrix using

import matplotlib.pyplot as plt
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)

plot_confusion_matrix(df_confusion)

plot confusion matrix

Or plot normalized confusion matrix using:

plot_confusion_matrix(df_conf_norm)  

plot confusion matrix normalized

You might also be interested by this project https://github.com/pandas-ml/pandas-ml and its Pip package https://pypi.python.org/pypi/pandas_ml

With this package confusion matrix can be pretty-printed, plot. You can binarize a confusion matrix, get class statistics such as TP, TN, FP, FN, ACC, TPR, FPR, FNR, TNR (SPC), LR+, LR-, DOR, PPV, FDR, FOR, NPV and some overall statistics

In [1]: from pandas_ml import ConfusionMatrix
In [2]: y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]
In [3]: y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]
In [4]: cm = ConfusionMatrix(y_actu, y_pred)
In [5]: cm.print_stats()
Confusion Matrix:

Predicted  0  1  2  __all__
Actual
0          3  0  0        3
1          0  1  2        3
2          2  1  3        6
__all__    5  2  5       12


Overall Statistics:

Accuracy: 0.583333333333
95% CI: (0.27666968568210581, 0.84834777019156982)
No Information Rate: ToDo
P-Value [Acc > NIR]: 0.189264302376
Kappa: 0.354838709677
Mcnemar's Test P-Value: ToDo


Class Statistics:

Classes                                        0          1          2
Population                                    12         12         12
P: Condition positive                          3          3          6
N: Condition negative                          9          9          6
Test outcome positive                          5          2          5
Test outcome negative                          7         10          7
TP: True Positive                              3          1          3
TN: True Negative                              7          8          4
FP: False Positive                             2          1          2
FN: False Negative                             0          2          3
TPR: (Sensitivity, hit rate, recall)           1  0.3333333        0.5
TNR=SPC: (Specificity)                 0.7777778  0.8888889  0.6666667
PPV: Pos Pred Value (Precision)              0.6        0.5        0.6
NPV: Neg Pred Value                            1        0.8  0.5714286
FPR: False-out                         0.2222222  0.1111111  0.3333333
FDR: False Discovery Rate                    0.4        0.5        0.4
FNR: Miss Rate                                 0  0.6666667        0.5
ACC: Accuracy                          0.8333333       0.75  0.5833333
F1 score                                    0.75        0.4  0.5454545
MCC: Matthews correlation coefficient  0.6831301  0.2581989  0.1690309
Informedness                           0.7777778  0.2222222  0.1666667
Markedness                                   0.6        0.3  0.1714286
Prevalence                                  0.25       0.25        0.5
LR+: Positive likelihood ratio               4.5          3        1.5
LR-: Negative likelihood ratio                 0       0.75       0.75
DOR: Diagnostic odds ratio                   inf          4          2
FOR: False omission rate                       0        0.2  0.4285714

I noticed that a new Python library about Confusion Matrix named PyCM is out: maybe you can have a look.

Android Camera : data intent returns null

I´ve had experienced this problem, the intent is not null but the information sent via this intent is not received in onActionActivit()

enter image description here

This is a better solution using getContentResolver() :

    private Uri imageUri;
    private ImageView myImageView;
    private Bitmap thumbnail;

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

      ...
      ...    
      ...
      myImageview = (ImageView) findViewById(R.id.pic); 

      values = new ContentValues();
      values.put(MediaStore.Images.Media.TITLE, "MyPicture");
      values.put(MediaStore.Images.Media.DESCRIPTION, "Photo taken on " + System.currentTimeMillis());
      imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
      startActivityForResult(intent, PICTURE_RESULT);

  }

the onActivityResult() get a bitmap stored by getContentResolver() :

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {

            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                myImageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

introducir la descripción de la imagen aquí introducir la descripción de la imagen aquí

Check my example in github:

https://github.com/Jorgesys/TakePicture

Get a worksheet name using Excel VBA

Sub FnGetSheetsName()

    Dim mainworkBook As Workbook

    Set mainworkBook = ActiveWorkbook

    For i = 1 To mainworkBook.Sheets.Count

    'Either we can put all names in an array , here we are printing all the names in Sheet 2

    mainworkBook.Sheets("Sheet2").Range("A" & i) = mainworkBook.Sheets(i).Name

    Next i

End Sub

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

Saving awk output to variable

I think the $() syntax is easier to read...

variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')

But the real issue is probably that $12 should not be qouted with ""

Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef is and what is expected in variable.

Python xticks in subplots

See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:

  • If you want to set the xticklabels:

    ax.set_xticks([1,4,5]) 
    ax.set_xticklabels([1,4,5], fontsize=12)
    
  • If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):

    ax.tick_params(axis="x", labelsize=12) 
    
  • To do it all at once:

    plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", 
             horizontalalignment="left")`
    

builtins.TypeError: must be str, not bytes

Convert binary file to base64 & vice versa. Prove in python 3.5.2

import base64

read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()

b64 = base64.b64encode(data)

print (b64)

# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)

# Test in python 3.5.2

What is the MySQL JDBC driver connection string?

"jdbc:mysql://localhost"

From the oracle docs..

jdbc:mysql://[host][,failoverhost...]
[:port]/[database]
[?propertyName1][=propertyValue1]
[&propertyName2][=propertyValue2]

host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively.

database is the name of the database to connect to. If not specified, a connection is made with no default database.

failover is the name of a standby database (MySQL Connector/J supports failover).

propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.

Make the console wait for a user input to close

I've put in what x4u said. Eclipse wanted a try catch block around it so I let it generate it for me.

try {
        System.in.read();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

It can probably have all sorts of bells and whistles on it but I think for beginners that want a command line window not quitting this should be fine.

Also I don't know how common this is (this is my first time making jar files), but it wouldn't run by itself, only via a bat file.

java.exe -jar mylibrary.jar

The above is what the bat file had in the same folder. Seems to be an install issue.

Eclipse tutorial came from: http://eclipsetutorial.sourceforge.net/index.html

Some of the answer also came from: Oracle Thread

How to replace DOM element in place using Javascript?

Given the already proposed options the easiest solution without finding a parent:

var parent = document.createElement("div");
var child = parent.appendChild(document.createElement("a"));
var span = document.createElement("span");

// for IE
if("replaceNode" in child)
  child.replaceNode(span);

// for other browsers
if("replaceWith" in child)
  child.replaceWith(span);

console.log(parent.outerHTML);

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

Ruby: How to turn a hash into HTTP parameters?

I know this is an old question, but I just wanted to post this bit of code as I could not find a simple gem to do just this task for me.

module QueryParams

  def self.encode(value, key = nil)
    case value
    when Hash  then value.map { |k,v| encode(v, append_key(key,k)) }.join('&')
    when Array then value.map { |v| encode(v, "#{key}[]") }.join('&')
    when nil   then ''
    else            
      "#{key}=#{CGI.escape(value.to_s)}" 
    end
  end

  private

  def self.append_key(root_key, key)
    root_key.nil? ? key : "#{root_key}[#{key.to_s}]"
  end
end

Rolled up as gem here: https://github.com/simen/queryparams

Change a Nullable column to NOT NULL with Default Value

If its SQL Server you can do it on the column properties within design view

Try this?:

ALTER TABLE dbo.TableName 
  ADD CONSTRAINT DF_TableName_ColumnName
    DEFAULT '01/01/2000' FOR ColumnName

How do the post increment (i++) and pre increment (++i) operators work in Java?

pre-increment and post increment are equivalent if not in an expression

int j =0;
int r=0         
for(int v = 0; v<10; ++v) { 
          ++r;
          j++;
          System.out.println(j+" "+r);
  }  
 1 1  
 2 2  
 3 3       
 4 4
 5 5
 6 6
 7 7
 8 8
 9 9
10 10

Android Button click go to another xml page

Write below code in your MainActivity.java file instead of your code.

public class MainActivity extends Activity implements OnClickListener {

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

        Button mBtn1 = (Button) findViewById(R.id.mBtn1);
        mBtn1.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        Log.i("clicks","You Clicked B1");
        Intent i=new Intent(MainActivity.this, MainActivity2.class);
        startActivity(i);
    }
}

And Declare MainActivity2 into your Androidmanifest.xml file using below code.

<activity
    android:name=".MainActivity2"
    android:label="@string/title_activity_main">
</activity>

php.ini: which one?

You can find what is the php.ini file used:

  • By add phpinfo() in a php page and display the page (like the picture under)
  • From the shell, enter: php -i

Next, you can find the information in the Loaded Configuration file (so here it's /user/local/etc/php/php.ini)

Sometimes, you have indicated (none), in this case you just have to put your custom php.ini that you can find here: http://git.php.net/?p=php-src.git;a=blob;f=php.ini-production;hb=HEAD

I hope this answer will help.

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

Just to clear up... or sum up...

  • nchar and nvarchar can store Unicode characters.
  • char and varchar cannot store Unicode characters.
  • char and nchar are fixed-length which will reserve storage space for number of characters you specify even if you don't use up all that space.
  • varchar and nvarchar are variable-length which will only use up spaces for the characters you store. It will not reserve storage like char or nchar.

nchar and nvarchar will take up twice as much storage space, so it may be wise to use them only if you need Unicode support.

How to style the <option> with only CSS?

There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...

MySQL error - #1062 - Duplicate entry ' ' for key 2

Seems like the second column is set as a unique index. If you dont need that remove it and your errors will go away. Possibly you added the index by mistake and thats why you are seeing the errors today and werent seeing them yesterday

How to increase dbms_output buffer?

You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.

dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);

Check this

EDIT

As per the comment posted by Frank and Mat, you can also enable it with Null

exec dbms_output.enable(NULL);

buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).

How to increase editor font size?

As a temporary tweak ( not permanent )

On Mac you would need to create your own shortcuts ..

Its easy. my set:

CMD + Wheel-up for increase font size

CMD + Wheel-down for decreasing font size

Prefernces => Keymap => Increase Font size/decrease Font size/Reset Font size

enter image description here

Good luck,'.

How to tell if string starts with a number with Python?

Use Regular Expressions, if you are going to somehow extend method's functionality.

Update multiple rows using select statement

None of above answers worked for me in MySQL, the following query worked though:

UPDATE
    Table1 t1
    JOIN
    Table2 t2 ON t1.ID=t2.ID 
SET
    t1.value =t2.value
WHERE
    ...

Is it possible to specify condition in Count()?

@Guffa 's answer is excellent, just point out that maybe is cleaner with an IF statement

select count(IF(Position = 'Manager', 1, NULL)) as ManagerCount
from ...

Why should text files end with a newline?

I personally like new lines at the end of source code files.

It may have its origin with Linux or all UNIX systems for that matter. I remember there compilation errors (gcc if I'm not mistaken) because source code files did not end with an empty new line. Why was it made this way one is left to wonder.

Difference between getAttribute() and getParameter()

Generally, a parameter is a string value that is most commonly known for being sent from the client to the server (e.g. a form post) and retrieved from the servlet request. The frustrating exception to this is ServletContext initial parameters which are string parameters that are configured in web.xml and exist on the server.

An attribute is a server variable that exists within a specified scope i.e.:

  • application, available for the life of the entire application
  • session, available for the life of the session
  • request, only available for the life of the request
  • page (JSP only), available for the current JSP page only

INSERT SELECT statement in Oracle 11G

Get rid of the values keyword and the parens. You can see an example here.

This is basic INSERT syntax:

INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...);

This is the INSERT SELECT syntax:

INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2";

How to get last inserted row ID from WordPress database?

just like this :

global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);

simply your selecting all the rows then order them DESC by id , and displaying only the first

Android: Difference between Parcelable and Serializable?

Parcelable vs Serializable I refer these two.

For Java and Kotlin

1) Java

Serializable, the Simplicity

What is Serializable?

Serializable is a standard Java interface. It is not a part of the Android SDK. Its simplicity is its beauty. Just by implementing this interface your POJO will be ready to jump from one Activity to another.

public class TestModel implements Serializable {

String name;

public TestModel(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}
  • The beauty of serializable is that you only need to implement the Serializable interface on a class and its children. It is a marker interface, meaning that there is no method to implement, Java will simply do its best effort to serialize it efficiently.

  • The problem with this approach is that reflection is used and it is a slow process. This mechanism also tends to create a lot of temporary objects and cause quite a bit of garbage collection.

Parcelable, The Speed

What is Parcelable?

Parcelable is another interface. Despite its rival (Serializable in case you forgot), it is a part of the Android SDK. Now, Parcelable was specifically designed in such a way that there is no reflection when using it. That is because we are being really explicit for the serialization process.

public class TestModel implements Parcelable {


String name;

public TestModel(String name, String id) {
    this.name = name;
}

protected TestModel(Parcel in) {
    this.name = in.readString();


}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.name);

}

public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>() {
    @Override
    public TestModel createFromParcel(Parcel source) {
        return new TestModel(source);
    }

    @Override
    public TestModel[] newArray(int size) {
        return new TestModel[size];
    }
};
}

Now, The winner is

enter image description here

The results of the tests conducted by Philippe Breault show that Parcelable is more than 10x faster than Serializable. Some other Google engineers stand behind this statement as well.

According to them, the default Serializable approach is slower than Parcelable. And here we have an agreement between the two parties! BUT, it is unfair to compare these two at all! Because with Parcelable we are actually writing custom code. Code specifically created for that one POJO. Thus, no garbage is created and the results are better. But with the default Serializable approach, we rely on the automatic serialization process of Java. The process is apparently not custom at all and creates lots of garbage! Thus, the worse results.

Stop Stop!!!!, Before making decision

Now, there is another approach. The whole automatic process behind Serializable can be replaced by custom code which uses writeObject() & readObject() methods. These methods are specific. If we want to rely on the Serializable approach in combination with custom serialization behavior, then we must include these two methods with the same exact signature as the one below:

 private void writeObject(java.io.ObjectOutputStream out)
 throws IOException;

 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;

 private void readObjectNoData()
     throws ObjectStreamException;

And now a comparison between Parcelable and custom Serializable seems fair! The results may be surprising! The custom Serializable approach is more than 3x faster for writes and 1.6x faster for reads than Parcelable.

Edited:-----

2) Kotlinx Serialization

Kotlinx Serialization Library

For Kotlin serialization need to add below dependency and plugin

implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.9.1"

apply plugin: 'kotlinx-serialization'

Your build.gradle file

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlinx-serialization'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.smile.kotlinxretrosample"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.9.1"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.okhttp3:okhttp:3.12.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Serializing is done quite easily, you need to annotate the intended class with the @Serializable annotation as below

import kotlinx.serialization.Serializable
@Serializable
class Field {
    var count: Int = 0
    var name: String = ""
}

Two more annotations to note are transient and optional. Using transient will have the serializer ignore that field and using optional will allow the serializer not to break if a field is missing, but at the same time a default value will need to be provided.

@Optional
var isOptional: Boolean = false
@Transient
var isTransient: Boolean = false

Note: This can as well work with data classes.

Now to actually use this in action let’s take an example of how to convert a JSON to object and back

 fun toObject(stringValue: String): Field {
        return JSON.parse(Field.serializer(), stringValue)
    }

    fun toJson(field: Field): String {
        //Notice we call a serializer method which is autogenerated from our class 
        //once we have added the annotation to it
        return JSON.stringify(Field.serializer(), field)
    }

For more

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Finding the max/min value in an array of primitives using Java

Yes, it's done in the Collections class. Note that you will need to convert your primitive char array to a Character[] manually.

A short demo:

import java.util.*;

public class Main {

    public static Character[] convert(char[] chars) {
        Character[] copy = new Character[chars.length];
        for(int i = 0; i < copy.length; i++) {
            copy[i] = Character.valueOf(chars[i]);
        }
        return copy;
    }

    public static void main(String[] args) {
        char[] a = {'3', '5', '1', '4', '2'};
        Character[] b = convert(a);
        System.out.println(Collections.max(Arrays.asList(b)));
    }
}

How to remove a web site from google analytics

Updated Answer (July 22, 2015)

The solution to delete an Account/Property/View is still very similar to @Pranav ?'s answer. Google has just moved a few things around, so I thought I would update.

Step #1

Click Admin Tab at the top of the page

Step #1

Step #2

Once you are on the Admin Page, You need to decide if you want to delete the Account, Property, or View. Make sure to select the desired Account, Property, or View from the Drop Down Menu.

In the following pictures, I will show you how to delete the Account, which removes all information including Properties and Views under that particular account.

Click Account Settings to remove Account, Property Settings to remove Property, and View Settings to remove View.

Step #2

Step #3

On Account Settings, you will notice a button 'Move to Trash Can'. You will click this to remove the Account, Property or View. You will have to verify Moving the Account to the Trash Can on the next page/picture.

Step #3

Step #4

When you have verified this is the account you want to delete, go ahead and select 'Trash Account'.

Note: When you Trash an Account it moves all the information to Admin/Account/Trash Can, where it can be recovered within 1 month. Keep in mind that every Account has its own Trash Can. Once that time has lapsed the Account, Property or View will be deleted FOREVER!

Step #4

Hope this helps someone in the future, since I just struggled trying to figure it out even though its pretty simple now.

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

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

Where in memory are my variables stored in C?

A popular desktop architecture divides a process's virtual memory in several segments:

  • Text segment: contains the executable code. The instruction pointer takes values in this range.

  • Data segment: contains global variables (i.e. objects with static linkage). Subdivided in read-only data (such as string constants) and uninitialized data ("BSS").

  • Stack segment: contains the dynamic memory for the program, i.e. the free store ("heap") and the local stack frames for all the threads. Traditionally the C stack and C heap used to grow into the stack segment from opposite ends, but I believe that practice has been abandoned because it is too unsafe.

A C program typically puts objects with static storage duration into the data segment, dynamically allocated objects on the free store, and automatic objects on the call stack of the thread in which it lives.

On other platforms, such as old x86 real mode or on embedded devices, things can obviously be radically different.

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

Tried many things but found solution by added below line in my.ini and restarting mysql service.

innodb_strict_mode = 0

How can I detect window size with jQuery?

You can get the values for the width and height of the browser using the following:

$(window).height();
$(window).width();

To get notified when the browser is resized, use this bind callback:

$(window).resize(function() {
    // Do something
});

What does the 'export' command do?

export in sh and related shells (such as bash), marks an environment variable to be exported to child-processes, so that the child inherits them.

export is defined in POSIX:

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

Just to add to Jon's coding if you needed to take it a step further, and do more than just one column you can add something like

Dim copyRange2 As Range
Dim copyRange3 As Range

Set copyRange2 =src.Range("B2:B" & lastRow)
Set copyRange3 =src.Range("C2:C" & lastRow)

copyRange2.SpecialCells(xlCellTypeVisible).Copy tgt.Range("B12")
copyRange3.SpecialCells(xlCellTypeVisible).Copy tgt.Range("C12")

put these near the other codings that are the same you can easily change the Ranges as you need.

I only add this because it was helpful for me. I'd assume Jon already knows this but for those that are less experienced sometimes it's helpful to see how to change/add/modify these codings. I figured since Ruya didn't know how to manipulate the original coding it could be helpful if one ever needed to copy over only 2 visibile columns, or only 3, etc. You can use this same coding, add in extra lines that are almost the same and then the coding is copying over whatever you need.

I don't have enough reputation to reply to Jon's comment directly so I have to post as a new comment, sorry.

Wait 5 seconds before executing next line

Use a delay function like this:

var delay = ( function() {
    var timer = 0;
    return function(callback, ms) {
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    };
})();

Usage:

delay(function(){
    // do stuff
}, 5000 ); // end delay

Credits: How to delay the .keyup() handler until the user stops typing?

How is attr_accessible used in Rails 4?

If you prefer attr_accessible, you could use it in Rails 4 too. You should install it like gem:

gem 'protected_attributes'

after that you could use attr_accessible in you models like in Rails 3

Also, and i think that is the best way- using form objects for dealing with mass assignment, and saving nested objects, and you can also use protected_attributes gem that way

class NestedForm
   include  ActiveModel::MassAssignmentSecurity
   attr_accessible :name,
                   :telephone, as: :create_params
   def create_objects(params)
      SomeModel.new(sanitized_params(params, :create_params))
   end
end

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

automating telnet session using bash scripts

While I'd suggest using expect, too, for non-interactive use the normal shell commands might suffice. Telnet accepts its command on stdin, so you just need to pipe or write the commands into it:

telnet 10.1.1.1 <<EOF
remotecommand 1
remotecommand 2
EOF

(Edit: Judging from the comments, the remote command needs some time to process the inputs or the early SIGHUP is not taken gracefully by the telnet. In these cases, you might try a short sleep on the input:)

{ echo "remotecommand 1"; echo "remotecommand 2"; sleep 1; } | telnet 10.1.1.1

In any case, if it's getting interactive or anything, use expect.

Twitter Bootstrap onclick event on buttons-radio

I would use a change event not a click like this:

$('input[name="name-of-radio-group"]').change( function() {
  alert($(this).val())
})

How to display activity indicator in middle of the iphone screen?

Try this way

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame = CGRectMake(10.0, 0.0, 40.0, 40.0);
    activityIndicator.center = super_view.center;
    [super_view addSubview: activityIndicator];

[activityIndicator startAnimating];

How to install PyQt5 on Windows?

If you are using canopy, use the package manager to install qt (and or pyqt)

Spring application context external properties?

This blog can help you. The trick is to use SpEL (spring expression language) to read the system properties like user.home, to read user home directory using SpEL you could use
#{ systemProperties['user.home']} expression inside your bean elements. For example to access your properties file stored in your home directory you could use the following in your PropertyPlaceholderConfigurer, it worked for me.

 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>file:#{ systemProperties['user.home']}/ur_folder/settings.properties</value>
    </property>
</bean>

How to convert hashmap to JSON object in Java

    import org.json.JSONObject;

    HashMap<Object, Object> map = new HashMap<>();
    String[] list={"Grader","Participant"};
    String[] list1={"Assistant","intern"};
    map.put("TeachingAssistant",list);
    map.put("Writer",list1);
    JSONObject jsonObject = new JSONObject(map);
    System.out.printf(jsonObject.toString());

    // Result: {"TeachingAssistant":["Grader","Participant"],"Writer":["Assistant","intern"]}

Access IP Camera in Python OpenCV

In pycharm I wrote the code for accessing the IP Camera like:

import cv2

cap=VideoCapture("rtsp://user_name:password@IP_address:port_number")

ret, frame=cap.read()

You will need to replace user_name, password, IP and port with suitable values

How is a CRC32 checksum calculated?

I spent a while trying to uncover the answer to this question, and I finally published a tutorial on CRC-32 today: CRC-32 hash tutorial - AutoHotkey Community

In this example from it, I demonstrate how to calculate the CRC-32 hash for the ASCII string 'abc':

calculate the CRC-32 hash for the ASCII string 'abc':

inputs:
dividend: binary for 'abc': 0b011000010110001001100011 = 0x616263
polynomial: 0b100000100110000010001110110110111 = 0x104C11DB7

011000010110001001100011
reverse bits in each byte:
100001100100011011000110
append 32 0 bits:
10000110010001101100011000000000000000000000000000000000
XOR the first 4 bytes with 0xFFFFFFFF:
01111001101110010011100111111111000000000000000000000000

'CRC division':
01111001101110010011100111111111000000000000000000000000
 100000100110000010001110110110111
 ---------------------------------
  111000100010010111111010010010110
  100000100110000010001110110110111
  ---------------------------------
   110000001000101011101001001000010
   100000100110000010001110110110111
   ---------------------------------
    100001011101010011001111111101010
    100000100110000010001110110110111
    ---------------------------------
         111101101000100000100101110100000
         100000100110000010001110110110111
         ---------------------------------
          111010011101000101010110000101110
          100000100110000010001110110110111
          ---------------------------------
           110101110110001110110001100110010
           100000100110000010001110110110111
           ---------------------------------
            101010100000011001111110100001010
            100000100110000010001110110110111
            ---------------------------------
              101000011001101111000001011110100
              100000100110000010001110110110111
              ---------------------------------
                100011111110110100111110100001100
                100000100110000010001110110110111
                ---------------------------------
                    110110001101101100000101110110000
                    100000100110000010001110110110111
                    ---------------------------------
                     101101010111011100010110000001110
                     100000100110000010001110110110111
                     ---------------------------------
                       110111000101111001100011011100100
                       100000100110000010001110110110111
                       ---------------------------------
                        10111100011111011101101101010011

remainder: 0b10111100011111011101101101010011 = 0xBC7DDB53
XOR the remainder with 0xFFFFFFFF:
0b01000011100000100010010010101100 = 0x438224AC
reverse bits:
0b00110101001001000100000111000010 = 0x352441C2

thus the CRC-32 hash for the ASCII string 'abc' is 0x352441C2

How do I center content in a div using CSS?

Update 2020:

There are several options available*:

*Disclaimer: This list may not be complete.

Using Flexbox
Nowadays, we can use flexbox. It is quite a handy alternative to the css-transform option. I would use this solution almost always. If it is just one element maybe not, but for example if I had to support an array of data e.g. rows and columns and I want them to be relatively centered in the very middle.

_x000D_
_x000D_
.flexbox {
  display: flex;
  height: 100px;
  flex-flow: row wrap;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  /* default => flex: 0 1 auto */
  background-color: #fff;
  border: 1px dotted #333;
  box-sizing: border-box;
}
_x000D_
<div class="flexbox">
  <div class="item">I am centered in the middle.</div>
  <div class="item">I am centered in the middle, too.</div>
</div>
_x000D_
_x000D_
_x000D_


Using CSS 2D-Transform
This is still a good option, was also the accepted solution back in 2015. It is very slim and simple to apply and does not mess with the layouting of other elements.

_x000D_
_x000D_
.boxes {
  position: relative;
}

.box {
  position: relative;
  display: inline-block;
  float: left;
  width: 200px;
  height: 200px;
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  margin-bottom: 10px;
  background-color: #eaeaea;
}

.h-center {
  text-align: center;
}

.v-center span {
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translate(0, -50%);
}
_x000D_
<div class="boxes">
  <div class="box h-center">horizontally centered lorem ipsun dolor sit amet</div>
  <div class="box v-center"><span>vertically centered lorem ipsun dolor sit amet lorem ipsun dolor sit amet</span></div>
  <div class="box h-center v-center"><span>horizontally and vertically centered lorem ipsun dolor sit amet</span></div>
</div>
_x000D_
_x000D_
_x000D_

Note: This does also work with :after and :before pseudo-elements.


Using Grid
This might just be an overkill, but it depends on your DOM. If you want to use grid anyway, then why not. It is very powerful alternative and you are really maximum flexible with the design.

Note: To align the items vertically we use flexbox in combination with grid. But we could also use display: grid on the items.

_x000D_
_x000D_
.grid {
  display: grid;
  width: 400px;
  grid-template-rows: 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dotted #333;
  box-sizing: border-box;
}

.item-large {
  height: 80px;
}
_x000D_
<div class="grid">
  <div class="item">Item 1</div>
  <div class="item item-large">Item 2</div>
  <div class="item">Item 3</div>
</div>
_x000D_
_x000D_
_x000D_


Further reading:

CSS article about grid
CSS article about flexbox
CSS article about centering without flexbox or grid

Xcode: Could not locate device support files

Actually, there is a way. You just need to copy DeviceSupport folder for iOS 7.1 from Older Xcode to the new one. It's located in:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.1

If you don't have the 7.1 files anymore, you can download a previous version of XCode on https://developer.apple.com/download/more/, extract it, and then copy these files to following path

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/

Credit

Difference between null and empty ("") Java String

enter image description here

This image might help you to understand the differences.

The image was collected from ProgrammerHumor

How to check if the string is empty?

If you just use

not var1 

it is not possible to difference a variable which is boolean False from an empty string '':

var1 = ''
not var1
> True

var1 = False
not var1
> True

However, if you add a simple condition to your script, the difference is made:

var1  = False
not var1 and var1 != ''
> True

var1 = ''
not var1 and var1 != ''
> False

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

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

Read file-contents into a string in C++

The most efficient is to create a buffer of the correct size and then read the file into the buffer.

#include <fstream>
#include <vector>

int main()
{
    std::ifstream       file("Plop");
    if (file)
    {
        /*
         * Get the size of the file
         */
        file.seekg(0,std::ios::end);
        std::streampos          length = file.tellg();
        file.seekg(0,std::ios::beg);

        /*
         * Use a vector as the buffer.
         * It is exception safe and will be tidied up correctly.
         * This constructor creates a buffer of the correct length.
         * Because char is a POD data type it is not initialized.
         *
         * Then read the whole file into the buffer.
         */
        std::vector<char>       buffer(length);
        file.read(&buffer[0],length);
    }
}

difference between iframe, embed and object elements

Another reason to use object over iframe is that object sub resources (when an <object> performs HTTP requests) are considered as passive/display in terms of Mixed content, which means it's more secure when you must have Mixed content.

Mixed content means that when you have https but your resource is from http.

Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content

How can I add additional PHP versions to MAMP

If you need to be able to switch between more than two versions at a time, you can use the following to change the version of PHP manually.

MAMP automatically rewrites the following line in your /Applications/MAMP/conf/apache/httpd.conf file when it restarts based on the settings in preferences. You can comment out this line and add the second one to the end of your file:

# Comment this out just under all the modules loaded
# LoadModule php5_module        /Applications/MAMP/bin/php/php5.x.x/modules/libphp5.so

At the bottom of the httpd.conf file, you'll see where additional configurations are loaded from the extra folder. Add this to the bottom of the httpd.conf file

# PHP Version Change
Include /Applications/MAMP/conf/apache/extra/httpd-php.conf

Then create a new file here: /Applications/MAMP/conf/apache/extra/httpd-php.conf

# Uncomment the version of PHP you want to run with MAMP
# LoadModule php5_module /Applications/MAMP/bin/php/php5.2.17/modules/libphp5.so
# LoadModule php5_module /Applications/MAMP/bin/php/php5.3.27/modules/libphp5.so
# LoadModule php5_module /Applications/MAMP/bin/php/php5.4.19/modules/libphp5.so
LoadModule php5_module /Applications/MAMP/bin/php/php5.5.3/modules/libphp5.so

After you have this setup, just uncomment the version of PHP you want to use and restart the servers!

Easy login script without database

Save the username and password hashes in array in a php file instead of db.

When you need to authenticate the user, compute hashes of his credentials and then compare them to hashes in array.

If you use safe hash function (see hash function and hash algos in PHP documentation), it should be pretty safe (you may consider using salted hash) and also add some protections to the form itself.

Get current URL from IFRAME

I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:

    const iframeReference = document.getElementById("iframe_id");
    const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
    if (iframeUrl) {
        console.log("Voila: " + iframeUrl);
    } else {
        console.warn("iframe with id iframe_id not found");
    }

MySQL SELECT LIKE or REGEXP to match multiple words in one record

You can just replace each space with %

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%2100%'

error: Error parsing XML: not well-formed (invalid token) ...?

It means there is a compilation error in your XML file, something that shouldn't be there: a spelling mistake/a spurious character/an incorrect namespace.

Your issue is you've got a semicolon that shouldn't be there after this line:

  android:text="@string/hello";

Add/remove class with jquery based on vertical scroll?

In a similar case, I wanted to avoid always calling addClass or removeClass due to performance issues. I've split the scroll handler function into two individual functions, used according to the current state. I also added a debounce functionality according to this article: https://developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers

        var $header = jQuery( ".clearHeader" );         
        var appScroll = appScrollForward;
        var appScrollPosition = 0;
        var scheduledAnimationFrame = false;

        function appScrollReverse() {
            scheduledAnimationFrame = false;
            if ( appScrollPosition > 500 )
                return;
            $header.removeClass( "darkHeader" );
            appScroll = appScrollForward;
        }

        function appScrollForward() {
            scheduledAnimationFrame = false;
            if ( appScrollPosition < 500 )
                return;
            $header.addClass( "darkHeader" );
            appScroll = appScrollReverse;
        }

        function appScrollHandler() {
            appScrollPosition = window.pageYOffset;
            if ( scheduledAnimationFrame )
                return;
            scheduledAnimationFrame = true;
            requestAnimationFrame( appScroll );
        }

        jQuery( window ).scroll( appScrollHandler );

Maybe someone finds this helpful.

Correct way of looping through C++ arrays

string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
    cout << "value of a: " << texts[a] << endl;
}

Nope. Totally a wrong way of iterating through an array. sizeof(texts) is not equal to the number of elements in the array!

The modern, C++11 ways would be to:

  • use std::array if you want an array whose size is known at compile-time; or
  • use std::vector if its size depends on runtime

Then use range-for when iterating.

#include <iostream>
#include <array>


int main() {
    std::array<std::string, 3> texts = {"Apple", "Banana", "Orange"};
    // ^ An array of 3 elements with the type std::string

    for(const auto& text : texts) {   // Range-for!
        std::cout << text << std::endl;
    }
}

Live example


You may ask, how is std::array better than the ol' C array? The answer is that it has the additional safety and features of other standard library containers, mostly closely resembling std::vector. Further, The answer is that it doesn't have the quirks of decaying to pointers and thus losing type information, which, once you lose the original array type, you can't use range-for or std::begin/end on it.

How to create an array containing 1...N

Just another ES6 version.

By making use of Array.from second optional argument:

Array.from(arrayLike[, mapFn[, thisArg]])

We can build the numbered array from the empty Array(10) positions:

Array.from(Array(10), (_, i) => i)

_x000D_
_x000D_
var arr = Array.from(Array(10), (_, i) => i);_x000D_
document.write(arr);
_x000D_
_x000D_
_x000D_

Is embedding background image data into CSS as Base64 good or bad practice?

One of the things I would suggest is to have two separate stylesheets: One with your regular style definitions and another one that contains your images in base64 encoding.

You have to include the base stylesheet before the image stylesheet of course.

This way you will assure that you're regular stylesheet is downloaded and applied as soon as possible to the document, yet at the same time you profit from reduced http-requests and other benefits data-uris give you.

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.

This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )

SELECT questionid,
       LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
       KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM   (SELECT questionid,
               elementid,
               ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
               ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
        FROM   emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;

PowerShell script to check the status of a URL

You can try this:

function Get-UrlStatusCode([string] $Url)
{
    try
    {
        (Invoke-WebRequest -Uri $Url -UseBasicParsing -DisableKeepAlive).StatusCode
    }
    catch [Net.WebException]
    {
        [int]$_.Exception.Response.StatusCode
    }
}

$statusCode = Get-UrlStatusCode 'httpstat.us/500'

Easiest way to compare arrays in C#

You can use Enumerable.Intersect:

int[] array1 = new int[] { 1, 2, 3, 4,5 },
      array2 = new int[] {7,8};

if (array1.Intersect(array2).Any())
    Console.WriteLine("matched");
else
    Console.WriteLine("not matched");

Java and HTTPS url connection without downloading certificate

Java and HTTPS url connection without downloading certificate

If you really want to avoid downloading the server's certificate, then use an anonymous protocol like Anonymous Diffie-Hellman (ADH). The server's certificate is not sent with ADH and friends.

You select an anonymous protocol with setEnabledCipherSuites. You can see the list of cipher suites available with getEnabledCipherSuites.

Related: that's why you have to call SSL_get_peer_certificate in OpenSSL. You'll get a X509_V_OK with an anonymous protocol, and that's how you check to see if a certificate was used in the exchange.

But as Bruno and Stephed C stated, its a bad idea to avoid the checks or use an anonymous protocol.


Another option is to use TLS-PSK or TLS-SRP. They don't require server certificates either. (But I don't think you can use them).

The rub is, you need to be pre-provisioned in the system because TLS-PSK is Pres-shared Secret and TLS-SRP is Secure Remote Password. The authentication is mutual rather than server only.

In this case, the mutual authentication is provided by a property that both parties know the shared secret and arrive at the same premaster secret; or one (or both) does not and channel setup fails. Each party proves knowledge of the secret is the "mutual" part.

Finally, TLS-PSK or TLS-SRP don't do dumb things, like cough up the user's password like in a web app using HTTP (or over HTTPS). That's why I said each party proves knowledge of the secret...

Bash: infinite sleep (infinite blocking)

Let me explain why sleep infinity works though it is not documented. jp48's answer is also useful.

The most important thing: By specifying inf or infinity (both case-insensitive), you can sleep for the longest time your implementation permits (i.e. the smaller value of HUGE_VAL and TYPE_MAXIMUM(time_t)).

Now let's dig into the details. The source code of sleep command can be read from coreutils/src/sleep.c. Essentially, the function does this:

double s; //seconds
xstrtod (argv[i], &p, &s, cl_strtod); //`p` is not essential (just used for error check).
xnanosleep (s);

Understanding xstrtod (argv[i], &p, &s, cl_strtod)

xstrtod()

According to gnulib/lib/xstrtod.c, the call of xstrtod() converts string argv[i] to a floating point value and stores it to *s, using a converting function cl_strtod().

cl_strtod()

As can be seen from coreutils/lib/cl-strtod.c, cl_strtod() converts a string to a floating point value, using strtod().

strtod()

According to man 3 strtod, strtod() converts a string to a value of type double. The manpage says

The expected form of the (initial portion of the) string is ... or (iii) an infinity, or ...

and an infinity is defined as

An infinity is either "INF" or "INFINITY", disregarding case.

Although the document tells

If the correct value would cause overflow, plus or minus HUGE_VAL (HUGE_VALF, HUGE_VALL) is returned

, it is not clear how an infinity is treated. So let's see the source code gnulib/lib/strtod.c. What we want to read is

else if (c_tolower (*s) == 'i'
         && c_tolower (s[1]) == 'n'
         && c_tolower (s[2]) == 'f')
  {
    s += 3;
    if (c_tolower (*s) == 'i'
        && c_tolower (s[1]) == 'n'
        && c_tolower (s[2]) == 'i'
        && c_tolower (s[3]) == 't'
        && c_tolower (s[4]) == 'y')
      s += 5;
    num = HUGE_VAL;
    errno = saved_errno;
  }

Thus, INF and INFINITY (both case-insensitive) are regarded as HUGE_VAL.

HUGE_VAL family

Let's use N1570 as the C standard. HUGE_VAL, HUGE_VALF and HUGE_VALL macros are defined in §7.12-3

The macro
    HUGE_VAL
expands to a positive double constant expression, not necessarily representable as a float. The macros
    HUGE_VALF
    HUGE_VALL
are respectively float and long double analogs of HUGE_VAL.

HUGE_VAL, HUGE_VALF, and HUGE_VALL can be positive infinities in an implementation that supports infinities.

and in §7.12.1-5

If a floating result overflows and default rounding is in effect, then the function returns the value of the macro HUGE_VAL, HUGE_VALF, or HUGE_VALL according to the return type

Understanding xnanosleep (s)

Now we understand all essence of xstrtod(). From the explanations above, it is crystal-clear that xnanosleep(s) we've seen first actually means xnanosleep(HUGE_VALL).

xnanosleep()

According to the source code gnulib/lib/xnanosleep.c, xnanosleep(s) essentially does this:

struct timespec ts_sleep = dtotimespec (s);
nanosleep (&ts_sleep, NULL);

dtotimespec()

This function converts an argument of type double to an object of type struct timespec. Since it is very simple, let me cite the source code gnulib/lib/dtotimespec.c. All of the comments are added by me.

struct timespec
dtotimespec (double sec)
{
  if (! (TYPE_MINIMUM (time_t) < sec)) //underflow case
    return make_timespec (TYPE_MINIMUM (time_t), 0);
  else if (! (sec < 1.0 + TYPE_MAXIMUM (time_t))) //overflow case
    return make_timespec (TYPE_MAXIMUM (time_t), TIMESPEC_HZ - 1);
  else //normal case (looks complex but does nothing technical)
    {
      time_t s = sec;
      double frac = TIMESPEC_HZ * (sec - s);
      long ns = frac;
      ns += ns < frac;
      s += ns / TIMESPEC_HZ;
      ns %= TIMESPEC_HZ;

      if (ns < 0)
        {
          s--;
          ns += TIMESPEC_HZ;
        }

      return make_timespec (s, ns);
    }
}

Since time_t is defined as an integral type (see §7.27.1-3), it is natural we assume the maximum value of type time_t is smaller than HUGE_VAL (of type double), which means we enter the overflow case. (Actually this assumption is not needed since, in all cases, the procedure is essentially the same.)

make_timespec()

The last wall we have to climb up is make_timespec(). Very fortunately, it is so simple that citing the source code gnulib/lib/timespec.h is enough.

_GL_TIMESPEC_INLINE struct timespec
make_timespec (time_t s, long int ns)
{
  struct timespec r;
  r.tv_sec = s;
  r.tv_nsec = ns;
  return r;
}

Extract a substring according to a pattern

For example using gsub or sub

    gsub('.*:(.*)','\\1',string)
    [1] "E001" "E002" "E003"

Parsing XML with namespace in Python via 'ElementTree'

Here's how to do this with lxml without having to hard-code the namespaces or scan the text for them (as Martijn Pieters mentions):

from lxml import etree
tree = etree.parse("filename")
root = tree.getroot()
root.findall('owl:Class', root.nsmap)

UPDATE:

5 years later I'm still running into variations of this issue. lxml helps as I showed above, but not in every case. The commenters may have a valid point regarding this technique when it comes merging documents, but I think most people are having difficulty simply searching documents.

Here's another case and how I handled it:

<?xml version="1.0" ?><Tag1 xmlns="http://www.mynamespace.com/prefix">
<Tag2>content</Tag2></Tag1>

xmlns without a prefix means that unprefixed tags get this default namespace. This means when you search for Tag2, you need to include the namespace to find it. However, lxml creates an nsmap entry with None as the key, and I couldn't find a way to search for it. So, I created a new namespace dictionary like this

namespaces = {}
# response uses a default namespace, and tags don't mention it
# create a new ns map using an identifier of our choice
for k,v in root.nsmap.iteritems():
    if not k:
        namespaces['myprefix'] = v
e = root.find('myprefix:Tag2', namespaces)

Check if image exists on server using JavaScript?

You can use the basic way image preloaders work to test if an image exists.

function checkImage(imageSrc, good, bad) {
    var img = new Image();
    img.onload = good; 
    img.onerror = bad;
    img.src = imageSrc;
}

checkImage("foo.gif", function(){ alert("good"); }, function(){ alert("bad"); } );

JSFiddle

How to center cards in bootstrap 4?

Put the elements which you want to shift to the centre within this div tag.

<div class="col d-flex justify-content-center">
</div>

Operand type clash: uniqueidentifier is incompatible with int

If you're accessing this via a View then try sp_recompile or refreshing views.

sp_recompile:

Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.

Arguments

[ @objname= ] 'object'

The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or view will be recompiled the next time that they are run.

Return Code Values

0 (success) or a nonzero number (failure)

Remarks

sp_recompile looks for an object in the current database only.

The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures, triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.

Callback when CSS3 transition finishes

For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.

var cssAnimate = function(cssClass, callback) {
    var self = this;

    // Checks if correct animation has ended
    var setAnimationListener = function() {
        self.one(
            "webkitAnimationEnd oanimationend msAnimationEnd animationend",
            function(e) {
                if(
                    e.originalEvent.animationName == cssClass &&
                    e.target === e.currentTarget
                ) {
                    callback();
                } else {
                    setAnimationListener();
                }
            }
        );
    }

    self.addClass(cssClass);
    setAnimationListener();
}

I used it kinda like this

cssAnimate.call($("#something"), "fadeIn", function() {
    console.log("Animation is complete");
    // Remove animation class name?
});

Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/

And this seems handy: http://api.jqueryui.com/addClass/


Update

After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

What is a good game engine that uses Lua?

Game engines that use Lua

Free unless noted

  • Agen (2D Lua; Windows)
  • Amulet (2D Lua; Window, Linux, Mac, HTML5, iOS)
  • Cafu 3D (3D C++/Lua)
  • Cocos2d-x (2D C++/Lua/JS; Windows, Linux, Mac, iOS, Android, BlackBerry)
  • Codea (2D&3D Lua; iOS (Editor is iOs app); $14.99 USD)
  • Cryengine by Crytek (3D C++/Lua; Windows, Mac)
  • Defold (2D Lua; Windows, Linux, Mac, iOS, Android, Web, Switch)
  • gengine (2D Lua; Windows, Linux, HTML5)
  • Irrlicht (3D C++/.NET/Lua; Windows, Linux, Mac)
  • Leadwerks (3D C++/C#/Delphi/BlitzMax/Lua; Windows; $199.95 USD)
  • LÖVE (2D Lua; Windows, Linux, Mac)
  • MOAI (2D C++/Lua; Windows, Linux, Mac, iOS, Android, Google Chrome (Native Client))
  • Solar2D (was Corona) (2D Lua; Windows, Mac, iOS, Android)
  • Spring RTS Engine (3D C++/Lua; Linux, Windows, Mac)
  • Wicked Engine (3D C++/Lua; Linux, Windows 10, Windows Phone, XBox One)

Bindings:

  • Raylib via raylib-lua-sol (2D&3D C++/Lua/Others; Windows, Linux, Mac, Android, Web, Other Ports)
  • SDL2 via luasdl2 (2D&3D C++/Lua/Others; Windows, Linux, Mac, Android, Console Ports)

Fantasy Consoles:

Editor and games run in an emulated computer system

  • PICO-8 (2D Lua; Windows, Linux, Mac, Raspberry Pi, Web Player $14.99 USD)
  • TIC-80 (2D Lua; Windows, Linux, Mac, Web)

Inactive/Discontinued:

  • Baja Engine (3D C++/Lua; Windows, Mac, No Release since Dec 2008)
  • Blitwizard (2D Lua; Windows, Linux, Mac, Development stopped in May 2014)
  • Drystal (2D Lua; Linux, HTML5)
  • EGSL (2D Pascal/Lua; Windows, Linux, Mac, Haiku)
  • Glint 3d Engine (3D Lua, Development stopped in Nov 2011)
  • Grail Adventure Game Engine (2D C++/Lua; Windows, Linux, Mac (SDL))
  • Juno (2D Lua; Windows, Linux, Mac, last commit on Friday the 13th, May 2016)
  • Lavgine (2.5D C++/Lua, Windows)
  • Luxinia (3D C/Lua; Windows, Development stopped in Dec 2018)
  • Polycode (2D&3D C++/Lua; Windows, Linux, Mac)

How to insert a timestamp in Oracle?

I prefer ANSI timestamp literals:

insert into the_table 
  (the_timestamp_column)
values 
  (timestamp '2017-10-12 21:22:23');

More details in the manual: https://docs.oracle.com/database/121/SQLRF/sql_elements003.htm#SQLRF51062

Kubernetes pod gets recreated when deleted

Instead of removing NS you can try removing replicaSet

kubectl get rs --all-namespaces

Then delete the replicaSet

kubectl delete rs your_app_name

Get environment value in controller

It's a better idea to put your configuration variables in a configuration file.

In your case, I would suggest putting your variables in config/mail.php like:

'imap_hostname' => env('IMAP_HOSTNAME_TEST', 'imap.gmail.com')

And refer to them by

config('mail.imap_hostname')

It first tries to get the configuration variable value in the .env file and if it couldn't find the variable value in the .env file, it will get the variable value from file config/mail.php.

How to delete all rows from all tables in a SQL Server database?

In my recent project my task was to clean an entire database by using sql statement and each table having many constraints like Primary Key and Foreign Key. There are more than 1000 tables in database so its not possible to write a delete query on each and ever table.

By using a stored procedure named sp_MSForEachTable which allows us to easily process some code against each and every table in a single database. It means that it is used to process a single T-SQL command or a different T-SQL commands against every table in the database.

So follow the below steps to truncate all tables in a SQL Server Database:

Step 1- Disable all constraints on the database by using below sql query :

EXEC sys.sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'

Step 2- Execute a Delete or truncate operation on each table of the database by using below sql command :

EXEC sys.sp_msforeachtable 'DELETE FROM ?'

Step 3- Enable all constraints on the database by using below sql statement:

EXEC sys.sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'

How to get a pixel's x,y coordinate color from an image?

The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.

MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.

For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).

enter image description here

Console output:

(0,0): TRANSPARENT
(150,150): NOT_TRANSPARENT

_x000D_
_x000D_
image = new MarvinImage();_x000D_
image.load("https://i.imgur.com/eLZVbQG.png", imageLoaded);_x000D_
_x000D_
function imageLoaded(){_x000D_
  console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
  console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
}
_x000D_
<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
_x000D_
_x000D_
_x000D_

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You only have to add group = 1 into the ggplot or geom_line aes().

For line graphs, the data points must be grouped so that it knows which points to connect. In this case, it is simple -- all points should be connected, so group=1. When more variables are used and multiple lines are drawn, the grouping for lines is usually done by variable.

Reference: Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.

Try this:

plot5 <- ggplot(df, aes(year, pollution, group = 1)) +
         geom_point() +
         geom_line() +
         labs(x = "Year", y = "Particulate matter emissions (tons)", 
              title = "Motor vehicle emissions in Baltimore")

Best implementation for hashCode method for a collection

@about8 : there is a pretty serious bug there.

Zam obj1 = new Zam("foo", "bar", "baz");
Zam obj2 = new Zam("fo", "obar", "baz");

same hashcode

you probably want something like

public int hashCode() {
    return (getFoo().hashCode() + getBar().hashCode()).toString().hashCode();

(can you get hashCode directly from int in Java these days? I think it does some autocasting.. if that's the case, skip the toString, it's ugly.)

Math operations from string

The asker commented:

I figure that if I understand a problem well enough to write a program that can figure it out, I don't need to do the work manually.

If he's writing a math expression solver as a learning exercise, using eval() isn't going to help. Plus it's terrible design.

You might consider making a calculator using Reverse Polish Notation instead of standard math notation. It simplifies the parsing considerably. It would still be a good exercise

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

Could not find module FindOpenCV.cmake ( Error in configuration process)

On my Fedora machine, when I typed "make" I got an error saying it could not find "cv.h". I fixed this by modifying my "OpenCVConfig.cmake" file.

Before:

SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")

SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib64")

After:

SET(OpenCV_INCLUDE_DIRS "/usr/include/opencv;/usr/include/opencv2")

SET(OpenCV_LIB_DIR "/usr/lib64")

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

I added a reference to the .dll file, for System.Data.Linq, the above was not sufficient. You can find .dll in the various directories for the following versions.

System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll 3.5.0.0

System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Data.Linq.dll 4.0.0.0

CSS background-size: cover replacement for Mobile Safari

I've had this issue on a lot of mobile views I've recently built.

My solution is still a pure CSS Fallback

http://css-tricks.com/perfect-full-page-background-image/ as three great methods, the latter two are fall backs for when CSS3's cover doesn't work.

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg {
  position: fixed; 
  top: 0; 
  left: 0; 

  /* Preserve aspect ratio */
  min-width: 100%;
  min-height: 100%;
}

python: urllib2 how to send cookie with urlopen request

This answer is not working since the urllib2 module has been split across several modules in Python 3. You need to do

from urllib import request
opener = request.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

How to change identity column values programmatically?

Very nice question, first we need to on the IDENTITY_INSERT for the specific table, after that run the insert query (Must specify the column name).

Note: After edit the the identity column, don't forget to off the IDENTITY_INSERT. If you not done, you cannot able to Edit the identity column for any other table.

SET IDENTITY_INSERT Emp_tb_gb_Menu ON
     INSERT Emp_tb_gb_Menu(MenuID) VALUES (68)
SET IDENTITY_INSERT Emp_tb_gb_Menu OFF

http://allinworld99.blogspot.com/2016/07/how-to-edit-identity-field-in-sql.html

Accessing Object Memory Address

You can get something suitable for that purpose with:

id(self)

How to check if a process id (PID) exists

For example in GNU/Linux you can use:

Pid=$(pidof `process_name`)

if [ $Pid > 0 ]; then

   do something
else

   do something
fi 

Or something like

Pin=$(ps -A | grep name | awk 'print $4}')
echo $PIN

and that shows you the name of the app, just the name without ID.

How to disable margin-collapsing?

In newer browser (excluding IE11), a simple solution to prevent parent-child margin collapsing is to use display: flow-root. However, you would still need other techniques to prevent adjacent element collapsing.

DEMO (before)

_x000D_
_x000D_
.parent {_x000D_
  background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  height: 16px;_x000D_
  margin-top: 16px;_x000D_
  margin-bottom: 16px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

DEMO (after)

_x000D_
_x000D_
.parent {_x000D_
  display: flow-root;_x000D_
  background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  height: 16px;_x000D_
  margin-top: 16px;_x000D_
  margin-bottom: 16px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

sprintf like functionality in Python

If you want something like the python3 print function but to a string:

def sprint(*args, **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, file=sio)
    return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}\n"

or without the '\n' at the end:

def sprint(*args, end='', **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, end=end, file=sio)
    return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}"

Curl to return http status code along with the response

This is a way to retrieve the body "AND" the status code and format it to a proper json or whatever format works for you. Some may argue it's the incorrect use of write format option but this works for me when I need both body and status code in my scripts to check status code and relay back the responses from server.

curl -X GET -w "%{stderr}{\"status\": \"%{http_code}\", \"body\":\"%{stdout}\"}"  -s -o - “https://github.com” 2>&1

run the code above and you should get back a json in this format:

{
"status" : <status code>,
"body" : <body of response>
}

with the -w write format option, since stderr is printed first, you can format your output with the var http_code and place the body of the response in a value (body) and follow up the enclosing using var stdout. Then redirect your stderr output to stdout and you'll be able to combine both http_code and response body into a neat output

Restore the mysql database from .frm files

I answered this question here, as well: https://dba.stackexchange.com/a/42932/24122

I recently experienced this same issue. I'm on a Mac and so I used MAMP in order to restore the Database to a point where I could export it in a MySQL dump.

You can read the full blog post about it here: http://www.quora.com/Jordan-Ryan/Web-Dev/How-to-Recover-innoDB-MySQL-files-using-MAMP-on-a-Mac

You must have:

-ibdata1

-ib_logfile0

-ib_logfile1

-.FRM files from your mysql_database folder

-Fresh installation of MAMP / MAMP Pro that you are willing to destroy (if need be)

  1. SSH into your web server (dev, production, no difference) and browse to your mysql folder (mine was at /var/lib/mysql for a Plesk installation on Linux)
  2. Compress the mysql folder
  3. Download an archive of mysql folder which should contain all mySQL databases, whether MyISAM or innoDB (you can scp this file, or move this to a downloadable directory, if need be)
  4. Install MAMP (Mac, Apache, MySQL, PHP)
  5. Browse to /Applications/MAMP/db/mysql/
  6. Backup /Applications/MAMP/db/mysql to a zip archive (just in case)
  7. Copy in all folders and files included in the archive of the mysql folder from the production server (mt Plesk environment in my case) EXCEPT DO NOT OVERWRITE:

    -/Applications/MAMP/db/mysql/mysql/

    -/Applications/MAMP/db/mysql/mysql_upgrade_info

    -/Applications/MAMP/db/mysql/performance_schema

  8. And voila, you now should be able to access the databases from phpMyAdmin, what a relief!

But we're not done, you now need to perform a mysqldump in order to restore these files to your production environment, and the phpmyadmin interface times out for large databases. Follow the steps here:

http://nickhardeman.com/308/export-import-large-database-using-mamp-with-terminal/

Copied below for reference. Note that on a default MAMP installation, the password is "root".

How to run mysqldump for MAMP using Terminal

EXPORT DATABASE FROM MAMP[1]

Step One: Open a new terminal window

Step Two: Navigate to the MAMP install by entering the following line in terminal cd /applications/MAMP/library/bin Hit the enter key

Step Three: Write the dump command ./mysqldump -u [USERNAME] -p [DATA_BASENAME] > [PATH_TO_FILE] Hit the enter key

Example:

./mysqldump -u root -p wp_database > /Applications/MAMP/htdocs/symposium10_wp/wp_db_onezero.sql

Quick tip: to navigate to a folder quickly you can drag the folder into the terminal window and it will write the location of the folder. It was a great day when someone showed me this.

Step Four: This line of text should appear after you hit enter Enter password: So guess what, type your password, keep in mind that the letters will not appear, but they are there Hit the enter key

Step Five: Check the location of where you stored your file, if it is there, SUCCESS Now you can import the database, which will be outlined next.

Now that you have an export of your mysql database you can import it on the production environment.

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

I got the same error as I didn't save the script before executing it. Check to see if you have saved it!

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

I like Brian R. Bondy's answer. I just wanted to add that Wikipedia provides a clear description of REST. The article distinguishes it from SOAP.

REST is an exchange of state information, done as simply as possible.

SOAP is a message protocol that uses XML.

One of the main reasons that many people have moved from SOAP to REST is that the WS-* (called WS splat) standards associated with SOAP based web services are EXTREMELY complicated. See wikipedia for a list of the specifications. Each of these specifications is very complicated.

EDIT: for some reason the links are not displaying correctly. REST = http://en.wikipedia.org/wiki/REST

WS-* = http://en.wikipedia.org/wiki/WS-*

How do I use Linq to obtain a unique list of properties from a list of objects?

IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();

how to set default main class in java?

If the two jars that you want to create are the mostly the same, and the only difference is the main class that should be started from each, you can put all of the classes in a third jar. Then create two jars with just a manifest in each. In the MANIFEST.MF file, name the entry class using the Main-Class attribute.

Additionally, specify the Class-Path attribute. The value of this should be the name of the jar file that contains all of the shared code. Then deploy all three jar files in the same directory. Of course, if you have third-party libraries, those can be listed in the Class-Path attribute too.

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

This is related to compact option of Babel compiler, which commands to "not include superfluous whitespace characters and line terminators. When set to 'auto' compact is set to true on input sizes of >100KB." By default its value is "auto", so that is probably the reason you are getting the warning message. See Babel documentation.

You can change this option from Webpack using a query parameter. For example:

loaders: [
    { test: /\.js$/, loader: 'babel', query: {compact: false} }
]