Programs & Examples On #Server farm

scp copy directory to another server with private key auth

Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and

scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www

it should work !

Save PHP array to MySQL?

Uhh, I don't know why everyone suggests serializing the array.

I say, the best way is to actually fit it into your database schema. I have no idea (and you gave no clues) about the actual semantic meaning of the data in your array, but there are generally two ways of storing sequences like that

create table mydata (
  id int not null auto_increment primary key,
  field1 int not null,
  field2 int not null,
  ...
  fieldN int not null
)

This way you are storing your array in a single row.

create table mydata (
    id int not null auto_increment primary key,
    ...
)

create table myotherdata (
    id int not null auto_increment primary key,
    mydata_id int not null,
    sequence int not null,
    data int not null
)

The disadvantage of the first method is, obviously, that if you have many items in your array, working with that table will not be the most elegant thing. It is also impractical (possible, but quite inelegant as well - just make the columns nullable) to work with sequences of variable length.

For the second method, you can have sequences of any length, but of only one type. You can, of course, make that one type varchar or something and serialize the items of your array. Not the best thing to do, but certainly better, than serializing the whole array, right?

Either way, any of this methods gets a clear advantage of being able to access an arbitrary element of the sequence and you don't have to worry about serializing arrays and ugly things like that.

As for getting it back. Well, get the appropriate row/sequence of rows with a query and, well, use a loop.. right?

How do I declare a two dimensional array?

As far as I'm aware there is no built in php function to do this, you need to do it via a loop or via a custom method that recursively calls to something like array_fill inidcated in the answer by @Amber;

I'm assuming you mean created an empty but intialized array of arrays. For example, you want a final results like the below of a array of 3 arrays:

   $final_array = array(array(), array(), array());

This is simple to just hand code, but for an arbitrary sized array like a an array of 3 arrays of 3 arrays it starts getting complex to initialize prior to use:

     $final_array = array(array(array(), array(), array()), array(array(), array(), array()), array(array(), array(), array()));

...etc...

I get the frustration. It would be nice to have an easy way to declare an initialized array of arrays any depth to use without checking or throwing errors.

How do I make a JAR from a .java file?

Although it is not recommended method but still it works
[7-Zip Software is needed]
Procedure to get jar from java files:

  • place all java files in one folder

  • right click on the folder enter image description here

  • now click on Add to archive you will get something like shown below enter image description here

  • now just change zip to jar and click on ok

JavaScriptSerializer.Deserialize - how to change field names

I have used the using Newtonsoft.Json as below. Create an object:

 public class WorklistSortColumn
  {
    [JsonProperty(PropertyName = "field")]
    public string Field { get; set; }

    [JsonProperty(PropertyName = "dir")]
    public string Direction { get; set; }

    [JsonIgnore]
    public string SortOrder { get; set; }
  }

Now Call the below method to serialize to Json object as shown below.

string sortColumn = JsonConvert.SerializeObject(worklistSortColumn);

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

how to parse json using groovy

Have you tried using JsonSlurper?

Example usage:

def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"

Openstreetmap: embedding map in webpage (like Google Maps)

Simple OSM Slippy Map Demo/Example

Click on "Run code snippet" to see an embedded OpenStreetMap slippy map with a marker on it. This was created with Leaflet.

Code

_x000D_
_x000D_
// Where you want to render the map.
var element = document.getElementById('osm-map');

// Height has to be set. You can do this in CSS too.
element.style = 'height:300px;';

// Create Leaflet map on map element.
var map = L.map(element);

// Add OSM tile leayer to the Leaflet map.
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// Target's GPS coordinates.
var target = L.latLng('47.50737', '19.04611');

// Set map's center to target with zoom 14.
map.setView(target, 14);

// Place a marker on the same location.
L.marker(target).addTo(map);
_x000D_
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>
<div id="osm-map"></div>
_x000D_
_x000D_
_x000D_

Specs

  • Uses OpenStreetMaps.
  • Centers the map to the target GPS.
  • Places a marker on the target GPS.
  • Only uses Leaflet as a dependency.

Note:

I used the CDN version of Leaflet here, but you can download the files so you can serve and include them from your own host.

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

Just type git init into your command line and press enter. Then run your command again, you probably were running git remote add origin [your-repository].

That should work, if it doesn't, just let me know.

Deleting an object in C++

saveLeaves(vec,msh);
I'm assuming takes the msh pointer and puts it inside of vec. Since msh is just a pointer to the memory, if you delete it, it will also get deleted inside of the vector.

how to install python distutils

You can install the python-distutils package. sudo apt-get install python-distutils should suffice.

This certificate has an invalid issuer Apple Push Services

As described in the Apple Worldwide Developer Relations Intermediate Certificate Expiration:


The previous Apple Worldwide Developer Relations Certification Intermediate Certificate expired on February 14, 2016 and the renewed certificate must now be used when signing Apple Wallet Passes, push packages for Safari Push Notifications, Safari Extensions, and submissions to the App Store, Mac App Store, and App Store for Apple TV.

All developers should download and install the renewed certificate on their development systems and servers. All apps will remain available on the App Store for iOS, Mac, and Apple TV.


The new valid certificate will look like the following:

Apple Worldwide Developer Relations Certification Authority

It will display (this certificate is valid) with a green mark.

So, go to your Key Chain Access. Just delete the old certificate and replace it with the new one (renewed certificate) as Apple described in the document. Mainly the problem is only with the Apple push notification service and extensions as described in the Apple document.

You can also check the listing of certificates in https://www.apple.com/certificateauthority/

Certificate Revocation List:

Certificate Revocation List

Now this updated certificate will expire on 2023-02-08.


If you could not see the old certificate then go to the System Keychains and from edit menu and select the option Show Expired Certificates.

Show Expired Certificates

Now you can see the following certificate that you have to delete:

Delete This Certificate

request exceeds the configured maxQueryStringLength when using [Authorize]

When an unauthorized request comes in, the entire request is URL encoded, and added as a query string to the request to the authorization form, so I can see where this may result in a problem given your situation.

According to MSDN, the correct element to modify to reset maxQueryStringLength in web.config is the <httpRuntime> element inside the <system.web> element, see httpRuntime Element (ASP.NET Settings Schema). Try modifying that element.

Release generating .pdb files, why?

Debug symbols (.pdb) and XML doc (.xml) files make up a large percentage of the total size and should not be part of the regular deployment package. But it should be possible to access them in case they are needed.

One possible approach: at the end of the TFS build process, move them to a separate artifact.

Scrolling a flexbox with overflowing content

.list-wrap {
  width: 355px;
  height: 100%;
  position: relative;

  .list {
    position: absolute;
    top: 0;
    bottom: 0;
    overflow-y: auto;
    width: 100%;
  }
}

How to dismiss keyboard for UITextView with return key?

I used this code to change responder.

 - (BOOL)textView:(UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
    {
        if ([text isEqualToString:@"\n"]) {
            //[textView resignFirstResponder];
            //return YES;
            NSInteger nextTag = textView.tag + 1;
            // Try to find next responder
            UIResponder* nextResponder = [self.view viewWithTag:nextTag];
            if (nextResponder) {
                // Found next responder, so set it.
                [nextResponder becomeFirstResponder];
            } else {
                // Not found, so remove keyboard.
                [textView resignFirstResponder];
            }
            return NO; 


            return NO;
        }
        return YES;

    }

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

I know that PHPMailer library can handle that kind of SMTP transactions.

Also, a fake sendmail with sendmail-SSL library should do the job.

javascript - replace dash (hyphen) with a space

var str = "This-is-a-news-item-";
while (str.contains("-")) {
  str = str.replace("-", ' ');
}
alert(str);

I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.

http://jsfiddle.net/LGCYF/

How to set shape's opacity?

use this code below as progress.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient
                    android:startColor="#ff9d9e9d"
                    android:centerColor="#ff5a5d5a"
                    android:centerY="0.75"
                    android:endColor="#ff747674"
                    android:angle="270"
            />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

</layer-list>

where:

  • "progress" is current progress before the thumb and "secondaryProgress" is the progress after thumb.
  • color="#00000000" is a perfect transparency
  • NOTE: the file above is from default android res and is for 2.3.7, it is available on android sources at: frameworks/base/core/res/res/drawable/progress_horizontal.xml. For newer versions you must find the default drawable file for the seekbar corresponding to your android version.

after that use it in the layout containing the xml:

<SeekBar
    android:id="@+id/myseekbar"
    ...
    android:progressDrawable="@drawable/progress"
    />

you can also customize the thumb by using a custom icon seek_thumb.png:

android:thumb="@drawable/seek_thumb"

CSS: transition opacity on mouse-out?

$(window).scroll(function() {    
    $('.logo_container, .slogan').css({
        "opacity" : ".1",
        "transition" : "opacity .8s ease-in-out"
    });
});

Check the fiddle: http://jsfiddle.net/2k3hfwo0/2/

How to directly execute SQL query in C#?

IMPORTANT NOTE: You should not concatenate SQL queries unless you trust the user completely. Query concatenation involves risk of SQL Injection being used to take over the world, ...khem, your database.

If you don't want to go into details how to execute query using SqlCommand then you could call the same command line like this:

string userInput = "Brian";
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format(@"sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS  
     -s ; -W -w 100 -Q "" SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName,
     tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '{0}' """, userInput);

process.StartInfo = startInfo;
process.Start();

Just ensure that you escape each double quote " with ""

Delete worksheet in Excel using VBA

You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.

With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.

Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.

Dim book
Dim sht as Worksheet

set book= Workbooks("SomeBook.xlsx")

On Error Resume Next

Application.DisplayAlerts=False 

Set sht = book.Worksheets("ID Sheet")
sht.Delete

Set sht = book.Worksheets("Summary")
sht.Delete

Application.DisplayAlerts=True 

On Error GoTo 0

Count number of lines in a git repository

I did this:

git ls-files | xargs file | grep "ASCII" | cut -d : -f 1 | xargs wc -l

this works if you count all text files in the repository as the files of interest. If some are considered documentation, etc, an exclusion filter can be added.

Attempt to write a readonly database - Django w/ SELinux error

I had this issue and I solved it by creating a directory in mysite folder to hold my db.sqlite3 file. so I did /home/user/src/mysite/database/db.sqlite3. In my django setting file I change my

 DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': "/home/user/src/mysite/database/db.sqlite3" ,
}}

I did this to make Django aware that I am storing my database in a sub directory of the base directory, which mysite in my case. Now you need to grant the permission to apache to be able read write the database.

chown user:www-data database/db.sqlite3
chown user:www-data database 
chmod 755 database
 chmod 755 database/db.sqlite3

This solved my problem. Here is a list of the different permissions. You can use choose the one that fits you but avoid 777 and 666

-rw------- (600) -- Only the user has read and write permissions.

-rw-r--r-- (644) -- Only user has read and write permissions; the group and others can read only.

-rwx------ (700) -- Only the user has read, write and execute permissions.

-rwxr-xr-x (755) -- The user has read, write and execute permissions; the group and others can only read and execute.

-rwx--x--x (711) -- The user has read, write and execute permissions; the group and others can only execute.

-rw-rw-rw- (666) -- Everyone can read and write to the file. Bad idea.

-rwxrwxrwx (777) -- Everyone can read, write and execute. Another bad idea.

Here are a couple common settings for directories:

drwx------ (700) -- Only the user can read, write in this directory.

drwxr-xr-x (755) -- Everyone can read the directory, but its contents can only be changed by the user.

here is a link to an article to [learn more][1]

[1]: http://ftp.kh.edu.tw/Linux/Redhat/en_6.2/doc/gsg/s1-navigating-chmodnum.htm#:~:text=%2Drwxr%2Dxr%2Dx%20(,and%20others%20can%20only%20execute.

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)

Difference between map and collect in Ruby?

There's no difference, in fact map is implemented in C as rb_ary_collect and enum_collect (eg. there is a difference between map on an array and on any other enum, but no difference between map and collect).


Why do both map and collect exist in Ruby? The map function has many naming conventions in different languages. Wikipedia provides an overview:

The map function originated in functional programming languages but is today supported (or may be defined) in many procedural, object oriented, and multi-paradigm languages as well: In C++'s Standard Template Library, it is called transform, in C# (3.0)'s LINQ library, it is provided as an extension method called Select. Map is also a frequently used operation in high level languages such as Perl, Python and Ruby; the operation is called map in all three of these languages. A collect alias for map is also provided in Ruby (from Smalltalk) [emphasis mine]. Common Lisp provides a family of map-like functions; the one corresponding to the behavior described here is called mapcar (-car indicating access using the CAR operation).

Ruby provides an alias for programmers from the Smalltalk world to feel more at home.


Why is there a different implementation for arrays and enums? An enum is a generalized iteration structure, which means that there is no way in which Ruby can predict what the next element can be (you can define infinite enums, see Prime for an example). Therefore it must call a function to get each successive element (typically this will be the each method).

Arrays are the most common collection so it is reasonable to optimize their performance. Since Ruby knows a lot about how arrays work it doesn't have to call each but can only use simple pointer manipulation which is significantly faster.

Similar optimizations exist for a number of Array methods like zip or count.

How to make g++ search for header files in a specific directory?

A/code.cpp

#include <B/file.hpp>

A/a/code2.cpp

#include <B/file.hpp>

Compile using:

g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp

Edit:

You can use environment variables to change the path g++ looks for header files. From man page:

Some additional environments variables affect the behavior of the preprocessor.

   CPATH
   C_INCLUDE_PATH
   CPLUS_INCLUDE_PATH
   OBJC_INCLUDE_PATH

Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon.

CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.

The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.

In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include.

There are many ways you can change an environment variable. On bash prompt you can do this:

$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp

You can of course add this in your Makefile etc.

How do you remove a Cookie in a Java Servlet

The proper way to remove a cookie is to set the max age to 0 and add the cookie back to the HttpServletResponse object.

Most people don't realize or forget to add the cookie back onto the response object. By doing that it will expire and remove the cookie immediately.

...retrieve cookie from HttpServletRequest
cookie.setMaxAge(0);
response.addCookie(cookie);

Run Android studio emulator on AMD processor

Recent updates enabled computers with AMD processors to run Android Emulator and you don't need to install ARM images anymore. Taken from the Android Developers blog:

If you have an AMD processor in your computer you need the following setup requirements to be in place:

  • AMD Processor - Recommended: AMD® Ryzen™ processors
  • Android Studio 3.2 Beta or higher
  • Android Emulator v27.3.8+
  • x86 Android Virtual Device (AVD)
  • Windows 10 with April 2018 Update
  • Enable via Windows Features: "Windows Hypervisor Platform"

The important point is enabling Windows Hypervisor Platform and that's it! I strongly recommend reading the whole blog post:
https://android-developers.googleblog.com/2018/07/android-emulator-amd-processor-hyper-v.html

How to use jQuery to get the current value of a file input field

Jquery works differently in IE and other browsers. You can access the last file name by using

alert($('input').attr('value'));

In IE the above alert will give the complete path but in other browsers it will give only the file name.

Input type number "only numeric value" validation

I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.

Sample use: <input type="number" formControlName="num" placeholder="0" ntvFormValidity>

Directive definition:

import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';

@Directive({
  selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {

  constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }

  /* 
  - Angular doesn't fire "change" events for invalid <input type="number">
  - We have to check the DOM object for browser native invalid state
  - Add custom validator that checks native invalidity
  */
  ngAfterViewInit() {
    var control: FormControl = this.cn.control;

    // Bridge native invalid to ng-invalid via Validators
    const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
    const v_fn = control.validator;

    control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
    setTimeout(()=>control.updateValueAndValidity(), 0);
  }
}

The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's @ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.

On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".

I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.

Something like this:

<my-input-number formControlName="num" placeholder="0">

PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers on the declaration, please let me know so I can update my Directive (and this answer).

Inserting into Oracle and retrieving the generated sequence ID

Expanding a bit on the answers from @Guru and @Ronnis, you can hide the sequence and make it look more like an auto-increment using a trigger, and have a procedure that does the insert for you and returns the generated ID as an out parameter.

create table batch(batchid number,
    batchname varchar2(30),
    batchtype char(1),
    source char(1),
    intarea number)
/

create sequence batch_seq start with 1
/

create trigger batch_bi
before insert on batch
for each row
begin
    select batch_seq.nextval into :new.batchid from dual;
end;
/

create procedure insert_batch(v_batchname batch.batchname%TYPE,
    v_batchtype batch.batchtype%TYPE,
    v_source batch.source%TYPE,
    v_intarea batch.intarea%TYPE,
    v_batchid out batch.batchid%TYPE)
as
begin
    insert into batch(batchname, batchtype, source, intarea)
    values(v_batchname, v_batchtype, v_source, v_intarea)
    returning batchid into v_batchid;
end;
/

You can then call the procedure instead of doing a plain insert, e.g. from an anoymous block:

declare
    l_batchid batch.batchid%TYPE;
begin
    insert_batch(v_batchname => 'Batch 1',
        v_batchtype => 'A',
        v_source => 'Z',
        v_intarea => 1,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);

    insert_batch(v_batchname => 'Batch 99',
        v_batchtype => 'B',
        v_source => 'Y',
        v_intarea => 9,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);
end;
/

Generated id: 1
Generated id: 2

You can make the call without an explicit anonymous block, e.g. from SQL*Plus:

variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);

... and use the bind variable :l_batchid to refer to the generated value afterwards:

print l_batchid;
insert into some_table values(:l_batch_id, ...);

Get custom product attributes in Woocommerce

Update for 2018. You can use:

global $product;
echo wc_display_product_attributes( $product );

To customise the output, copy plugins/woocommerce/templates/single-product/product-attributes.php to themes/theme-child/woocommerce/single-product/product-attributes.php and modify that.

Center align "span" text inside a div

You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.

You could give the span a set width, then add the margin:0 auto again. This would center-align it.

.left 
{
   background-color: #999999;
   height: 50px;
   width: 24.5%;
}
span.panelTitleTxt 
{
   display:block;
   width:100px;
   height: 100%;
   margin: 0 auto;
}

How to make <a href=""> link look like a button?

A simple as that :

<a href="#" class="btn btn-success" role="button">link</a>

Just add "class="btn btn-success" & role=button

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

I want to indent a specific section of code in Visual Studio Code:

  • Select the lines you want to indent, and
  • use Ctrl + ] to indent them.

If you want to format a section (instead of indent it):

  • Select the lines you want to format,
  • use Ctrl + K, Ctrl + F to format them.

How to do logging in React Native?

There is normally two scenarios where we need debugging.

  1. When we facing issues related to data and we want to check our data and debugging related to data in that case console.log('data::',data)

    and debug js remotely is the best option.

  2. Other case is the UI and styles related issues where we need to check styling of the component in that case react-dev-tools is the best option.

    both of the methods mention here.

.m2 , settings.xml in Ubuntu

As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned

$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml

How to make child element higher z-index than parent?

To achieve what you want without removing any styles you have to make the z-index of the '.parent' class bigger then the '.wholePage' class.

.parent {
    position: relative;
    z-index: 4; /*matters since it's sibling to wholePage*/
}

.child {
    position: relative;
    z-index:1; /*doesn't matter */
    background-color: white;
    padding: 5px;
}

jsFiddle: http://jsfiddle.net/ZjXMR/2/

Difference between Static and final?

static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.

public class MyClass {
    public static int myVariable = 0; 
}

//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances

MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();

MyClass.myVariable = 5;  //This change is reflected in both instances

final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.

note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.

Extra Reading So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.

public class MyClass {

    public static List<String> cars = new ArrayList<String>();

    static {
        cars.add("Ferrari");
        cars.add("Scoda");
    }

}

public class TestClass {

    public static void main(String args[]) {
        System.out.println(MyClass.cars.get(0));  //This will print Ferrari
    }
}

You must not get this confused with instance initializer blocks which are called before the constructor per instance.

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

Enable this option in VS: Just My Code option

Tools -> Options -> Debugging -> General -> Enable Just My Code (Managed only)

log4net vs. Nlog

Having had an experience with both frameworks recently, I thought I can share my views on each frameworks.

I was asked to evaluate the logging frameworks for an existing web application, I narrowed down my choices to NLog (v2.0) and log4net (v1.2.11) after going through various online forums. Here are my findings:

  1. Setting/starting up with NLog is dead easy. You go through the Getting started tutorial on their website and you are done. You get a fair idea, how thing might be with nlog. Config file is so intuitive that anyone can understand the config. For example: if you want to set the internal logging on, you set the flag in Nlog config file's header node, which is where you would expect it to be. In log4net, you set different flags in web.config's appSettings section.

  2. In log4net, internal logging doesnt output timestamp which is annoying. In Nlog, you get a nice log with timestamps. I found it very useful in my evaluations.

  3. Filters in log4net - You better check my this question - log4net filter - how to write AND filter to ignore log messages and if you find an answer/solution for this, please let me know. I understand, there is a workaround for this question, as you can write your own custom filter. But something which is not easily available in log4net.

  4. Performance - I logged around 3000 log messages to database using a stored procedure. I used simple for loop (int i=0; i<3000; i++... to log the same message 3000 times. For the writes: log4net AdoAppender took almost double the time than NLog.

  5. Log4net doesnt support asynchronous appender.

It was sufficient comparison for me to choose NLog as the logging framework. :)

laravel Eloquent ORM delete() method

check before delete the user otherwise throws error exeption

$user=User::find($request->id);
  
   if($user)
   {
   // return $user;           <------------------------user exist
       if($user->delete()){
         return 'user deleted';
         }
    else{
       return "something wrong";
        }   

   }
  else{
     return "user not exist";// <--------------------user not exist
    }

100% width background image with an 'auto' height

It's 2017, and now you can use object-fit which has decent support. It works in the same way as a div's background-size but on the element itself, and on any element including images.

.your-img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

How do I find the length of an array?

ANSWER:

int number_of_elements = sizeof(array)/sizeof(array[0])

EXPLANATION:

Since the compiler sets a specific size chunk of memory aside for each type of data, and an array is simply a group of those, you simply divide the size of the array by the size of the data type. If I have an array of 30 strings, my system sets aside 24 bytes for each element(string) of the array. At 30 elements, that's a total of 720 bytes. 720/24 == 30 elements. The small, tight algorithm for that is:

int number_of_elements = sizeof(array)/sizeof(array[0]) which equates to

number_of_elements = 720/24

Note that you don't need to know what data type the array is, even if it's a custom data type.

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

In BIDS or SSDT-BI, do the following:

  1. Click on Report > Report Properties > Layout tab (Page Setup tab in SSDT-BI)
  2. Make a note of the values for Page width, Left margin, Right margin
  3. Close and go back to the design surface
  4. In the Properties window, select Body
  5. Click the + symbol to expand the Size node
  6. Make a note of the value for Width

To render in PDF correctly Body Width + Left margin + Right margin must be less than or equal to Page width. When you see blank pages being rendered it is almost always because the body width plus margins is greater than the page width.

Remember: (Body Width + Left margin + Right margin) <= (Page width)

Online Internet Explorer Simulators

Use wine - it has IE6 with Gecko support built into it. More information here.

Http Servlet request lose params from POST body after read it once

you can use servlet filter chain, but instead use the original one, you can create your own request yourownrequests extends HttpServletRequestWrapper.

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

Copy map values to vector in STL

Here is what I would do.
Also I would use a template function to make the construction of select2nd easier.

#include <map>
#include <vector>
#include <algorithm>
#include <memory>
#include <string>

/*
 * A class to extract the second part of a pair
 */   
template<typename T>
struct select2nd
{
    typename T::second_type operator()(T const& value) const
    {return value.second;}
};

/*
 * A utility template function to make the use of select2nd easy.
 * Pass a map and it automatically creates a select2nd that utilizes the
 * value type. This works nicely as the template functions can deduce the
 * template parameters based on the function parameters. 
 */
template<typename T>
select2nd<typename T::value_type> make_select2nd(T const& m)
{
    return select2nd<typename T::value_type>();
}

int main()
{
    std::map<int,std::string>   m;
    std::vector<std::string>    v;

    /*
     * Please note: You must use std::back_inserter()
     *              As transform assumes the second range is as large as the first.
     *              Alternatively you could pre-populate the vector.
     *
     * Use make_select2nd() to make the function look nice.
     * Alternatively you could use:
     *    select2nd<std::map<int,std::string>::value_type>()
     */   
    std::transform(m.begin(),m.end(),
                   std::back_inserter(v),
                   make_select2nd(m)
                  );
}

How do you set, clear, and toggle a single bit?

For the beginner I would like to explain a bit more with an example:

Example:

value is 0x55;
bitnum : 3rd.

The & operator is used check the bit:

0101 0101
&
0000 1000
___________
0000 0000 (mean 0: False). It will work fine if the third bit is 1 (then the answer will be True)

Toggle or Flip:

0101 0101
^
0000 1000
___________
0101 1101 (Flip the third bit without affecting other bits)

| operator: set the bit

0101 0101
|
0000 1000
___________
0101 1101 (set the third bit without affecting other bits)

Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file to debug it.

When it starts up, you can use bt (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.

Typing help within GDB will give you a prompt that will let you see additional commands.

Outline effect to text

Multiple text-shadows..
Something like this:

var steps = 10,
    i,
    R = 0.6,
    x,
    y,
    theStyle = '1vw 1vw 3vw #005dab';
for (i = -steps; i <= steps; i += 1) {
    x = (i / steps) / 2;
    y = Math.sqrt(Math.pow(R, 2) - Math.pow(x, 2));
    theStyle = theStyle + ',' + x.toString() + 'vw ' + y.toString() + 'vw 0 #005dab';
    theStyle = theStyle + ',' + x.toString() + 'vw -' + y.toString() + 'vw 0 #005dab';
    theStyle = theStyle + ',' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
    theStyle = theStyle + ',-' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
}
document.getElementsByTagName("H1")[0].setAttribute("style", "text-shadow:" + theStyle);

Demo: http://jsfiddle.net/punosound/gv6zs58m/

Debugging "Element is not clickable at point" error

You can also use JavaScript click and scrolling would be not required then.

IJavaScriptExecutor ex = (IJavaScriptExecutor)Driver;
ex.ExecuteScript("arguments[0].click();", elementToClick);

how to remove multiple columns in r dataframe?

Basic subsetting:

album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7

Partial Dependency (Databases)

Partial Dependency is one kind of functional dependency that occur when primary key must be candidate key and non prime attribute are depends on the subset/part of candidates key (more than one primary key).

Try to understand partial dependency relate through example :

Seller(Id, Product, Price)

Candidate Key : Id, Product
Non prime attribute : Price

Price attribute only depends on only Product attribute which is a subset of candidate key, Not the whole candidate key(Id, Product) key . It is called partial dependency.

So we can say that Product->Price is partial dependency.

Is there a real solution to debug cordova apps

FOR ANDROID:

You only need to enable “USB remote debugger” within your android device and plug with a USB cable. Then open your application in the device. Chrome will detect the remote browser and you can see the console in the same way than you see it when you use Chrome locally.

Use this link: chrome://inspect/#devices in Chrome browser (you'll have to paste it into the nav bar).

If your app crashes in the device you only need to see the console’s log within your browser and see what happens. You also can add functionality, change variables, and override functions in the same way than we do it with our local browser.

Read this article for more information on the steps to take.

This will work ONLY with devices running Android 4.4+.

FOR iOS:

Use Safari for iOS, follow these steps:

1.In your iOS device go to Settings > Safari > Advanced > Web Inspector to enable Web Inspector

2.Open Safari on your iOS device.

3.Connect it to your computer via USB.

4.Open Safari on your computer.

5.In Safari’s menu, go to Develop and, look for your device’s name.

6.Select the tab you want to debug.

enter image description here

How can I install the Beautiful Soup module on the Mac?

The "normal" way is to:

Another solution is to use easy_install. Go to http://peak.telecommunity.com/DevCenter/EasyInstall), install the package using the instructions on that page, and then type, in a Terminal window:

easy_install BeautifulSoup4
# for older v3:
# easy_install BeautifulSoup

easy_install will take care of downloading, unpacking, building, and installing the package. The advantage to using easy_install is that it knows how to search for many different Python packages, because it queries the PyPI registry. Thus, once you have easy_install on your machine, you install many, many different third-party packages simply by one command at a shell.

How to finish current activity in Android

I tried using this example but it failed miserably. Every time I use to invoke finish()/ finishactivity() inside a handler, I end up with this menacing java.lang.IllegalAccess Exception. i'm not sure how did it work for the one who posed the question.

Instead the solution I found was that create a method in your activity such as

void kill_activity()
{ 
    finish();
}

Invoke this method from inside the run method of the handler. This worked like a charm for me. Hope this helps anyone struggling with "how to close an activity from a different thread?".

How to capture UIView to UIImage without loss of quality on retina display

UIGraphicsImageRenderer is a relatively new API, introduced in iOS 10. You construct a UIGraphicsImageRenderer by specifying a point size. The image method takes a closure argument and returns a bitmap that results from executing the passed closure. In this case, the result is the original image scaled down to draw within the specified bounds.

https://nshipster.com/image-resizing/

So be sure the size you are passing into UIGraphicsImageRenderer is points, not pixels.

If your images are larger than you are expecting, you need to divide your size by the scale factor.

Remove all items from RecyclerView

setAdapter(null);

Useful if RecycleView have different views type

How do I change select2 box height

None of the above solutions worked for me. This is my solution:

/* Height fix for select2 */
.select2-container .select2-selection--single, .select2-container--default .select2-selection--single .select2-selection__rendered, .select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 35px;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 35px;
}

Replace text inside td using jQuery having td containing other elements

Wrap your to be deleted contents within a ptag, then you can do something like this:

$(function(){
  $("td").click(function(){ console.log($("td").find("p"));
    $("td").find("p").remove();    });
});

FIDDLE DEMO: http://jsfiddle.net/y3p2F/

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

check your image cmd using the command docker inspect image_name . The output might be like this:

"Cmd": [
    "/bin/bash",
    "-c",
    "#(nop) ",
    "CMD [\"/bin/bash\"]"
],

So use the command docker exec -it container_id /bin/bash. If your cmd output is different like this:

"Cmd": [
    "/bin/sh",
    "-c",
    "#(nop) ",
    "CMD [\"/bin/sh\"]"
],

Use /bin/sh instead of /bin/bash in the command above.

Giving my function access to outside variable

The one and probably not so good way of achieving your goal would using global variables.

You could achieve that by adding global $myArr; to the beginning of your function. However note that using global variables is in most cases a bad idea and probably avoidable.

The much better way would be passing your array as an argument to your function:

function someFuntion($arr){
    $myVal = //some processing here to determine value of $myVal
    $arr[] = $myVal;
    return $arr;
}

$myArr = someFunction($myArr);

Index all *except* one item in python

For a list, you could use a list comp. For example, to make b a copy of a without the 3rd element:

a = range(10)[::-1]                       # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
b = [x for i,x in enumerate(a) if i!=3]   # [9, 8, 7, 5, 4, 3, 2, 1, 0]

This is very general, and can be used with all iterables, including numpy arrays. If you replace [] with (), b will be an iterator instead of a list.

Or you could do this in-place with pop:

a = range(10)[::-1]     # a = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
a.pop(3)                # a = [9, 8, 7, 5, 4, 3, 2, 1, 0]

In numpy you could do this with a boolean indexing:

a = np.arange(9, -1, -1)     # a = array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
b = a[np.arange(len(a))!=3]  # b = array([9, 8, 7, 5, 4, 3, 2, 1, 0])

which will, in general, be much faster than the list comprehension listed above.

Converting a String to DateTime

I tried various ways. What worked for me was this:

Convert.ToDateTime(data, CultureInfo.InvariantCulture);

data for me was times like this 9/24/2017 9:31:34 AM

What is the Ruby <=> (spaceship) operator?

The spaceship method is useful when you define it in your own class and include the Comparable module. Your class then gets the >, < , >=, <=, ==, and between? methods for free.

class Card
  include Comparable
  attr_reader :value

  def initialize(value)
    @value = value
  end

  def <=> (other) #1 if self>other; 0 if self==other; -1 if self<other
    self.value <=> other.value
  end

end

a = Card.new(7)
b = Card.new(10)
c = Card.new(8)

puts a > b # false
puts c.between?(a,b) # true

# Array#sort uses <=> :
p [a,b,c].sort # [#<Card:0x0000000242d298 @value=7>, #<Card:0x0000000242d248 @value=8>, #<Card:0x0000000242d270 @value=10>]

What does int argc, char *argv[] mean?

int main();

This is a simple declaration. It cannot take any command line arguments.

int main(int argc, char* argv[]);

This declaration is used when your program must take command-line arguments. When run like such:

myprogram arg1 arg2 arg3

argc, or Argument Count, will be set to 4 (four arguments), and argv, or Argument Vectors, will be populated with string pointers to "myprogram", "arg1", "arg2", and "arg3". The program invocation (myprogram) is included in the arguments!

Alternatively, you could use:

int main(int argc, char** argv);

This is also valid.

There is another parameter you can add:

int main (int argc, char *argv[], char *envp[])

The envp parameter also contains environment variables. Each entry follows this format:

VARIABLENAME=VariableValue

like this:

SHELL=/bin/bash    

The environment variables list is null-terminated.

IMPORTANT: DO NOT use any argv or envp values directly in calls to system()! This is a huge security hole as malicious users could set environment variables to command-line commands and (potentially) cause massive damage. In general, just don't use system(). There is almost always a better solution implemented through C libraries.

Difference between margin and padding?

Try putting a background color on a block div with width and height. You'll see that padding increases the size of the element, whereas margin just moves it within the flow of the document.

Margin is specifically for shifting the element around.

How do I read the first line of a file using cat?

Use the below command to get the first row from a CSV file or any file formats.

head -1 FileName.csv

Stretch horizontal ul to fit width of div

I Hope that this helps you out... Because I tried all the answers but nothing worked perfectly. So, I had to come up with a solution on my own.

#horizontal-style {
  padding-inline-start: 0 !important; // Just in case if you find that there is an extra padding at the start of the line 
  justify-content: space-around;
  display: flex;
}

#horizontal-style a {
    text-align: center;
    color: white;
    text-decoration: none;
}

What does the clearfix class do in css?

When an element, such as a div is floated, its parent container no longer considers its height, i.e.

<div id="main">
  <div id="child" style="float:left;height:40px;"> Hi</div>
</div>

The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.

So the clearfix class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.

Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.

Can read more here

http://www.webtoolkit.info/css-clearfix.html

How do I declare an array with a custom class?

To default-initialize an array of Ts, T must be default constructible. Normally the compiler gives you a default constructor for free. However, since you declared a constructor yourself, the compiler does not generate a default constructor.

Your options:

  • add a default constructor to name, if that makes sense (I don't think so, but I don't know the problem domain);
  • initialize all the elements of the array upon declaration (you can do this because name is an aggregate);

      name someName[4] = { { "Arthur", "Dent" },
                           { "Ford", "Prefect" },
                           { "Tricia", "McMillan" },
                           { "Zaphod", "Beeblebrox" }
                         };
    
  • use a std::vector instead, and only add element when you have them constructed.

Business logic in MVC

Fist of all:
I believe that you are mixing up the MVC pattern and n-tier-based design principles.

Using an MVC approach does not mean that you shouldn't layer your application.
It might help if you see MVC more like an extension of the presentation layer.

If you put non-presentation code inside the MVC pattern you might very soon end up in a complicated design.
Therefore I would suggest that you put your business logic into a separate business layer.

Just have a look at this: Wikipedia article about multitier architecture

It says:

Today, MVC and similar model-view-presenter (MVP) are Separation of Concerns design patterns that apply exclusively to the presentation layer of a larger system.

Anyway ... when talking about an enterprise web application the calls from the UI to the business logic layer should be placed inside the (presentation) controller.

That is because the controller actually handles the calls to a specific resource, queries the data by making calls to the business logic and links the data (model) to the appropriate view.

Mud told you that the business rules go into the model.
That is also true, but he mixed up the (presentation) model (the 'M' in MVC) and the data layer model of a tier-based application design.
So it is valid to place your database related business rules in the model (data layer) of your application.
But you should not place them in the model of your MVC-structured presentation layer as this only applies to a specific UI.

This technique is independent of whether you use a domain driven design or a transaction script based approach.

Let me visualize that for you:


Presentation layer: Model - View - Controller


Business layer: Domain logic - Application logic


Data layer: Data repositories - Data access layer


The model that you see above means that you have an application that uses MVC, DDD and a database-independed data layer.
This is a common approach to design a larger enterprise web application.

But you can also shrink it down to use a simple non-DDD business layer (a business layer without domain logic) and a simple data layer that writes directly to a specific database.
You could even drop the whole data-layer and access the database directly from the business layer, though I do not recommend it.

Thats' the trick...I hope this helps...

[Note:] You should also be aware of the fact that nowadays there is more than just one "model" in an application. Commonly, each layer of an application has it's own model. The model of the presentation layer is view specific but often independent of the used controls. The business layer can also have a model, called the "domain-model". This is typically the case when you decide to take a domain-driven approach. This "domain-model" contains of data as well as business logic (the main logic of your program) and is usually independent of the presentation layer. The presentation layer usually calls the business layer on a certain "event" (button pressed etc.) to read data from or write data to the data layer. The data layer might also have it's own model, which is typically database related. It often contains a set of entity classes as well as data-access-objects (DAOs).

The question is: how does this fit into the MVC concept?

Answer -> It doesn't!
Well - it kinda does, but not completely.
This is because MVC is an approach that was developed in the late 1970's for the Smalltalk-80 programming language. At that time GUIs and personal computers were quite uncommon and the world wide web was not even invented! Most of today's programming languages and IDEs were developed in the 1990s. At that time computers and user interfaces were completely different from those in the 1970s.
You should keep that in mind when you talk about MVC.
Martin Fowler has written a very good article about MVC, MVP and today's GUIs.

SQL query question: SELECT ... NOT IN

SELECT MIN(A.maxsal) secondhigh
FROM (
      SELECT TOP 2 MAX(EmployeeBasic) maxsal
      FROM M_Salary
      GROUP BY EmployeeBasic
      ORDER BY EmployeeBasic DESC
     ) A

android.view.InflateException: Binary XML file: Error inflating class fragment

FWIW: I was getting "Android.Views.InflateException Message=Binary XML file line #1: Binary XML file line #1: Error inflating class android.view.TextureView"

I am new to android form design. In trying to put a border on some buttons I found an SO post that inspired me to create buttonborder.xml that looks like:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/transparent" />
<stroke android:width="1dp" android:color="@android:color/white"/>

Then for each button I added

android:background="@drawable/buttonborder"

However, in my enthusiasm I also added it to a TextureView - which was my problem. When I removed the line from the TextureView, things worked.

Python error message io.UnsupportedOperation: not readable

Use a+ to open a file for reading, writing as well as create it if it doesn't exist.

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. -Python file modes

with open('"File.txt', 'a+') as file:
    print(file.readlines())
    file.write("test")

Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

How do I mock a class without an interface?

If worse comes to worse, you can create an interface and adapter pair. You would change all uses of ConcreteClass to use the interface instead, and always pass the adapter instead of the concrete class in production code.

The adapter implements the interface, so the mock can also implement the interface.

It's more scaffolding than just making a method virtual or just adding an interface, but if you don't have access to the source for the concrete class it can get you out of a bind.

How do I compare 2 rows from the same table (SQL Server)?

SELECT COUNT(*) FROM (SELECT * FROM tbl WHERE id=1 UNION SELECT * FROM tbl WHERE id=2) a

If you got two rows, they different, if one - the same.

How do I get the current timezone name in Postgres 9.3?

See this answer: Source

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone. If TZ is not defined or is not any of the time zone names known to PostgreSQL, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime(). The default time zone is selected as the closest match among PostgreSQL's known time zones. (These rules are also used to choose the default value of log_timezone, if not specified.) source

This means that if you do not define a timezone, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone.

It seems to have the System's timezone to be set is possible indeed.

Get the OS local time zone from the shell. In psql:

=> \! date +%Z

Difference between WebStorm and PHPStorm

There is actually a comparison of the two in the official WebStorm FAQ. However, the version history of that page shows it was last updated December 13, so I'm not sure if it's maintained.

This is an extract from the FAQs for reference:

What is WebStorm & PhpStorm?

WebStorm & PhpStorm are IDEs (Integrated Development Environment) built on top of JetBrains IntelliJ platform and narrowed for web development.

Which IDE do I need?

PhpStorm is designed to cover all needs of PHP developer including full JavaScript, CSS and HTML support. WebStorm is for hardcore JavaScript developers. It includes features PHP developer normally doesn’t need like Node.JS or JSUnit. However corresponding plugins can be installed into PhpStorm for free.

How often new vesions (sic) are going to be released?

Preliminarily, WebStorm and PhpStorm major updates will be available twice in a year. Minor (bugfix) updates are issued periodically as required.

snip

IntelliJ IDEA vs WebStorm features

IntelliJ IDEA remains JetBrains' flagship product and IntelliJ IDEA provides full JavaScript support along with all other features of WebStorm via bundled or downloadable plugins. The only thing missing is the simplified project setup.

Rotating x axis labels in R for barplot

You can use ggplot2 to rotate the x-axis label adding an additional layer

theme(axis.text.x = element_text(angle = 90, hjust = 1))

How to set the JDK Netbeans runs on?

IN windows open cmd

go to directory where your netbeans downloaded

then run below command JDK path may be different from the path I mentioned

netbeans-8.2-windows.exe --javahome "C:\Program Files\Java\jdk-9.0.1"

if you face issue in existing installed in netbeans you can find details in here

Get user input from textarea

Here is full component example

import { Component } from '@angular/core';

@Component({
  selector: 'app-text-box',
  template: `
        <h1>Text ({{textValue}})</h1>
        <input #textbox type="text" [(ngModel)]="textValue" required>
        <button (click)="logText(textbox.value)">Update Log</button>
        <button (click)="textValue=''">Clear</button>

        <h2>Template Reference Variable</h2>
        Type: '{{textbox.type}}', required: '{{textbox.hasAttribute('required')}}',
        upper: '{{textbox.value.toUpperCase()}}'

        <h2>Log <button (click)="log=''">Clear</button></h2>
        <pre>{{log}}</pre>`
})
export class TextComponent {

  textValue = 'initial value';
  log = '';

  logText(value: string): void {
    this.log += `Text changed to '${value}'\n`;
  }
}

Google maps API V3 method fitBounds()

This happens because LatLngBounds() does not take two arbitrary points as parameters, but SW and NE points

use the .extend() method on an empty bounds object

var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);

Demo at http://jsfiddle.net/gaby/22qte/

How to disable keypad popup when on edittext?

Two Simple Solutions:

First Solution is added below line of code in manifest xml file. In Manifest file (AndroidManifest.xml), add the following attribute in the activity construct

android:windowSoftInputMode="stateHidden"

Example:

<activity android:name=".MainActivity" 
          android:windowSoftInputMode="stateHidden" />

Second Solution is adding below line of code in activity

//Block auto opening keyboard  
  this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

We can use any one solution of above. Thanks

Named colors in matplotlib

I constantly forget the names of the colors I want to use and keep coming back to this question =)

The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.

I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.

enter image description here

I really didn't change much from the matplotlib example, but here is the code for completeness.

import matplotlib.pyplot as plt
from matplotlib import colors as mcolors


colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)

# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]

n = len(sorted_names)
ncols = 4
nrows = n // ncols

fig, ax = plt.subplots(figsize=(12, 10))

# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols

for i, name in enumerate(sorted_names):
    row = i % nrows
    col = i // nrows
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.8),
            horizontalalignment='left',
            verticalalignment='center')

    ax.hlines(y + h * 0.1, xi_line, xf_line,
              color=colors[name], linewidth=(h * 0.8))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.show()

Additional named colors

Updated 2017-10-25. I merged my previous updates into this section.

xkcd

If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:

plt.plot([1,2], lw=4, c='xkcd:baby poop green')

Now you have access to a plethora of named colors!

enter image description here

Tableau

The default Tableau colors are available in matplotlib via the 'tab:' prefix:

plt.plot([1,2], lw=4, c='tab:green')

There are ten distinct colors:

enter image description here

HTML

You can also plot colors by their HTML hex code:

plt.plot([1,2], lw=4, c='#8f9805')

This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...


For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py.


Functional programming vs Object Oriented programming

Object Oriented Programming offers:

  1. Encapsulation, to
    • control mutation of internal state
    • limit coupling to internal representation
  2. Subtyping, allowing:
    • substitution of compatible types (polymorphism)
    • a crude means of sharing implementation between classes (implementation inheritance)

Functional Programming, in Haskell or even in Scala, can allow substitution through more general mechanism of type classes. Mutable internal state is either discouraged or forbidden. Encapsulation of internal representation can also be achieved. See Haskell vs OOP for a good comparison.

Norman's assertion that "Adding a new kind of thing to a functional program may require editing many function definitions to add a new case." depends on how well the functional code has employed type classes. If Pattern Matching on a particular Abstract Data Type is spread throughout a codebase, you will indeed suffer from this problem, but it is perhaps a poor design to start with.

EDITED Removed reference to implicit conversions when discussing type classes. In Scala, type classes are encoded with implicit parameters, not conversions, although implicit conversions are another means to acheiving substitution of compatible types.

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

I use this:

var app = express();

app
.use(function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    next();
})
.options('*', function(req, res, next){
    res.end();
})
;

h.readFiles('controllers').forEach(function(file){
  require('./controllers/' + file)(app);
})
;

app.listen(port);
console.log('server listening on port ' + port);

this code assumes that your controllers are located in the controllers directory. each file in this directory should be something like this:

module.exports = function(app){

    app.get('/', function(req, res, next){
        res.end('hi');
    });

}

How to force DNS refresh for a website?

If both of your servers are using WHM, I think we can reduce the time to nil. Create your domain in the new server and set everything ready. Go to the previous server and delete the account corresponding to that domain. Until now I have got no errors by doing this and felt the update instantaneous. FYI I used hostgator hosting (both dedicated servers). And I really dont know why it is so. It's supposed to be not like that until the TTL is over.

Zip folder in C#

There is a ZipPackage class in the System.IO.Packaging namespace which is built into .NET 3, 3.5, and 4.0.

http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx

Here is an example how to use it. http://www.codeproject.com/KB/files/ZipUnZipTool.aspx?display=Print

Android soft keyboard covers EditText field

just add

android:gravity="bottom" android:paddingBottom="10dp"

change paddingBottom according to your size of edittext

Change string color with NSAttributedString?

With Swift 4, NSAttributedStringKey has a static property called foregroundColor. foregroundColor has the following declaration:

static let foregroundColor: NSAttributedStringKey

The value of this attribute is a UIColor object. Use this attribute to specify the color of the text during rendering. If you do not specify this attribute, the text is rendered in black.

The following Playground code shows how to set the text color of an NSAttributedString instance with foregroundColor:

import UIKit

let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)

The code below shows a possible UIViewController implementation that relies on NSAttributedString in order to update the text and text color of a UILabel from a UISlider:

import UIKit

enum Status: Int {
    case veryBad = 0, bad, okay, good, veryGood

    var display: (text: String, color: UIColor) {
        switch self {
        case .veryBad:  return ("Very bad", .red)
        case .bad:      return ("Bad", .orange)
        case .okay:     return ("Okay", .yellow)
        case .good:     return ("Good", .green)
        case .veryGood: return ("Very good", .blue)
        }
    }

    static let minimumValue = Status.veryBad.rawValue
    static let maximumValue = Status.veryGood.rawValue
}
final class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var slider: UISlider!
    var currentStatus: Status = Status.veryBad {
        didSet {
            // currentStatus is our model. Observe its changes to update our display
            updateDisplay()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Prepare slider
        slider.minimumValue = Float(Status.minimumValue)
        slider.maximumValue = Float(Status.maximumValue)

        // Set display
        updateDisplay()
    }

    func updateDisplay() {
        let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
        let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
        label.attributedText = attributedString
        slider.value = Float(currentStatus.rawValue)
    }

    @IBAction func updateCurrentStatus(_ sender: UISlider) {
        let value = Int(sender.value.rounded())
        guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
        currentStatus = status
    }

}

Note however that you don't really need to use NSAttributedString for such an example and can simply rely on UILabel's text and textColor properties. Therefore, you can replace your updateDisplay() implementation with the following code:

func updateDisplay() {
    label.text = currentStatus.display.text
    label.textColor = currentStatus.display.color
    slider.value = Float(currentStatus.rawValue)
}

How might I find the largest number contained in a JavaScript array?

Finding max and min value the easy and manual way. This code is much faster than Math.max.apply; I have tried up to 1000k numbers in array.

function findmax(array)
{
    var max = 0;
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] > max)
        {
            max = array[counter];
        }
    }
    return max;
}

function findmin(array)
{
    var min = array[0];
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] < min)
        {
            min = array[counter];
        }
    }
    return min;
}

Where are $_SESSION variables stored?

As Mr. Taylor pointed out this is usually set in php.ini. Usually they are stored as files in a specific directory.

How can I get query string values in JavaScript?

This function converts the querystring to a JSON-like object, it also handles value-less and multi-value parameters:

"use strict";
function getQuerystringData(name) {
    var data = { };
    var parameters = window.location.search.substring(1).split("&");
    for (var i = 0, j = parameters.length; i < j; i++) {
        var parameter = parameters[i].split("=");
        var parameterName = decodeURIComponent(parameter[0]);
        var parameterValue = typeof parameter[1] === "undefined" ? parameter[1] : decodeURIComponent(parameter[1]);
        var dataType = typeof data[parameterName];
        if (dataType === "undefined") {
            data[parameterName] = parameterValue;
        } else if (dataType === "array") {
            data[parameterName].push(parameterValue);
        } else {
            data[parameterName] = [data[parameterName]];
            data[parameterName].push(parameterValue);
        }
    }
    return typeof name === "string" ? data[name] : data;
}

We perform a check for undefined on parameter[1] because decodeURIComponent returns the string "undefined" if the variable is undefined, and that's wrong.

Usage:

"use strict";
var data = getQuerystringData();
var parameterValue = getQuerystringData("parameterName");

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

How do I delete a Git branch locally and remotely?

Deleting Branches

Let's assume our work on branch "contact-form" is done and we've already integrated it into "master". Since we don't need it anymore, we can delete it (locally):

$ git branch -d contact-form

And for deleting the remote branch:

git push origin --delete contact-form

Group by with union mysql select query

Try this EDITED:

(SELECT COUNT(motorbike.owner_id),owner.name,transport.type FROM transport,owner,motorbike WHERE transport.type='motobike' AND owner.owner_id=motorbike.owner_id AND transport.type_id=motorbike.motorbike_id GROUP BY motorbike.owner_id)

UNION ALL

(SELECT COUNT(car.owner_id),owner.name,transport.type FROM transport,owner,car WHERE transport.type='car' AND owner.owner_id=car.owner_id AND transport.type_id=car.car_id GROUP BY car.owner_id)

How do I count the number of rows and columns in a file using bash?

head -1 file.tsv |head -1 train.tsv |tr '\t' '\n' |wc -l

take the first line, change tabs (or you can use ',' instead of '\t' for commas), count the number of lines.

Submit Button Image

You have to remove the borders and add a background image on the input.

.imgClass { 
    background-image: url(path to image) no-repeat;
    width: 186px;
    height: 53px;
    border: none;
}

It should be good now, normally.

VBA Public Array : how to?

Well, basically what I found is that you can declare the array, but when you set it vba shows you an error.

So I put an special sub to declare global variables and arrays, something like:

Global example(10) As Variant

Sub set_values()

example(1) = 1
example(2) = 1
example(3) = 1
example(4) = 1
example(5) = 1
example(6) = 1
example(7) = 1
example(8) = 1
example(9) = 1
example(10) = 1

End Sub

And whenever I want to use the array, I call the sub first, just in case

call set_values

Msgbox example(5)

Perhaps is not the most correct way, but I hope it works for you

print variable and a string in python

Assuming you use Python 2.7 (not 3):

print "I have", card.price (as mentioned above).

print "I have %s" % card.price (using string formatting)

print " ".join(map(str, ["I have", card.price])) (by joining lists)

There are a lot of ways to do the same, actually. I would prefer the second one.

How to get my project path?

This gives you the root folder:

System.AppDomain.CurrentDomain.BaseDirectory

You can navigate from here using .. or ./ etc.. , Appending .. takes you to folder where .sln file can be found

For .NET framework (thanks to Adiono comment)

Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"..\\..\\"))

For .NET core here is a way to do it (thanks to nopara73 comment)

Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")) ;

What is the non-jQuery equivalent of '$(document).ready()'?

This does not answer the question nor does it show any non-jQuery code. See @ sospedra's answer below.

The nice thing about $(document).ready() is that it fires before window.onload. The load function waits until everything is loaded, including external assets and images. $(document).ready, however, fires when the DOM tree is complete and can be manipulated. If you want to acheive DOM ready, without jQuery, you might check into this library. Someone extracted just the ready part from jQuery. Its nice and small and you might find it useful:

domready at Google Code

How to make graphics with transparent background in R using ggplot2?

Updated with the theme() function, ggsave() and the code for the legend background:

df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
  stat_boxplot(aes(x = x, y = y, color = group), 
               fill = "transparent" # for the inside of the boxplot
  ) 

Fastest way is using using rect, as all the rectangle elements inherit from rect:

p <- p +
  theme(
        rect = element_rect(fill = "transparent") # all rectangles
      )
    p

More controlled way is to use options of theme:

p <- p +
  theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
  )
p

To save (this last step is important):

ggsave(p, filename = "tr_tst2.png",  bg = "transparent")

Multiple submit buttons in the same form calling different Servlets

There are several ways to achieve this.

Probably the easiest would be to use JavaScript to change the form's action.

<input type="submit" value="SecondServlet" onclick="form.action='SecondServlet';">

But this of course won't work when the enduser has JS disabled (mobile browsers, screenreaders, etc).


Another way is to put the second button in a different form, which may or may not be what you need, depending on the concrete functional requirement, which is not clear from the question at all.

<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" value="FirstServlet">
</form>
<form action="SecondServlet" method="Post">
    <input type="submit"value="SecondServlet">
</form>

Note that a form would on submit only send the input data contained in the very same form, not in the other form.


Again another way is to just create another single entry point servlet which delegates further to the right servlets (or preferably, the right business actions) depending on the button pressed (which is by itself available as a request parameter by its name):

<form action="MainServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" name="action" value="FirstServlet">
    <input type="submit" name="action" value="SecondServlet">
</form>

with the following in MainServlet

String action = request.getParameter("action");

if ("FirstServlet".equals(action)) {
    // Invoke FirstServlet's job here.
} else if ("SecondServlet".equals(action)) {
    // Invoke SecondServlet's job here.
}

This is only not very i18n/maintenance friendly. What if you need to show buttons in a different language or change the button values while forgetting to take the servlet code into account?


A slight change is to give the buttons its own fixed and unique name, so that its presence as request parameter could be checked instead of its value which would be sensitive to i18n/maintenance:

<form action="MainServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" name="first" value="FirstServlet">
    <input type="submit" name="second" value="SecondServlet">
</form>

with the following in MainServlet

if (request.getParameter("first") != null) {
    // Invoke FirstServlet's job here.
} else if (request.getParameter("second") != null) {
    // Invoke SecondServlet's job here.
}

Last way would be to just use a MVC framework like JSF so that you can directly bind javabean methods to buttons, but that would require drastic changes to your existing code.

<h:form>
    Last Name: <h:inputText value="#{bean.lastName}" size="20" />
    <br/><br/>
    <h:commandButton value="First" action="#{bean.first}" />
    <h:commandButton value="Second" action="#{bean.Second}" />
</h:form>

with just the following javabean instead of a servlet

@ManagedBean
@RequestScoped
public class Bean {

    private String lastName; // +getter+setter

    public void first() {
        // Invoke original FirstServlet's job here.
    }

    public void second() {
        // Invoke original SecondServlet's job here.
    }

}

Hibernate: get entity by id

use get instead of load

// ...
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            user =  (User) session.get(User.class, user_id);
        } catch (Exception e) {
 // ...

Find stored procedure by name

Assuming you're in the Object Explorer Details (F7) showing the list of Stored Procedures, click the Filters button and enter the name (or partial name).

alt text

How to do a timer in Angular 5

This may be overkill for what you're looking for, but there is an npm package called marky that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer. You just need to install it via npm and then import the dependency anywhere you'd like to use it. Here is a link to the npm package: https://www.npmjs.com/package/marky

An example of use after installing via npm would be as follows:

import * as _M from 'marky';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
 Marky = _M;
}

constructor() {}

ngOnInit() {}

startTimer(key: string) {
 this.Marky.mark(key);
}

stopTimer(key: string) {
 this.Marky.stop(key);
}

key is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.

CSS: auto height on containing div, 100% height on background div inside containing div

Make #container to display:inline-block

#container {
  height: auto;
  width: 100%;
  display: inline-block;
}

#content {
  height: auto;
  width: 500px;
  margin-left: auto;
  margin-right: auto;
}

#backgroundContainer {
  height: 200px; /*200px is example, change to what you want*/
  width: 100%;
}

Also see: W3Schools

SQL Server Output Clause into a scalar variable

You need a table variable and it can be this simple.

declare @ID table (ID int)

insert into MyTable2(ID)
output inserted.ID into @ID
values (1)

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

Here are more code examples that will produce the argument null exception:

List<Myobj> myList = null;
//from this point on, any linq statement you perform on myList will throw an argument null exception
myList.ToList();
myList.GroupBy(m => m.Id);
myList.Count();
myList.Where(m => m.Id == 0);
myList.Select(m => m.Id == 0);
//etc...

Remove characters from a string

Using replace() with regular expressions is the most flexible/powerful. It's also the only way to globally replace every instance of a search pattern in JavaScript. The non-regex variant of replace() will only replace the first instance.

For example:

var str = "foo gar gaz";

// returns: "foo bar gaz"
str.replace('g', 'b');

// returns: "foo bar baz"
str = str.replace(/g/gi, 'b');

In the latter example, the trailing /gi indicates case-insensitivity and global replacement (meaning that not just the first instance should be replaced), which is what you typically want when you're replacing in strings.

To remove characters, use an empty string as the replacement:

var str = "foo bar baz";

// returns: "foo r z"
str.replace(/ba/gi, '');

Multipart File upload Spring Boot

@RequestMapping(value="/add/image", method=RequestMethod.POST)
public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
{   
    try {
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
        Iterator<String> it=multipartRequest.getFileNames();
        MultipartFile multipart=multipartRequest.getFile(it.next());
        String fileName=id+".png";
        String imageName = fileName;

        byte[] bytes=multipart.getBytes();
        BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));;

        stream.write(bytes);
        stream.close();
        return new ResponseEntity("upload success", HttpStatus.OK);

    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST);
    }   
}

Differences between action and actionListener

As BalusC indicated, the actionListener by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.

This happens through a call like this:

context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,                                                          
    new ExceptionQueuedEventContext(context, exception, source, phaseId)
);

The default listener for this event is the ExceptionHandler which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.

This ExceptionHandler can be replaced however in faces-config.xml with a custom implementation:

<exception-handlerfactory>
   com.foo.myExceptionHandler
</exception-handlerfactory>

Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:

@ManagedBean
@RequestScoped
public class MyBean {

    public void actionMethod(ActionEvent event) {

        FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {

        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
            ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
            throw new RuntimeException(content.getException());
        }

        @Override
        public boolean isListenerForSource(Object source) {
            return true;
        }
        });

        throw new RuntimeException("test");
    }

}

(note, this is not how one should normally code listeners, this is only for demonstration purposes!)

Calling this from a Facelet like this:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <h:form>
            <h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
        </h:form>
    </h:body>
</html>

Will result in an error page being displayed.

c++ boost split string

My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:

-----------test2-------test3

What happened is the machine actually printed this:

test-------test2-------test3\r-------

That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).

How to close a Tkinter window by pressing a Button?

You can use lambda to pass a reference to the window object as argument to close_window function:

button = Button (frame, text="Good-bye.", command = lambda: close_window(window))

This works because the command attribute is expecting a callable, or callable like object. A lambda is a callable, but in this case it is essentially the result of calling a given function with set parameters.

In essence, you're calling the lambda wrapper of the function which has no args, not the function itself.

ORA-00918: column ambiguously defined in SELECT *

A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting * your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.

The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID.

Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT * is regarded as bad practice in production code: explicitly named columns are much safer.

Remove Unnamed columns in pandas dataframe

The pandas.DataFrame.dropna function removes missing values (e.g. NaN, NaT).

For example the following code would remove any columns from your dataframe, where all of the elements of that column are missing.

df.dropna(how='all', axis='columns')

iPhone Safari Web App opens links in new window

I created a bower installable package out of @rmarscher's answer which can be found here:

http://github.com/stylr/iosweblinks

You can easily install the snippet with bower using bower install --save iosweblinks

jQuery duplicate DIV into another DIV

Copy code using clone and appendTo function :

Here is also working example jsfiddle

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="copy"><a href="http://brightwaay.com">Here</a> </div>
<br/>
<div id="copied"></div>
<script type="text/javascript">
    $(function(){
        $('#copy').clone().appendTo('#copied');
    });
</script>
</body>
</html>

Best way to store a key=>value array in JavaScript?

That's just what a JavaScript object is:

var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
myArray.id3 = 400;
myArray["id4"] = 500;

You can loop through it using for..in loop:

for (var key in myArray) {
  console.log("key " + key + " has value " + myArray[key]);
}

See also: Working with objects (MDN).

In ECMAScript6 there is also Map (see the browser compatibility table there):

  • An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done.

  • The keys of an Object are Strings and Symbols, where they can be any value for a Map.

  • You can get the size of a Map easily while you have to manually keep track of size for an Object.

'profile name is not valid' error when executing the sp_send_dbmail command

profile name is not valid [SQLSTATE 42000] (Error 14607)

This happened to me after I copied job script from old SQL server to new SQL server. In SSMS, under Management, the Database Mail profile name was different in the new SQL Server. All I had to do was update the name in job script.

PostgreSQL psql terminal command

These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.

Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):

psql -h host -p 5900 -U username database
\pset format aligned

Python - converting a string of numbers into a list of int

I guess the dirtiest solution is this:

list(eval('0, 0, 0, 11, 0, 0, 0, 11'))

Getting multiple values with scanf()

Yes.

int minx, miny, maxx,maxy;
do {
   printf("enter four integers: ");
} while (scanf("%d %d %d %d", &minx, &miny, &maxx, &maxy)!=4);

The loop is just to demonstrate that scanf returns the number of fields succesfully read (or EOF).

Array formula on Excel for Mac

  1. Select the desired range of cells
  2. Press Fn + F2 or CONTROL + U
  3. Paste in your array value
  4. Press COMMAND (?) + SHIFT + RETURN

Send raw ZPL to Zebra printer via USB

I've found yet an easier way to write to a Zebra printer over a COM port. I went to the Windows control panel and added a new printer. For the port, I chose COM1 (the port the printer was plugged in to). I used a "Generic / Text Only" printer driver. I disabled the print spooler (a standard option in the printer preferences) as well as all advanced printing options. Now, I can just print any string to that printer and if the string contains ZPL, the printer renders the ZPL just fine! No need for special "start sequences" or funky stuff like that. Yay for simplicity!

jQuery: how to scroll to certain anchor/div on page load?

Have a look at this

Appending the #value into the address is default behaviour that browsers such as IE use to identify named anchor positions on the page, seeing this comes from Netscape.

You can intercept it and remove it, read this article.

Changing datagridview cell color dynamically

This works for me

dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;

How to define a relative path in java

I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.

private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className  + ".html";
ExtentReports report;
ExtentTest test;

@BeforeMethod
    //  initialise report variables
    report = new ExtentReports(outputFolder + outputFile);
    test = report.startTest(className);
    // more setup code

@Test
    // test method code with log statements

@AfterMethod
    // takeScreenShot returns the relative path and filename for the image
    String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
    String imagePath = test.addScreenCapture(imgFilename);
    test.log(LogStatus.FAIL, "Added image to report", imagePath);

This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".

This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.

Chris

String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);

Can someone give an example of cosine similarity, in a very simple, graphical way?

Here's my implementation in C#.

using System;

namespace CosineSimilarity
{
    class Program
    {
        static void Main()
        {
            int[] vecA = {1, 2, 3, 4, 5};
            int[] vecB = {6, 7, 7, 9, 10};

            var cosSimilarity = CalculateCosineSimilarity(vecA, vecB);

            Console.WriteLine(cosSimilarity);
            Console.Read();
        }

        private static double CalculateCosineSimilarity(int[] vecA, int[] vecB)
        {
            var dotProduct = DotProduct(vecA, vecB);
            var magnitudeOfA = Magnitude(vecA);
            var magnitudeOfB = Magnitude(vecB);

            return dotProduct/(magnitudeOfA*magnitudeOfB);
        }

        private static double DotProduct(int[] vecA, int[] vecB)
        {
            // I'm not validating inputs here for simplicity.            
            double dotProduct = 0;
            for (var i = 0; i < vecA.Length; i++)
            {
                dotProduct += (vecA[i] * vecB[i]);
            }

            return dotProduct;
        }

        // Magnitude of the vector is the square root of the dot product of the vector with itself.
        private static double Magnitude(int[] vector)
        {
            return Math.Sqrt(DotProduct(vector, vector));
        }
    }
}

Text blinking jQuery

result

$('.blink').fadeIn('fast')
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100)
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100)
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100)
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100)
    .animate({
        color: "#FFCD56"
    }, 100).animate({
        color: "white"
    }, 100);

Prevent content from expanding grid items

The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr) instead of 1fr as your track size.

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.

Modulo operator in Python

same as a normal modulo 3.14 % 6.28 = 3.14, just like 3.14%4 =3.14 3.14%2 = 1.14 (the remainder...)

How to execute a raw update sql with dynamic binding in rails

You should just use something like:

YourModel.update_all(
  ActiveRecord::Base.send(:sanitize_sql_for_assignment, {:value => "'wow'"})
)

That would do the trick. Using the ActiveRecord::Base#send method to invoke the sanitize_sql_for_assignment makes the Ruby (at least the 1.8.7 version) skip the fact that the sanitize_sql_for_assignment is actually a protected method.

$(document).ready(function() is not working

I found we need to use noConflict sometimes:

jQuery.noConflict()(function ($) { // this was missing for me
    $(document).ready(function() { 

       other code here....

    });
});

From the docs:

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

Python division

You need to change it to a float BEFORE you do the division. That is:

float(20 - 10) / (100 - 10)

Reading a file character by character in C

The problem here is twofold

  • a) you increment the pointer before you check the value read in, and
  • b) you ignore the fact that fgetc() returns an int instead of a char.

The first is easily fixed:

char *orig = code; // the beginning of the array
// ...
do {
  *code = fgetc(file);
} while(*code++ != EOF);
*code = '\0'; // nul-terminate the string
return orig; // don't return a pointer to the end

The second problem is more subtle -fgetc returns an int so that the EOF value can be distinguished from any possible char value. Fixing this uses a temporary int for the EOF check and probably a regular while loop instead of do / while.

How to check if a string starts with one of several prefixes?

if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || newStr4.startsWith("Weds") .. etc)

You need to include the whole str.startsWith(otherStr) for each item, since || only works with boolean expressions (true or false).

There are other options if you have a lot of things to check, like regular expressions, but they tend to be slower and more complicated regular expressions are generally harder to read.

An example regular expression for detecting day name abbreviations would be:

if(Pattern.matches("Mon|Tues|Wed|Thurs|Fri", stringToCheck)) {

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

If working with classes you need to make sure you reference member variables using $this:

class Person
{
    protected $firstName;
    protected $lastName;

    public function setFullName($first, $last)
    {
        // Correct
        $this->firstName = $first;

        // Incorrect
        $lastName = $last;

        // Incorrect
        $this->$lastName = $last;
    }
}

What is the difference between Jupyter Notebook and JupyterLab?

If you are looking for features that notebooks in JupyterLab have that traditional Jupyter Notebooks do not, check out the JupyterLab notebooks documentation. There is a simple video showing how to use each of the features in the documentation link.

JupyterLab notebooks have the following features and more:

  • Drag and drop cells to rearrange your notebook
  • Drag cells between notebooks to quickly copy content (since you can
    have more than one open at a time)
  • Create multiple synchronized views of a single notebook
  • Themes and customizations: Dark theme and increase code font size

Add a summary row with totals

Try to use union all as below

SELECT [Type], [Total Sales] From Before
union all
SELECT 'Total', Sum([Total Sales]) From Before

if you have problem with ordering, as i-one suggested try this:

select [Type], [Total Sales] 
from (SELECT [Type], [Total Sales], 0 [Key] 
      From Before 
      union all 
      SELECT 'Total', Sum([Total Sales]), 1 From Before) sq 
order by [Key], Type

How do I reference the input of an HTML <textarea> control in codebehind?

You should reference the textarea ID and include the runat="server" attribute to the textarea

message.Body = TextArea1.Text;  

What is test123?


How to edit/save a file through Ubuntu Terminal

If you are not root user then, use following commands:

There are two ways to do it -

1.

sudo vi path_to_file/file_name

Press Esc and then type below respectively

:wq //save and exit
:q! //exit without saving
  1. sudo nano path_to_file/file_name

When using nano: after you finish editing press ctrl+x then it will ask save Y/N.
If you want to save press Y, if not press N. And press enter to exit the editor.

Asp.net 4.0 has not been registered

If ASP.NET 4.0 is not registered with IIS

*****Use this step if u cant access using run command*****

Go to

C Drive
-->>windows
-->>Microsoft.Net
-->>Framework
-->>v4.0.30319

(Choose whatever framework to register with IIS me selecting Framework 4)
-->>aspnet_regiis
(Double-click or right click & choose run as administrator)

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

Just rename the command or file name ln -s /usr/bin/nodejs /usr/bin/node by this command

git revert back to certain commit

http://www.kernel.org/pub/software/scm/git/docs/git-revert.html

using git revert <commit> will create a new commit that reverts the one you dont want to have.

You can specify a list of commits to revert.

An alternative: http://git-scm.com/docs/git-reset

git reset will reset your copy to the commit you want.

Tainted canvases may not be exported

If you're using ctx.drawImage() function, you can do the following:

var img = loadImage('../yourimage.png', callback);

function loadImage(src, callback) {
    var img = new Image();

    img.onload = callback;
    img.setAttribute('crossorigin', 'anonymous'); // works for me

    img.src = src;

    return img;
}

And in your callback you can now use ctx.drawImage and export it using toDataURL

Is there a way that I can check if a data attribute exists?

if ($("#dataTable").data('timer')) {
  ...
}

NOTE this only returns true if the data attribute is not empty string or a "falsey" value e.g. 0 or false.

If you want to check for the existence of the data attribute, even if empty, do this:

if (typeof $("#dataTable").data('timer') !== 'undefined') {
  ...
}

Map<String, String>, how to print both the "key string" and "value string" together

There are various ways to achieve this. Here are three.

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println("using entrySet and toString");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry);
    }
    System.out.println();

    System.out.println("using entrySet and manual string creation");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    System.out.println();

    System.out.println("using keySet");
    for (String key : map.keySet()) {
        System.out.println(key + "=" + map.get(key));
    }
    System.out.println();

Output

using entrySet and toString
key1=value1
key2=value2
key3=value3

using entrySet and manual string creation
key1=value1
key2=value2
key3=value3

using keySet
key1=value1
key2=value2
key3=value3

HTML-Tooltip position relative to mouse pointer

We can achieve the same using "Directive" in Angularjs.

            //Bind mousemove event to the element which will show tooltip
            $("#tooltip").mousemove(function(e) {
                //find X & Y coodrinates
                x = e.clientX,
                y = e.clientY;

                //Set tooltip position according to mouse position
                tooltipSpan.style.top = (y + 20) + 'px';
                tooltipSpan.style.left = (x + 20) + 'px';
            });

You can check this post for further details. http://www.ufthelp.com/2014/12/Tooltip-Directive-AngularJS.html

How do you do relative time in Rails?

Another approach is to unload some logic from the backend and maek the browser do the job by using Javascript plugins such as:

jQuery time ago or its Rails Gem adaptation

Angular checkbox and ng-click

The order of execution of ng-click and ng-model is ambiguous since they do not define clear priorities. Instead you should use ng-change or a $watch on the $scope to ensure that you obtain the correct values of the model variable.

In your case, this should work:

<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">

PHP: Call to undefined function: simplexml_load_string()

If the XML module is not installed, install it.

Current version 5.6 on ubuntu 14.04:

sudo apt-get install php5.6-xml

And don't forget to run sudo service apache2 restart command after it

Zulhilmi Zainudi

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

How to run test methods in specific order in JUnit4?

I've read a few answers and agree its not best practice, but the easiest way to order your tests - and the way that JUnit runs tests by default is by alphabetic name ascending.

So just name your tests in the alphabetic order that you want. Also note the test name must begin with the word test. Just watch out for numbers

test12 will run before test2

so:

testA_MyFirstTest testC_ThirdTest testB_ATestThatRunsSecond

How to detect if URL has changed after hash in JavaScript

You are starting a new setInterval at each call, without cancelling the previous one - probably you only meant to have a setTimeout

running php script (php function) in linux bash

just run in linux terminal to get phpinfo .

   php -r 'phpinfo();'

and to run file like index.php

    php -f index.php

error_log per Virtual Host?

You can try:

    <VirtualHost myvhost:80>
       php_value error_log "/var/log/httpd/vhost_php_error_log"
    </Virtual Host>

But I'm not sure if it is going to work. I tried on my sites with no success.

In Python How can I declare a Dynamic Array

In python, A dynamic array is an 'array' from the array module. E.g.

from array import array
x = array('d')          #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop()                 # returns 2.2

This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.

However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.

See https://docs.python.org/2/library/array.html for details.

How to force Chrome browser to reload .css file while debugging in Visual Studio?

To force chrome to reaload css and js:

Windows option 1: CTRL + SHIFT + R
Windows option 2: SHIFT + F5

OS X: ? + SHIFT + R

Updated as stated by @PaulSlocum in the comments (and many confirmed)


Original answer:

Chrome changed behavior. Ctrl + R will do it.

On OS X: ? + R

If you have problems reloading css/js files, open the inspector (CTRL + SHIFT + C) before doing the reload.

Calculating moving average

The slider package can be used for this. It has an interface that has been specifically designed to feel similar to purrr. It accepts any arbitrary function, and can return any type of output. Data frames are even iterated over row wise. The pkgdown site is here.

library(slider)

x <- 1:3

# Mean of the current value + 1 value before it
# returned as a double vector
slide_dbl(x, ~mean(.x, na.rm = TRUE), .before = 1)
#> [1] 1.0 1.5 2.5


df <- data.frame(x = x, y = x)

# Slide row wise over data frames
slide(df, ~.x, .before = 1)
#> [[1]]
#>   x y
#> 1 1 1
#> 
#> [[2]]
#>   x y
#> 1 1 1
#> 2 2 2
#> 
#> [[3]]
#>   x y
#> 1 2 2
#> 2 3 3

The overhead of both slider and data.table's frollapply() should be pretty low (much faster than zoo). frollapply() looks to be a little faster for this simple example here, but note that it only takes numeric input, and the output must be a scalar numeric value. slider functions are completely generic, and you can return any data type.

library(slider)
library(zoo)
library(data.table)

x <- 1:50000 + 0L

bench::mark(
  slider = slide_int(x, function(x) 1L, .before = 5, .complete = TRUE),
  zoo = rollapplyr(x, FUN = function(x) 1L, width = 6, fill = NA),
  datatable = frollapply(x, n = 6, FUN = function(x) 1L),
  iterations = 200
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 slider      19.82ms   26.4ms     38.4    829.8KB     19.0
#> 2 zoo        177.92ms  211.1ms      4.71    17.9MB     24.8
#> 3 datatable    7.78ms   10.9ms     87.9    807.1KB     38.7

android layout with visibility GONE

Kotlin Style way to do this more simple (example):

    isVisible = false

Complete example:

    if (some_data_array.details == null){
                holder.view.some_data_array.isVisible = false}

How to get the current user's Active Directory details in C#

Add reference to COM "Active DS Type Library"


            Int32 nameTypeNT4               = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4;
            Int32 nameTypeDN                = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_1779;
            Int32 nameTypeUserPrincipalName = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_USER_PRINCIPAL_NAME;

            ActiveDs.NameTranslate nameTranslate = new ActiveDs.NameTranslate();

            // Convert NT name DOMAIN\User into AD distinguished name 
            // "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com"
            nameTranslate.Set(nameTypeNT4, ntUser);

            String distinguishedName = nameTranslate.Get(nameTypeDN);

            Console.WriteLine(distinguishedName);

            // Convert AD distinguished name "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com" 
            // into NT name DOMAIN\User
            ntUser = String.Empty;
            nameTranslate.Set(nameTypeDN, distinguishedName);
            ntUser = nameTranslate.Get(nameTypeNT4);
            Console.WriteLine(ntUser);

            // Convert NT name DOMAIN\User into AD UserPrincipalName [email protected]
            nameTranslate.Set(nameTypeNT4, ntUser);
            String userPrincipalName = nameTranslate.Get(nameTypeUserPrincipalName);

            Console.WriteLine(userPrincipalName);

Get JSON Data from URL Using Android?

Easy way to get JSON especially for Android SDK 23:

public class MainActivity extends AppCompatActivity {

Button btnHit;
TextView txtJson;
ProgressDialog pd;

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

    btnHit = (Button) findViewById(R.id.btnHit);
    txtJson = (TextView) findViewById(R.id.tvJsonItem);

    btnHit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JsonTask().execute("Url address here");
        }
    });


}


private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        txtJson.setText(result);
    }
}
}

convert pfx format to p12

Run this command to change .cert file to .p12:

openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt 

Where server.key is the server key and server.cert is a CA issue cert or a self sign cert file.

How to get element by class name?

you can use

getElementsByClassName

suppose you have some elements and applied a class name 'test', so, you can get elements like as following

var tests = document.getElementsByClassName('test');

its returns an instance NodeList, or its superset: HTMLCollection (FF).

Read more

How to round the minute of a datetime object

def get_rounded_datetime(self, dt, freq, nearest_type='inf'):

    if freq.lower() == '1h':
        round_to = 3600
    elif freq.lower() == '3h':
        round_to = 3 * 3600
    elif freq.lower() == '6h':
        round_to = 6 * 3600
    else:
        raise NotImplementedError("Freq %s is not handled yet" % freq)

    # // is a floor division, not a comment on following line:
    seconds_from_midnight = dt.hour * 3600 + dt.minute * 60 + dt.second
    if nearest_type == 'inf':
        rounded_sec = int(seconds_from_midnight / round_to) * round_to
    elif nearest_type == 'sup':
        rounded_sec = (int(seconds_from_midnight / round_to) + 1) * round_to
    else:
        raise IllegalArgumentException("nearest_type should be  'inf' or 'sup'")

    dt_midnight = datetime.datetime(dt.year, dt.month, dt.day)

    return dt_midnight + datetime.timedelta(0, rounded_sec)

JavaScript seconds to time string with format hh:mm:ss

Easiest way to do it.

new Date(sec * 1000).toISOString().substr(11, 8)

How do I choose grid and block dimensions for CUDA kernels?

The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.

MySQL user DB does not have password columns - Installing MySQL on OSX

In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'.

First choose the database:

mysql>use mysql;

And then show the tables:

mysql>show tables;

You will find the user table, now let's see its fields:

mysql> describe user;
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                  | Type                              | Null | Key | Default               | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                   | char(60)                          | NO   | PRI |                       |       |
| User                   | char(16)                          | NO   | PRI |                       |       |
| Select_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Insert_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Update_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Delete_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Create_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Reload_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Shutdown_priv          | enum('N','Y')                     | NO   |     | N                     |       |
| Process_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| File_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Grant_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| References_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Index_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Show_db_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Super_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tmp_table_priv  | enum('N','Y')                     | NO   |     | N                     |       |
| Lock_tables_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Execute_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_slave_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_client_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Create_view_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Show_view_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Create_routine_priv    | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_routine_priv     | enum('N','Y')                     | NO   |     | N                     |       |
| Create_user_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Event_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Trigger_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tablespace_priv | enum('N','Y')                     | NO   |     | N                     |       |
| ssl_type               | enum('','ANY','X509','SPECIFIED') | NO   |     |                       |       |
| ssl_cipher             | blob                              | NO   |     | NULL                  |       |
| x509_issuer            | blob                              | NO   |     | NULL                  |       |
| x509_subject           | blob                              | NO   |     | NULL                  |       |
| max_questions          | int(11) unsigned                  | NO   |     | 0                     |       |
| max_updates            | int(11) unsigned                  | NO   |     | 0                     |       |
| max_connections        | int(11) unsigned                  | NO   |     | 0                     |       |
| max_user_connections   | int(11) unsigned                  | NO   |     | 0                     |       |
| plugin                 | char(64)                          | NO   |     | mysql_native_password |       |
| authentication_string  | text                              | YES  |     | NULL                  |       |
| password_expired       | enum('N','Y')                     | NO   |     | N                     |       |
| password_last_changed  | timestamp                         | YES  |     | NULL                  |       |
| password_lifetime      | smallint(5) unsigned              | YES  |     | NULL                  |       |
| account_locked         | enum('N','Y')                     | NO   |     | N                     |       |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
45 rows in set (0.00 sec)

Surprise!There is no field named 'password', the password field is named ' authentication_string'. So, just do this:

update user set authentication_string=password('1111') where user='root';

Now, everything will be ok.

Compared to MySQL 5.6, the changes are quite extensive: What’s New in MySQL 5.7

How to redirect both stdout and stderr to a file

If you want to log to the same file:

command1 >> log_file 2>&1

If you want different files:

command1 >> log_file 2>> err_file

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

$_POST should only get populated on POST requests. The browser usually sends GET requests. If you reached a page via POST it usually asks you if it should resend the POST data when you hit refresh. What it does is simply that - sending the POST data again. To PHP that looks like a different request although it semantically contains the same data.

Pass Array Parameter in SqlCommand

I want to propose another way, how to solve limitation with IN operator.

For example we have following query

select *
from Users U
WHERE U.ID in (@ids)

We want to pass several IDs to filter users. Unfortunately it is not possible to do with C# in easy way. But I have fount workaround for this by using "string_split" function. We need to rewrite a bit our query to following.

declare @ids nvarchar(max) = '1,2,3'

SELECT *
FROM Users as U
CROSS APPLY string_split(@ids, ',') as UIDS
WHERE U.ID = UIDS.value

Now we can easily pass one parameter enumeration of values separated by comma.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

I had the same problem with third parties scripts like CodeMirror for example and Krpano, and even using safeApply methods mentioned here haven't solved the error for me.

But what do has solved it is using $timeout service (don't forget to inject it first).

Thus, something like:

$timeout(function() {
  // run my code safely here
})

and if inside your code you are using

this

perhaps because it's inside a factory directive's controller or just need some kind of binding, then you would do something like:

.factory('myClass', [
  '$timeout',
  function($timeout) {

    var myClass = function() {};

    myClass.prototype.surprise = function() {
      // Do something suprising! :D
    };

    myClass.prototype.beAmazing = function() {
      // Here 'this' referes to the current instance of myClass

      $timeout(angular.bind(this, function() {
          // Run my code safely here and this is not undefined but
          // the same as outside of this anonymous function
          this.surprise();
       }));
    }

    return new myClass();

  }]
)

Assign JavaScript variable to Java Variable in JSP

you cant do it.. because jsp is compiled and converted into html server side whereas javascript is executed on client side. you may set the value to a hidden html element and send to servlet in request just in case you want to use for further

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

File path to resource in our war/WEB-INF folder?

There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:

ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource methods.

ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");

or alternatively if you just want the input stream:

InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getResource(java.lang.String)

The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.

EDIT: The getContext() method is obviously something you would have to implement. JSP pages make it available as the context field. In a servlet you get it from your ServletConfig which is passed into the servlet's init() method. If you store it at that time, you can get your ServletContext any time you want after that.

How to read a file in reverse order?

for line in reversed(open("file").readlines()):
    print line.rstrip()

If you are on linux, you can use tac command.

$ tac file

2 recipes you can find in ActiveState here and here

Right HTTP status code to wrong input

We had the same problem when making our API as well. We were looking for an HTTP status code equivalent to an InvalidArgumentException. After reading the source article below, we ended up using 422 Unprocessable Entity which states:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

source: https://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm

How to concatenate strings in windows batch file for loop?

In batch you could do it like this:

@echo off

setlocal EnableDelayedExpansion

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do (
  set "var=%%sxyz"
  svn co "!var!"
)

If you don't need the variable !var! elsewhere in the loop, you could simplify that to

@echo off

setlocal

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do svn co "%%sxyz"

However, like C.B. I'd prefer PowerShell if at all possible:

$string_list = 'str1', 'str2', 'str3', ... 'str10'

$string_list | ForEach-Object {
  $var = "${_}xyz"   # alternatively: $var = $_ + 'xyz'
  svn co $var
}

Again, this could be simplified if you don't need $var elsewhere in the loop:

$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }

Django URL Redirect

Another way of doing it is using HttpResponsePermanentRedirect like so:

In view.py

def url_redirect(request):
    return HttpResponsePermanentRedirect("/new_url/")

In the url.py

url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),

How to parse XML in Bash?

While it seems like "never parse XML, JSON... from bash without a proper tool" is sound advice, I disagree. If this is side job, it is waistfull to look for the proper tool, then learn it... Awk can do it in minutes. My programs have to work on all above mentioned and more kinds of data. Hell, I do not want to test 30 tools to parse 5-7-10 different formats I need if I can awk the problem in minutes. I do not care about XML, JSON or whatever! I need a single solution for all of them.

As an example: my SmartHome program runs our homes. While doing it, it reads plethora of data in too many different formats I can not control. I never use dedicated, proper tools since I do not want to spend more than minutes on reading the data I need. With FS and RS adjustments, this awk solution works perfectly for any textual format. But, it may not be the proper answer when your primary task is to work primarily with loads of data in that format!

The problem of parsing XML from bash I faced yesterday. Here is how I do it for any hierarchical data format. As a bonus - I assign data directly to the variables in a bash script.

To make thins easier to read, I will present solution in stages. From the OP test data, I created a file: test.xml

Parsing said XML in bash and extracting the data in 90 chars:

awk 'BEGIN { FS="<|>"; RS="\n" }; /host|username|password|dbname/ { print $2, $4 }' test.xml

I normally use more readable version since it is easier to modify in real life as I often need to test differently:

awk 'BEGIN { FS="<|>"; RS="\n" }; { if ($0 ~ /host|username|password|dbname/) print $2,$4}' test.xml

I do not care how is the format called. I seek only the simplest solution. In this particular case, I can see from the data that newline is the record separator (RS) and <> delimit fields (FS). In my original case, I had complicated indexing of 6 values within two records, relating them, find when the data exists plus fields (records) may or may not exist. It took 4 lines of awk to solve the problem perfectly. So, adapt idea to each need before using it!

Second part simply looks it there is wanted string in a line (RS) and if so, prints out needed fields (FS). The above took me about 30 seconds to copy and adapt from the last command I used this way (4 times longer). And that is it! Done in 90 chars.

But, I always need to get the data neatly into variables in my script. I first test the constructs like so:

awk 'BEGIN { FS="<|>"; RS="\n" }; { if ($0 ~ /host|username|password|dbname/) print $2"=\""$4"\"" }' test.xml

In some cases I use printf instead of print. When I see everything looks well, I simply finish assigning values to variables. I know many think "eval" is "evil", no need to comment :) Trick works perfectly on all four of my networks for years. But keep learning if you do not understand why this may be bad practice! Including bash variable assignments and ample spacing, my solution needs 120 chars to do everything.

eval $( awk 'BEGIN { FS="<|>"; RS="\n" }; { if ($0 ~ /host|username|password|dbname/) print $2"=\""$4"\"" }' test.xml ); echo "host: $host, username: $username, password: $password dbname: $dbname"

Create code first, many to many, with additional fields in association table

It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class MemberComment
{
    [Key, Column(Order = 0)]
    public int MemberID { get; set; }
    [Key, Column(Order = 1)]
    public int CommentID { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }

    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

... or ...

var commentsOfMembers = context.MemberComments
    .Where(mc => mc.Member.LastName == "Smith")
    .Select(mc => mc.Comment)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

If you want to find all comments of a member with MemberId = 1:

var commentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1)
    .Select(mc => mc.Comment)
    .ToList();

Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something:

var filteredCommentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1 && mc.Something == 99)
    .Select(mc => mc.Comment)
    .ToList();

Because of lazy loading things might become easier. If you have a loaded Member you should be able to get the comments without an explicit query:

var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);

I guess that lazy loading will fetch the comments automatically behind the scenes.

Edit

Just for fun a few examples more how to add entities and relationships and how to delete them in this model:

1) Create one member and two comments of this member:

var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
                                         Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
                                         Something = 102 };

context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2

context.SaveChanges();

2) Add a third comment of member1:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    var comment3 = new Comment { Message = "Good night!" };
    var memberComment3 = new MemberComment { Member = member1,
                                             Comment = comment3,
                                             Something = 103 };

    context.MemberComments.Add(memberComment3); // will also add comment3
    context.SaveChanges();
}

3) Create new member and relate it to the existing comment2:

var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
    .SingleOrDefault();
if (comment2 != null)
{
    var member2 = new Member { FirstName = "Paul" };
    var memberComment4 = new MemberComment { Member = member2,
                                             Comment = comment2,
                                             Something = 201 };

    context.MemberComments.Add(memberComment4);
    context.SaveChanges();
}

4) Create relationship between existing member2 and comment3:

var member2 = context.Members.Where(m => m.FirstName == "Paul")
    .SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
    .SingleOrDefault();
if (member2 != null && comment3 != null)
{
    var memberComment5 = new MemberComment { Member = member2,
                                             Comment = comment3,
                                             Something = 202 };

    context.MemberComments.Add(memberComment5);
    context.SaveChanges();
}

5) Delete this relationship again:

var memberComment5 = context.MemberComments
    .Where(mc => mc.Member.FirstName == "Paul"
        && mc.Comment.Message == "Good night!")
    .SingleOrDefault();
if (memberComment5 != null)
{
    context.MemberComments.Remove(memberComment5);
    context.SaveChanges();
}

6) Delete member1 and all its relationships to the comments:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    context.Members.Remove(member1);
    context.SaveChanges();
}

This deletes the relationships in MemberComments too because the one-to-many relationships between Member and MemberComments and between Comment and MemberComments are setup with cascading delete by convention. And this is the case because MemberId and CommentId in MemberComment are detected as foreign key properties for the Member and Comment navigation properties and since the FK properties are of type non-nullable int the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.

Show Curl POST Request Headers? Is there a way to do this?

Here is all you need:

curl_setopt($curlHandle, CURLINFO_HEADER_OUT, true); // enable tracking
... // do curl request    
$headerSent = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT ); // request headers

Counting unique values in a column in pandas dataframe like in Qlik?

Count distinct values, use nunique:

df['hID'].nunique()
5

Count only non-null values, use count:

df['hID'].count()
8

Count total values including null values, use the size attribute:

df['hID'].size
8

Edit to add condition

Use boolean indexing:

df.loc[df['mID']=='A','hID'].agg(['nunique','count','size'])

OR using query:

df.query('mID == "A"')['hID'].agg(['nunique','count','size'])

Output:

nunique    5
count      5
size       5
Name: hID, dtype: int64

How to find the array index with a value?

Here is my take on it, seems like most peoples solutions don't check if the item exists and it removes random values if it does not exist.

First check if the element exists by looking for it's index. If it does exist, remove it by its index using the splice method

elementPosition = array.indexOf(value);

if(elementPosition != -1) {
  array.splice(elementPosition, 1);
}

Why does ENOENT mean "No such file or directory"?

It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE would have been too narrow in its meaning.