Programs & Examples On #Html.actionlink

ActionLink htmlAttributes

@Html.ActionLink("display name", "action", "Contorller"
    new { id = 1 },Html Attribute=new {Attribute1="value"})

Passing parameter to controller action from a Html.ActionLink

Addition to the accepted answer:

if you are going to use

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)

this will create actionlink where you can't create new custom attribute or style for the link.

However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })

How do I set default terminal to terminator?

The only way that worked for me was

  1. Open nautilus or nemo as root user gksudo nautilus
  2. Go to /usr/bin
  3. Change name of your default terminal to any other name for exemple "orig_gnome-terminal"
  4. rename your favorite terminal as "gnome-terminal"

Check if MySQL table exists or not

You can try this

$query = mysql_query("SELECT * FROM $this_table") or die (mysql_error());

or this

$query = mysql_query("SELECT * FROM $this_table") or die ("Table does not exists!");

or this

$query = mysql_query("SELECT * FROM $this_table");

if(!$query)
   echo "The ".$this_table." does not exists";

Hope it helps!

Swift days between two NSDates

I translated my Objective-C answer

let start = "2010-09-01"
let end = "2010-09-05"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let startDate:NSDate = dateFormatter.dateFromString(start)
let endDate:NSDate = dateFormatter.dateFromString(end)

let cal = NSCalendar.currentCalendar()


let unit:NSCalendarUnit = .Day

let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: nil)


println(components)

result

<NSDateComponents: 0x10280a8a0>
     Day: 4

The hardest part was that the autocompletion insists fromDate and toDate would be NSDate?, but indeed they must be NSDate! as shown in the reference.

I don't see how a good solution with an operator would look like, as you want to specify the unit differently in each case. You could return the time interval, but than won't you gain much.

Pandas "Can only compare identically-labeled DataFrame objects" error

At the time when this question was asked there wasn't another function in Pandas to test equality, but it has been added a while ago: pandas.equals

You use it like this:

df1.equals(df2)

Some differenes to == are:

  • You don't get the error described in the question
  • It returns a simple boolean.
  • NaN values in the same location are considered equal
  • 2 DataFrames need to have the same dtype to be considered equal, see this stackoverflow question

Spring RequestMapping for controllers that produce and consume JSON

You can use the @RestController instead of @Controller annotation.

Fatal error: Namespace declaration statement has to be the very first statement in the script in

I fix it this way when I started doesn't matter utf8 just this way open <?php in the first line in the editor in my case sublime text and the namespace writte in the second line

2 <?php namespace mynamespace; //you should writte youe namespace down where you open php here should be in line 3 here I make the error cuz I started open from line 2 <?php

1 <?php namespace mynamespace; // I started from line 1 <?php it WORK

nginx: connect() failed (111: Connection refused) while connecting to upstream

I don't think that solution would work anyways because you will see some error message in your error log file.

The solution was a lot easier than what I thought.

simply, open the following path to your php5-fpm

sudo nano /etc/php5/fpm/pool.d/www.conf

or if you're the admin 'root'

nano /etc/php5/fpm/pool.d/www.conf

Then find this line and uncomment it:

listen.allowed_clients = 127.0.0.1

This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks

like this: fastcgi_pass 127.0.0.1:9000;

after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm

Php5-fpm

sudo service php5-fpm restart

or

sudo service php5-fpm reload

Nginx

sudo service nginx restart

or

sudo service nginx reload

From the comments:

Also comment

;listen = /var/run/php5-fpm.sock 

and add

listen = 9000

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.

Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.

Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.

The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.

 &obj; //  valid
 &12;  //invalid

Disabling the button after once click

Use modern Js events, with "once"!

const button = document.getElementById(btnId);
button.addEventListener("click", function() {
    // Submit form
}, {once : true});

// Disabling works too, but this is a more standard approach for general one-time events

Documentation, CanIUse

How to set JAVA_HOME in Mac permanently?

You can use /usr/libexec/java_home -v <version you want> to get the path you need for JAVA_HOME. For instance, to get the path to the 1.7 JDK you can run /usr/libexec/java_home -v 1.7 and it will return the path to the JDK. In your .profile or .bash_profile just add

export JAVA_HOME=`/usr/libexec/java_home -v <version>`

and you should be good. Alternatively, try and convince the maintainers of java tools you use to make use of this method to get the version they need.

To open '.bash_profile' type the following in terminal :

nano ~/.bash_profile 

and add the following line to the file:

export JAVA_HOME=`/usr/libexec/java_home -v <version>`

Press CTRL+X to exit the bash. Press 'Y' to save changes.

To check whether the path has been added, type following in terminal:

source ~/.bash_profile
echo $JAVA_HOME

How to delete rows from a pandas DataFrame based on a conditional expression

In pandas you can do str.len with your boundary and using the Boolean result to filter it .

df[df['column name'].str.len().lt(2)]

Suppress warning messages using mysql from within Terminal, but password written in bash script

One method that is convenient (but equally insecure) is to use:

MYSQL_PWD=xxxxxxxx mysql -u root -e "statement"

Note that the official docs recommend against it.
See 6.1.2.1 End-User Guidelines for Password Security (Mysql Manual for Version 5.6):

Storing your password in the MYSQL_PWD environment variable

This method of specifying your MySQL password must be considered extremely insecure and should not be used. Some versions of ps include an option to display the environment of running processes. On some systems, if you set MYSQL_PWD, your password is exposed to any other user who runs ps. Even on systems without such a version of ps, it is unwise to assume that there are no other methods by which users can examine process environments.

Bootstrap Responsive Text Size

Well, my solution is sort of hack, but it works and I am using it.

1vw = 1% of viewport width

1vh = 1% of viewport height

1vmin = 1vw or 1vh, whichever is smaller

1vmax = 1vw or 1vh, whichever is larger

h1 {
  font-size: 5.9vw;
}
h2 {
  font-size: 3.0vh;
}
p {
  font-size: 2vmin;
}

Using CSS to insert text

It is, but requires a CSS2 capable browser (all major browsers, IE8+).

.OwnerJoe:before {
  content: "Joe's Task:";
}

But I would rather recommend using Javascript for this. With jQuery:

$('.OwnerJoe').each(function() {
  $(this).before($('<span>').text("Joe's Task: "));
});

Correct way to load a Nib for a UIView subclass

In Swift:

For example, name of your custom class is InfoView

At first, you create files InfoView.xib and InfoView.swiftlike this:

import Foundation
import UIKit

class InfoView: UIView {
    class func instanceFromNib() -> UIView {
    return UINib(nibName: "InfoView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
}

Then set File's Owner to UIViewController like this:

enter image description here

Rename your View to InfoView:

enter image description here

Right-click to File's Owner and connect your view field with your InfoView:

enter image description here

Make sure that class name is InfoView:

enter image description here

And after this you can add the action to button in your custom class without any problem:

enter image description here

And usage of this custom class in your MainViewController:

func someMethod() {
    var v = InfoView.instanceFromNib()
    v.frame = self.view.bounds
    self.view.addSubview(v)
}

pandas unique values multiple columns

In [5]: set(df.Col1).union(set(df.Col2))
Out[5]: {'Bill', 'Bob', 'Joe', 'Mary', 'Steve'}

Or:

set(df.Col1) | set(df.Col2)

Single statement across multiple lines in VB.NET without the underscore character

For most multiline strings using an XML element with an inner CDATA block is easier to avoid having to escape anything for simple raw string data.

Dim s as string = <s><![CDATA[Line 1
line 2
line 3]]></s>.Value

Note that I've seen many people state the same format but without the wrapping "< s >" tag (just the CDATA block) but visual studio Automatic formatting seams to alter the leading whitespace of each line then. I think this is due to the object inheritance structure behind the Linq "X" objects. CDATA is not a "Container", the outer block is an XElement which inherits from XContainer.

use current date as default value for a column

To use the current date as the default for a date column, you will need to:

1- open table designer

2- select the column

3- go to column proprerties

4- set the value of Default value or binding propriete To (getdate())

enter image description here

How can I get the baseurl of site?

This is a much more fool proof method.

VirtualPathUtility.ToAbsolute("~/");

How to create an empty array in Swift?

Swift 5

// Create an empty array
var emptyArray = [String]()

// Add values to array by appending (Adds values as the last element)
emptyArray.append("Apple")
emptyArray.append("Oppo")

// Add values to array by inserting (Adds to a specified position of the list)
emptyArray.insert("Samsung", at: 0)

// Remove elements from an array by index number
emptyArray.remove(at: 2)

// Remove elements by specifying the element
if let removeElement = emptyArray.firstIndex(of: "Samsung") {
    emptyArray.remove(at: removeElement)
}

A similar answer is given but that doesn't work for the latest version of Swift (Swift 5), so here is the updated answer. Hope it helps! :)

commons httpclient - Adding query string parameters to GET/POST request

The HttpParams interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient object.

If you want to pass query string parameters, you need to assemble them on the URL yourself, e.g.

new HttpGet(url + "key1=" + value1 + ...);

Remember to encode the values first (using URLEncoder).

Script not served by static file handler on IIS7.5

Maybe too late now, but more often than not you need to run

aspnet_regiis.exe -i  

after installing asp.net. Maybe I would do it anyway now.

Copy table from one database to another

INSERT INTO ProductPurchaseOrderItems_bkp
      (
       [OrderId],
       [ProductId],
       [Quantity],
       [Price]
      )
SELECT 
       [OrderId],
       [ProductId],
       [Quantity],
       [Price] 
FROM ProductPurchaseOrderItems 
   WHERE OrderId=415

Drawing circles with System.Drawing

You should use DrawEllipse:

//
// Summary:
//     Draws an ellipse defined by a bounding rectangle specified by coordinates
//     for the upper-left corner of the rectangle, a height, and a width.
//
// Parameters:
//   pen:
//     System.Drawing.Pen that determines the color, width,
//      and style of the ellipse.
//
//   x:
//     The x-coordinate of the upper-left corner of the bounding rectangle that
//     defines the ellipse.
//
//   y:
//     The y-coordinate of the upper-left corner of the bounding rectangle that
//     defines the ellipse.
//
//   width:
//     Width of the bounding rectangle that defines the ellipse.
//
//   height:
//     Height of the bounding rectangle that defines the ellipse.
//
// Exceptions:
//   System.ArgumentNullException:
//     pen is null.
public void DrawEllipse(Pen pen, int x, int y, int width, int height);

Connecting to MySQL from Android with JDBC

public void testDB() {
        TextView tv = (TextView) this.findViewById(R.id.tv_data);
        try {

            Class.forName("com.mysql.jdbc.Driver");

            // perfect

            // localhost

            /*
             * Connection con = DriverManager .getConnection(
             * "jdbc:mysql://192.168.1.5:3306/databasename?user=root&password=123"
             * );
             */

            // online testing

            Connection con = DriverManager
                    .getConnection("jdbc:mysql://173.5.128.104:3306/vokyak_heyou?user=viowryk_hiweser&password=123");

            String result = "Database connection success\n";
            Statement st = con.createStatement();

            ResultSet rs = st.executeQuery("select * from tablename ");
            ResultSetMetaData rsmd = rs.getMetaData();

            while (rs.next()) {

                result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";

            }
            tv.setText(result);
        } catch (Exception e) {
            e.printStackTrace();
            tv.setText(e.toString());
        }

    }

Is optimisation level -O3 dangerous in g++?

Yes, O3 is buggier. I'm a compiler developer and I've identified clear and obvious gcc bugs caused by O3 generating buggy SIMD assembly instructions when building my own software. From what I've seen, most production software ships with O2 which means O3 will get less attention wrt testing and bug fixes.

Think of it this way: O3 adds more transformations on top of O2, which adds more transformations on top of O1. Statistically speaking, more transformations means more bugs. That's true for any compiler.

Make index.html default, but allow index.php to be visited if typed in

I agree with @TheAlpha's accepted answer, Apache reads the DirectoryIndex target files from left to right , if the first file exists ,apche serves it and if it doesnt then the next file is served as an index for the directory. So if you have the following Directive :

DirectoryIndex file1.html file2.html

Apache will serve /file.html as index ,You will need to change the order of files if you want to set /file2.html as index

DirectoryIndex file2.html file1.html

You can also set index file using a RewriteRule

RewriteEngine on

RewriteRule ^$ /index.html [L]

RewriteRule above will rewrite your homepage to /index.html the rewriting happens internally so http://example.com/ would show you the contents ofindex.html .

Declaring array of objects

Use array.push() to add an item to the end of the array.

var sample = new Array();
sample.push(new Object());

you can use it

var x = 100;
var sample = [];
for(let i=0; i<x ;i++){
  sample.push({}) 
  OR
  sample.push(new Object())
}    

'sudo gem install' or 'gem install' and gem locations

You can install gems into a specific folder (example vendor/) in your Rails app using :

bundle install --path vendor

_DEBUG vs NDEBUG

The macro NDEBUG controls whether assert() statements are active or not.

In my view, that is separate from any other debugging - so I use something other than NDEBUG to control debugging information in the program. What I use varies, depending on the framework I'm working with; different systems have different enabling macros, and I use whatever is appropriate.

If there is no framework, I'd use a name without a leading underscore; those tend to be reserved to 'the implementation' and I try to avoid problems with name collisions - doubly so when the name is a macro.

Convert hexadecimal string (hex) to a binary string

Integer.parseInt(hex,16);    
System.out.print(Integer.toBinaryString(hex));

Parse hex(String) to integer with base 16 then convert it to Binary String using toBinaryString(int) method

example

int num = (Integer.parseInt("A2B", 16));
System.out.print(Integer.toBinaryString(num));

Will Print

101000101011

Max Hex vakue Handled by int is FFFFFFF

i.e. if FFFFFFF0 is passed ti will give error

List of Java class file format major version numbers?

If you're having some problem about "error compiler of class file", it's possible to resolve this by changing the project's JRE to its correspondent through Eclipse.

  1. Build path
  2. Configure build path
  3. Change library to correspondent of table that friend shows last.
  4. Create "jar file" and compile and execute.

I did that and it worked.

How to Pass Parameters to Activator.CreateInstance<T>()

Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.

There are better alternatives for dynamically creating objects using pre compiled lambda. Of course always performance is subjective and it clearly depends on each case if it's worth it or not.

Details about the issue on this article.

Graph is taken from the article and represents time taken in ms per 1000 calls.

Performance comparison

How to remove origin from git repository

Fairly straightforward:

git remote rm origin

As for the filter-branch question - just add --prune-empty to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:

git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD

Basic communication between two fragments

I recently created a library that uses annotations to generate those type casting boilerplate code for you. https://github.com/zeroarst/callbackfragment

Here is an example. Click a TextView on DialogFragment triggers a callback to MainActivity in onTextClicked then grab the MyFagment instance to interact with.

public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback, MyDialogFragment.DialogListener {

private static final String MY_FRAGM = "MY_FRAGMENT";
private static final String MY_DIALOG_FRAGM = "MY_DIALOG_FRAGMENT";

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

    getSupportFragmentManager().beginTransaction()
        .add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), MY_FRAGM)
        .commit();

    findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyDialogFragmentCallbackable.create().show(getSupportFragmentManager(), MY_DIALOG_FRAGM);
        }
    });
}

Toast mToast;

@Override
public void onClickButton(MyFragment fragment) {
    if (mToast != null)
        mToast.cancel();
    mToast = Toast.makeText(this, "Callback from " + fragment.getTag() + " to " + this.getClass().getSimpleName(), Toast.LENGTH_SHORT);
    mToast.show();
}

@Override
public void onTextClicked(MyDialogFragment fragment) {
    MyFragment myFragm = (MyFragment) getSupportFragmentManager().findFragmentByTag(MY_FRAGM);
    if (myFragm != null) {
        myFragm.updateText("Callback from " + fragment.getTag() + " to " + myFragm.getTag());
    }
}

}

How to capture a JFrame's close button click event?

Try this:

setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

It will work.

Auto-indent in Notepad++

You can use 'Indent by fold' plugin. Install it from the plugin manager. It works fine for me.

How to access custom attributes from event object in React?

event.target gives you the native DOM node, then you need to use the regular DOM APIs to access attributes. Here are docs on how to do that:Using data attributes.

You can do either event.target.dataset.tag or event.target.getAttribute('data-tag'); either one works.

php: how to get associative array key from numeric index?

$array = array( 'one' =>'value', 'two' => 'value2' );
$keys  = array_keys($array);
echo $keys[0]; // one
echo $keys[1]; // two

JavaScript object: access variable property by name as string

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

This is equal to dot notation, var side = columns.right;, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

Android - how to make a scrollable constraintlayout?

For me, none of the suggestions about removing bottom constraints nor setting scroll container to true seemed to work. What worked: expand the height of individual/nested views in my layout so they "spanned" beyond the parent by using the "Expand Vertically" option of the Constraint Layout Editor as shown below.

For any approach, it is important that the dotted preview lines extend vertically beyond the parent's top or bottom dimensions

Expand Vertically

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

Error importing SQL dump into MySQL: Unknown database / Can't create database

If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE command to CREATE DATABASE IF NOT EXISTS in line22

Select first 4 rows of a data.frame in R

Use head:

dnow <- data.frame(x=rnorm(100), y=runif(100))
head(dnow,4) ## default is 6

Inverse dictionary lookup in Python

Since this is still very relevant, the first Google hit and I just spend some time figuring this out, I'll post my (working in Python 3) solution:

testdict = {'one'   : '1',
            'two'   : '2',
            'three' : '3',
            'four'  : '4'
            }

value = '2'

[key for key in testdict.items() if key[1] == value][0][0]

Out[1]: 'two'

It will give you the first value that matches.

iOS 8 UITableView separator inset 0 not working

following answer from @cdstamper, a better place is layoutSubviews of UITableViewCell, in your cell file(I set 1% spacing, you can set to zero), so need only to set code here to handle all situations(rotate and other):

 -(void)layoutSubviews
    {
        [super layoutSubviews];
        if ([self respondsToSelector:@selector(setSeparatorInset:)]) {
            [self setSeparatorInset:UIEdgeInsetsMake(0,self.bounds.size.width*0.01,0,self.bounds.size.width*0.01)];
        }
        if ([self respondsToSelector:@selector(setLayoutMargins:)]) {
            [self setLayoutMargins:UIEdgeInsetsMake(0,self.bounds.size.width*0.01,0,self.bounds.size.width*0.01)];
        }
    }

Add a list item through javascript

If you want to create a li element for each input/name, then you have to create it, with document.createElement [MDN].

Give the list the ID:

<ol id="demo"></ol>

and get a reference to it:

var list = document.getElementById('demo');

In your event handler, create a new list element with the input value as content and append to the list with Node.appendChild [MDN]:

var firstname = document.getElementById('firstname').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);

DEMO

Django Rest Framework File Upload

From my experience, you don't need to do anything particular about file fields, you just tell it to make use of the file field:

from rest_framework import routers, serializers, viewsets

class Photo(django.db.models.Model):
    file = django.db.models.ImageField()

    def __str__(self):
        return self.file.name

class PhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Photo
        fields = ('id', 'file')   # <-- HERE

class PhotoViewSet(viewsets.ModelViewSet):
    queryset = models.Photo.objects.all()
    serializer_class = PhotoSerializer

router = routers.DefaultRouter()
router.register(r'photos', PhotoViewSet)

api_urlpatterns = ([
    url('', include(router.urls)),
], 'api')
urlpatterns += [
    url(r'^api/', include(api_urlpatterns)),
]

and you're ready to upload files:

curl -sS http://example.com/api/photos/ -F 'file=@/path/to/file'

Add -F field=value for each extra field your model has. And don't forget to add authentication.

Procedure or function !!! has too many arguments specified

For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.

Just put use [DBName] on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.

How do you rotate a two dimensional array?

@dagorym: Aw, man. I had been hanging onto this as a good "I'm bored, what can I ponder" puzzle. I came up with my in-place transposition code, but got here to find yours pretty much identical to mine...ah, well. Here it is in Ruby.

require 'pp'
n = 10
a = []
n.times { a << (1..n).to_a }

pp a

0.upto(n/2-1) do |i|
  i.upto(n-i-2) do |j|
    tmp             = a[i][j]
    a[i][j]         = a[n-j-1][i]
    a[n-j-1][i]     = a[n-i-1][n-j-1]
    a[n-i-1][n-j-1] = a[j][n-i-1]
    a[j][n-i-1]     = tmp
  end
end

pp a

Table scroll with HTML and CSS

Table with Fixed Header

_x000D_
_x000D_
<table cellspacing="0" cellpadding="0" border="0" width="325">_x000D_
  <tr>_x000D_
    <td>_x000D_
       <table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
         <tr style="color:white;background-color:grey">_x000D_
            <th>Header 1</th>_x000D_
            <th>Header 2</th>_x000D_
         </tr>_x000D_
       </table>_x000D_
    </td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>_x000D_
       <div style="width:320px; height:80px; overflow:auto;">_x000D_
         <table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
           <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
           <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
              <tr>_x000D_
             <td>new item</td>_x000D_
             <td>new item</td>_x000D_
           </tr>_x000D_
         </table>  _x000D_
       </div>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Result

Demo Image

This is working in all browser

Demo jsfiddle http://jsfiddle.net/nyCKE/6302/

How to log in to phpMyAdmin with WAMP, what is the username and password?

http://localhost/phpmyadmin

Username: root

Password:

(No password set)

cordova Android requirements failed: "Could not find an installed version of Gradle"

macOS

Gradle can be added on the Mac by adding the line below to ~/.bash_profile. If the file doesn't exist, please use touch ~/.bash_profile. This hidden file can be made visible in Finder by using Command + Shift + .

export PATH=${PATH}:/Applications/Android\ Studio.app/Contents/gradle/gradle-4.6/bin/

Use source ~/.bash_profile to load the new path directly into your current terminal session.

How do I connect to my existing Git repository using Visual Studio Code?

Use the Git GUI in the Git plugin.

Clone your online repository with the URL which you have.

After cloning, make changes to the files. When you make changes, you can see the number changes. Commit those changes.

Fetch from the remote (to check if anything is updated while you are working).

If the fetch operation gives you an update about the changes in the remote repository, make a pull operation which will update your copy in Visual Studio Code. Otherwise, do not make a pull operation if there aren't any changes in the remote repository.

Push your changes to the upstream remote repository by making a push operation.

Entity Framework is Too Slow. What are my options?

I have found the answer by @Slauma here very useful for speeding things up. I used the same sort of pattern for both inserts and updates - and performance rocketed.

Http Basic Authentication in Java using HttpClient?

while using Header array

String auth = Base64.getEncoder().encodeToString(("test1:test1").getBytes());
Header[] headers = {
    new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()),
    new BasicHeader("Authorization", "Basic " +auth)
};

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Spring is a light weight and open source framework created by Rod Johnson in 2003. Spring is a complete and a modular framework, Spring framework can be used for all layer implementations for a real time application or spring can be used for the development of particular layer of a real time application.

Struts is an open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourage developers to adopt a model–view–controller (MVC) architecture. It was originally created by Craig McClanahan and donated to the Apache Foundation in May, 2000.

Listed below is the comparison chart of difference between Spring and Strut Framework

enter image description here

Undo git stash pop that results in merge conflict

Luckily git stash pop does not change the stash in the case of a conflict!

So nothing, to worry about, just clean up your code and try it again.

Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop again and you get the same stash, that conflicted before.

Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.

Returning unique_ptr from functions

is there some other clause in the language specification that this exploits?

Yes, see 12.8 §34 and §35:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...] This elision of copy/move operations, called copy elision, is permitted [...] in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type [...]

When the criteria for elision of a copy operation are met and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.


Just wanted to add one more point that returning by value should be the default choice here because a named value in the return statement in the worst case, i.e. without elisions in C++11, C++14 and C++17 is treated as an rvalue. So for example the following function compiles with the -fno-elide-constructors flag

std::unique_ptr<int> get_unique() {
  auto ptr = std::unique_ptr<int>{new int{2}}; // <- 1
  return ptr; // <- 2, moved into the to be returned unique_ptr
}

...

auto int_uptr = get_unique(); // <- 3

With the flag set on compilation there are two moves (1 and 2) happening in this function and then one move later on (3).

How to beautifully update a JPA entity in Spring Data?

In Spring Data you simply define an update query if you have the ID

  @Repository
  public interface CustomerRepository extends JpaRepository<Customer , Long> {

     @Query("update Customer c set c.name = :name WHERE c.id = :customerId")
     void setCustomerName(@Param("customerId") Long id, @Param("name") String name);

  }

Some solutions claim to use Spring data and do JPA oldschool (even in a manner with lost updates) instead.

Check if two unordered lists are equal

What about getting the string representation of the lists and comparing them ?

>>> l1 = ['one', 'two', 'three']
>>> l2 = ['one', 'two', 'three']
>>> l3 = ['one', 'three', 'two']
>>> print str(l1) == str(l2)
True
>>> print str(l1) == str(l3)
False

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I had this problem updating from VS2017 to VS2019

For me the problem was simply solved by deleting the .VC.db file of the project.

View's getWidth() and getHeight() returns 0

I used this solution, which I think is better than onWindowFocusChanged(). If you open a DialogFragment, then rotate the phone, onWindowFocusChanged will be called only when the user closes the dialog):

    yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // Ensure you call it only once :
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            // Here you can get the size :)
        }
    });

Edit : as removeGlobalOnLayoutListener is deprecated, you should now do :

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {

    // Ensure you call it only once :
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
    else {
        yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }

    // Here you can get the size :)
}

In plain English, what does "git reset" do?

TL;DR

git reset resets Staging to the last commit. Use --hard to also reset files in your Working directory to the last commit.

LONGER VERSION

But that's obviously simplistic hence the many rather verbose answers. It made more sense for me to read up on git reset in the context of undoing changes. E.g. see this:

If git revert is a “safe” way to undo changes, you can think of git reset as the dangerous method. When you undo with git reset(and the commits are no longer referenced by any ref or the reflog), there is no way to retrieve the original copy—it is a permanent undo. Care must be taken when using this tool, as it’s one of the only Git commands that has the potential to lose your work.

From https://www.atlassian.com/git/tutorials/undoing-changes/git-reset

and this

On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.

From https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/commit-level-operations

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Limiting floats to two decimal points

The Python tutorial has an appendix called Floating Point Arithmetic: Issues and Limitations. Read it. It explains what is happening and why Python is doing its best. It has even an example that matches yours. Let me quote a bit:

>>> 0.1
0.10000000000000001

you may be tempted to use the round() function to chop it back to the single digit you expect. But that makes no difference:

>>> round(0.1, 1)
0.10000000000000001

The problem is that the binary floating-point value stored for “0.1” was already the best possible binary approximation to 1/10, so trying to round it again can’t make it better: it was already as good as it gets.

Another consequence is that since 0.1 is not exactly 1/10, summing ten values of 0.1 may not yield exactly 1.0, either:

>>> sum = 0.0
>>> for i in range(10):
...     sum += 0.1
...
>>> sum
0.99999999999999989

One alternative and solution to your problems would be using the decimal module.

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

Can't import database through phpmyadmin file size too large

You no need to edit php.ini or any thing. I suggest best thing as Just use MySQL WorkBench.

JUST FOLLOW THE STEPS.

Install MySQL WorkBench 6.0

And In "Navigation panel"(Left side) there is option call 'Data import' under "MANAGEMENT". Click that and [follow steps below]

  1. click Import Self-Contained File and choose your SQL file
  2. Go to My Document and create folder call "dump"[simple].
  3. now you ready to upload file. Click IMPORT Button on down.

Range of values in C Int and Long 32 - 64 bits

No, int in C is not defined to be 32 bits. int and long are not defined to be any specific size at all. The only thing the language guarantees is that sizeof(char)<=sizeof(short)<=sizeof(long).

Theoretically a compiler could make short, char, and long all the same number of bits. I know of some that actually did that for all those types save char.

This is why C now defines types like uint16_t and uint32_t. If you need a specific size, you are supposed to use one of those.

How do I make the scrollbar on a div only visible when necessary?

try

<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>

Eclipse CDT: no rule to make target all

You have 2 cases

  • If you create Makefile by yourself, go to
  1. Select Project->Properties from the menu bar.
  2. Click C/C++ Build on the left in the dialog that comes up.
  3. Disable generate makefile automatically -> Under the Builder Settings tab on the right, check and make sure the "Build location" is correct (That location is where your Makefile)
  • If you don't have Makefile -> You need Eclipse DS-5 to help you create Makefile
  1. Select Project->Properties from the menu bar.
  2. Click C/C++ Build on the left in the dialog that comes up.
  3. Enable generate makefile automatically

I advise you create Makefile by your self

How to throw RuntimeException ("cannot find symbol")

throw new RuntimeException(msg);

You need the new in there. It's creating an instance and throwing it, not calling a method.

Safest way to run BAT file from Powershell script

To run the .bat, and have access to the last exit code, run it as:

 & .\my-app\my-fle.bat

Make a table fill the entire window

Below line helped me to fix the issue of scroll bar for a table; the issue was awkward 2 scroll bars in a page. Below style when applied to table worked fine for me.
<table Style="position: absolute; height: 100%; width: 100%";/>

Fastest way to convert JavaScript NodeList to Array?

The most fast and cross browser is

for(var i=-1,l=nl.length;++i!==l;arr[i]=nl[i]);

As I compared in

http://jsbin.com/oqeda/98/edit

*Thanks @CMS for the idea!

Chromium (Similar to Google Chrome) Firefox Opera

How do you join tables from two different SQL Server instances in one SQL query

The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:

SELECT *
FROM server1table
    INNER JOIN server2.database.dbo.server2table ON .....

Center an item with position: relative

Another option is to create an extra wrapper to center the element vertically.

_x000D_
_x000D_
#container{_x000D_
  border:solid 1px #33aaff;_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
}_x000D_
_x000D_
#helper{_x000D_
  position:relative;_x000D_
  height:50px;_x000D_
  top:50%;_x000D_
  border:dotted 1px #ff55aa;_x000D_
}_x000D_
_x000D_
#centered{_x000D_
  position:relative;_x000D_
  height:50px;_x000D_
  top:-50%;_x000D_
  border:solid 1px #ff55aa;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="helper">_x000D_
    <div id="centered"></div>_x000D_
  </div>_x000D_
<div>
_x000D_
_x000D_
_x000D_

Automatically resize images with browser size using CSS

The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!

<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />

Change the window width and the image scales obligingly.

Maven does not find JUnit tests to run

junitArtifactName might also be the case if the JUnit in use isn't the standard (junit:junit) but for instance...

<dependency>
    <groupId>org.eclipse.orbit</groupId>
    <artifactId>org.junit</artifactId>
    <version>4.11.0</version>
    <type>bundle</type>
    <scope>test</scope>
</dependency>

jQuery: How to get the event object in an event handler function without passing it as an argument?

If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:

Markup:

  <a href="#" id="link1" >click</a>

Javascript:

  $(document).ready(function(){
      $("#link1").click(clickWithEvent);  //Bind the click event to the link
  });
  function clickWithEvent(evt){
     myFunc('p1', 'p2', 'p3');
     function myFunc(p1,p2,p3){  //Defined as local function, but has access to evt
        alert(evt.type);        
     }
  }

Since the event ob

Cross origin requests are only supported for HTTP but it's not cross-domain

I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.

  1. Install express npm install express

  2. Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server

  3. Put something like the following in the server.js file and read about this on the express gihub site:

    var express = require('express');
    var app = express();
    var path = require('path');
    
    // __dirname will use the current path from where you run this file 
    app.use(express.static(__dirname));
    app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
    
    app.listen(8000);
    console.log('Listening on port 8000');
    
  4. After you've saved server.js, you can run the server using:

node server.js

  1. Go to http://localhost:8000/FILENAME and you should see the HTML file you were trying to load

How to get image size (height & width) using JavaScript?

You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below...

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function imgTesting_onload()
{
    alert(this.width + " by " + this.height);
}


imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

In my case, it was InterfaceBuilder. I had copied some Views from another ViewController which messed up the constraints.

In InterfaceBuilder I had the red arrow error on the ViewController.

During execution the app crashed.

How to delete the contents of a folder?

Answer for a limited, specific situation: assuming you want to delete the files while maintainig the subfolders tree, you could use a recursive algorithm:

import os

def recursively_remove_files(f):
    if os.path.isfile(f):
        os.unlink(f)
    elif os.path.isdir(f):
        for fi in os.listdir(f):
            recursively_remove_files(os.path.join(f, fi))

recursively_remove_files(my_directory)

Maybe slightly off-topic, but I think many would find it useful

Does Go have "if x in" construct similar to Python?

Another option is using a map as a set. You use just the keys and having the value be something like a boolean that's always true. Then you can easily check if the map contains the key or not. This is useful if you need the behavior of a set, where if you add a value multiple times it's only in the set once.

Here's a simple example where I add random numbers as keys to a map. If the same number is generated more than once it doesn't matter, it will only appear in the final map once. Then I use a simple if check to see if a key is in the map or not.

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    var MAX int = 10

    m := make(map[int]bool)

    for i := 0; i <= MAX; i++ {
        m[rand.Intn(MAX)] = true
    }

    for i := 0; i <= MAX; i++ {
        if _, ok := m[i]; ok {
            fmt.Printf("%v is in map\n", i)
        } else {
            fmt.Printf("%v is not in map\n", i)
        }
    }
}

Here it is on the go playground

How to execute a shell script from C in Linux?

If you're ok with POSIX, you can also use popen()/pclose()

#include <stdio.h>
#include <stdlib.h>

int main(void) {
/* ls -al | grep '^d' */
  FILE *pp;
  pp = popen("ls -al", "r");
  if (pp != NULL) {
    while (1) {
      char *line;
      char buf[1000];
      line = fgets(buf, sizeof buf, pp);
      if (line == NULL) break;
      if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
    }
    pclose(pp);
  }
  return 0;
}

Responsive Bootstrap Jumbotron Background Image

The simplest way is to set the background-size CSS property to cover:

.jumbotron {
  background-image: url("../img/jumbotron_bg.jpg");
  background-size: cover;
}

Precision String Format Specifier In Swift

Swift2 example: Screen width of iOS device formatting the Float removing the decimal

print(NSString(format: "Screen width = %.0f pixels", CGRectGetWidth(self.view.frame)))

What are callee and caller saved registers?

I'm not really sure if this adds anything but,

Caller saved means that the caller has to save the registers because they will be clobbered in the call and have no choice but to be left in a clobbered state after the call returns (for instance, the return value being in eax for cdecl. It makes no sense for the return value to be restored to the value before the call by the callee, because it is a return value).

Callee saved means that the callee has to save the registers and then restore them at the end of the call because they have the guarantee to the caller of containing the same values after the function returns, and it is possible to restore them, even if they are clobbered at some point during the call.

The issue with the above definition though is that for instance on Wikipedia cdecl, it says eax, ecx and edx are caller saved and rest are callee saved, this suggests that the caller must save all 3 of these registers, when it might not if none of these registers were used by the caller in the first place. In which case caller 'saved' becomes a misnomer, but 'call clobbered' still correctly applies. This is the same with 'the rest' being called callee saved. It implies that all other x86 registers will be saved and restored by the callee when this is not the case if some of the registers are never used in the call anyway. With cdecl, eax:edx may be used to return a 64 bit value. I'm not sure why ecx is also caller saved if needed, but it is.

How to unmerge a Git merge?

You can reset your branch to the state it was in just before the merge if you find the commit it was on then.

One way is to use git reflog, it will list all the HEADs you've had. I find that git reflog --relative-date is very useful as it shows how long ago each change happened.

Once you find that commit just do a git reset --hard <commit id> and your branch will be as it was before.

If you have SourceTree, you can look up the <commit id> there if git reflog is too overwhelming.

How to do Select All(*) in linq to sql

u want select all data from database then u can try this:-

dbclassDataContext dc= new dbclassDataContext()
List<tableName> ObjectName= dc.tableName.ToList();

otherwise You can try this:-

var Registration = from reg in dcdc.GetTable<registration>() select reg;

and method Syntex :-

 var Registration = dc.registration.Select(reg => reg); 

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

Editor issue. When you create new files that not using Angular CLI, make sure you go to File > Save All (VS Code) to let the Editor aware of your new changes. Then run "ng serve --open" again. It solved mine. Hope it helps

Getting text from td cells with jQuery

$(document).ready(function() {
  $('td').on('click', function() {
    var value = $this.text();
  });
});

an htop-like tool to display disk activity in linux

Use collectl which has extensive process I/O monitoring including monitoring threads.

Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html

Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?

How to sort findAll Doctrine's method?

You can sort an existing ArrayCollection using an array iterator.

assuming $collection is your ArrayCollection returned by findAll()

$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
    return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));

This can easily be turned into a function you can put into your repository in order to create findAllOrderBy() method.

Special characters like @ and & in cURL POST data

Double quote (" ") the entire URL .It works.

curl "http://www.mysite.com?name=john&passwd=@31&3*J"

Rounding SQL DateTime to midnight

As @BassamMehanni mentioned, you can cast as DATE in SQL Server 2008 onwards...

SELECT
  *
FROM
  yourTable
WHERE
      dateField >= CAST(GetDate() - 6 AS DATE)
  AND dateField <  CAST(GetDate() + 1 AS DATE)

The second condition can actually be just GetDate(), but I'm showing this format as an example of Less Than DateX to avoid having to cast the dateField to a DATE as well, thus massively improving performance.


If you're on 2005 or under, you can use this...

SELECT
  *
FROM
  yourTable
WHERE
      dateField >= DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()) - 6, 0)
  AND dateField <  DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()) + 1, 0)

Android "elevation" not showing a shadow

Adding background color helped me.

<CalendarView
    android:layout_width="match_parent"
    android:id="@+id/calendarView"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_height="wrap_content"
    android:elevation="5dp"

    android:background="@color/windowBackground"

    />

Convert string with comma to integer

If someone is looking to sub out more than a comma I'm a fan of:

"1,200".chars.grep(/\d/).join.to_i

dunno about performance but, it is more flexible than a gsub, ie:

"1-200".chars.grep(/\d/).join.to_i

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

How to detect if a string contains at least a number?

The simplest method is to use LIKE:

SELECT CASE WHEN 'FDAJLK' LIKE '%[0-9]%' THEN 'True' ELSE 'False' END;  -- False
SELECT CASE WHEN 'FDAJ1K' LIKE '%[0-9]%' THEN 'True' ELSE 'False' END;  -- True

Get Month name from month number

For Abbreviated Month Names : "Aug"

DateTimeFormatInfo.GetAbbreviatedMonthName Method (Int32)

Returns the culture-specific abbreviated name of the specified month based on the culture associated with the current DateTimeFormatInfo object.

string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(8)

For Full Month Names : "August"

DateTimeFormatInfo.GetMonthName Method (Int32)

Returns the culture-specific full name of the specified month based on the culture associated with the current DateTimeFormatInfo object.

string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(8);

SQL join: selecting the last records in a one-to-many relationship

I found this thread as a solution to my problem.

But when I tried them the performance was low. Bellow is my suggestion for better performance.

With MaxDates as (
SELECT  customer_id,
                MAX(date) MaxDate
        FROM    purchase
        GROUP BY customer_id
)

SELECT  c.*, M.*
FROM    customer c INNER JOIN
        MaxDates as M ON c.id = M.customer_id 

Hope this will be helpful.

Variable might not have been initialized error

You declared them, but you didn't initialize them. Initializing them is setting them equal to a value:

int a;        // This is a declaration
a = 0;        // This is an initialization
int b = 1;    // This is a declaration and initialization

You get the error because you haven't initialized the variables, but you increment them (e.g., a++) in the for loop.

Java primitives have default values but as one user commented below

Their default value is zero when declared as class members. Local variables don't have default values

JQuery Calculate Day Difference in 2 date textboxes

Hi, This is my example of calculating the difference between two dates

    <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://code.jquery.com/jquery.min.js"></script>
  <title>JS Bin</title>
</head>
<body>
  <br>
<input class='fromdate' type="date"  />
<input class='todate' type="date" />
<div class='calculated' /><br>
<div class='minim' />  
<input class='todate' type="submit" onclick='showDays()' />

</body>
</html>

This is the function that calculates the difference :

function showDays(){

     var start = $('.fromdate').val();
     var end = $('.todate').val();

     var startDay = new Date(start);
     var endDay = new Date(end);
     var millisecondsPerDay = 1000 * 60 * 60 * 24;

     var millisBetween = endDay.getTime() - startDay.getTime();
     var days = millisBetween / millisecondsPerDay;

      // Round down.
       alert( Math.floor(days));

}

I hope I have helped you

width:auto for <input> fields

As stated in the other answer, width: auto doesn't work due to the width being generated by the input's size attribute, which cannot be set to "auto" or anything similar.

There are a few workarounds you can use to cause it to play nicely with the box model, but nothing fantastic as far as I know.

First you can set the padding in the field using percentages, making sure that the width adds up to 100%, e.g.:

input {
  width: 98%;
  padding: 1%;
}

Another thing you might try is using absolute positioning, with left and right set to 0. Using this markup:

<fieldset>
    <input type="text" />
</fieldset>

And this CSS:

fieldset {
  position: relative;
}

input {
    position: absolute;
    left: 0;
    right: 0;
}

This absolute positioning will cause the input to fill the parent fieldset horizontally, regardless of the input's padding or margin. However a huge downside of this is that you now have to deal with the height of the fieldset, which will be 0 unless you set it. If your inputs are all the same height this will work for you, simply set the fieldset's height to whatever the input's height should be.

Other than this there are some JS solutions, but I don't like applying basic styling with JS.

Search input with an icon Bootstrap 4

Here's a fairly simple way to achieve it by enclosing both the magnifying glass icon and the input field inside a div with relative positioning.

Absolute positioning is applied to the icon, which takes it out of the normal document layout flow. The icon is then positioned inside the input. Left padding is applied to the input so that the user's input appears to the right of the icon.

Note that this example places the magnifying glass icon on the left instead of the right. This is recommended when using <input type="search"> as Chrome adds an X button in the right side of the searchbox. If we placed the icon there it would overlay the X button and look fugly.

Here is the needed Bootstrap markup.

<div class="position-relative">
    <i class="fa fa-search position-absolute"></i>
    <input class="form-control" type="search">
</div>

...and a couple CSS classes for the things which I couldn't do with Bootstrap classes:

i {
    font-size: 1rem;
    color: #333;
    top: .75rem;
    left: .75rem
}

input {
    padding-left: 2.5rem;
}

You may have to fiddle with the values for top, left, and padding-left.

Finding square root without using sqrt function?

There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:

#include <math.h>

double sqrt(double x) {
    if (x <= 0)
        return 0;       // if negative number throw an exception?
    int exp = 0;
    x = frexp(x, &exp); // extract binary exponent from x
    if (exp & 1) {      // we want exponent to be even
        exp--;
        x *= 2;
    }
    double y = (1+x)/2; // first approximation
    double z = 0;
    while (y != z) {    // yes, we CAN compare doubles here!
        z = y;
        y = (y + x/y) / 2;
    }
    return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}

Algorithm starts with 1 as first approximation for square root value. Then, on each step, it improves next approximation by taking average between current value y and x/y. If y = sqrt(x), it will be the same. If y > sqrt(x), then x/y < sqrt(x) by about the same amount. In other words, it will converge very fast.

UPDATE: To speed up convergence on very large or very small numbers, changed sqrt() function to extract binary exponent and compute square root from number in [1, 4) range. It now needs frexp() from <math.h> to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp().

Why is SQL Server 2008 Management Studio Intellisense not working?

I tried all the fixes - taking databases offline and then bringing them online, installed Cumulative update 10, repaired SQL Server Installation, refreshed local cache, made changes to the required settings on SQL Server Management Studio but everything was in vain. Finally installing the correct service pack (SP1) did the trick for me !

Follow the link below, and download SQLServer2008R2SP1-KB2528583-x86-ENU.exe (or the x64 file for a x64 bit instance of SQL Server)

http://www.microsoft.com/download/en/details.aspx?id=26727

Finally i have Intellisense enabled !

embedding image in html email

I know this is an old post, but the current answers dont address the fact that outlook and many other email providers dont support inline images or CID images. The most effective way to place images in emails is to host it online and place a link to it in the email. For small email lists a public dropbox works fine. This also keeps the email size down.

C - function inside struct

This will only work in C++. Functions in structs are not a feature of C.

Same goes for your client.AddClient(); call ... this is a call for a member function, which is object oriented programming, i.e. C++.

Convert your source to a .cpp file and make sure you are compiling accordingly.

If you need to stick to C, the code below is (sort of) the equivalent:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;

};


pno AddClient(pno *pclient) 
{
    /* code */
}


int main()
{

    client_t client;

    //code ..

    AddClient(client);

}

multiple conditions for filter in spark data frames

Instead of:

df2 = df1.filter("Status=2" || "Status =3")

Try:

df2 = df1.filter($"Status" === 2 || $"Status" === 3)

Trigger to fire only if a condition is met in SQL Server

The _ character is also a wildcard, BTW, but I'm not sure why this wasn't working for you:

CREATE TRIGGER 
    [dbo].[SystemParameterInsertUpdate]
ON 
    [dbo].[SystemParameter]
FOR INSERT, UPDATE 
AS
  BEGIN
    SET NOCOUNT ON
      INSERT INTO SystemParameterHistory 
      (
        Attribute,
        ParameterValue,
        ParameterDescription,
        ChangeDate
      )
    SELECT
      I.Attribute,
      I.ParameterValue,
      I.ParameterDescription,
      I.ChangeDate
    FROM Inserted AS I
    WHERE I.Attribute NOT LIKE 'NoHist[_]%'
END

What's the "average" requests per second for a production web application?

When I go to the control panel of my webhost, open up phpMyAdmin, and click on "Show MySQL runtime information", I get:

This MySQL server has been running for 53 days, 15 hours, 28 minutes and 53 seconds. It started up on Oct 24, 2008 at 04:03 AM.

Query statistics: Since its startup, 3,444,378,344 queries have been sent to the server.

Total 3,444 M
per hour 2.68 M
per minute 44.59 k
per second 743.13

That's an average of 743 mySQL queries every single second for the past 53 days!

I don't know about you, but to me that's fast! Very fast!!

What order are the Junit @Before/@After called?

I think based on the documentation of the @Before and @After the right conclusion is to give the methods unique names. I use the following pattern in my tests:

public abstract class AbstractBaseTest {

  @Before
  public final void baseSetUp() { // or any other meaningful name
    System.out.println("AbstractBaseTest.setUp");
  }

  @After
  public final void baseTearDown() { // or any other meaningful name
    System.out.println("AbstractBaseTest.tearDown");
  }
}

and

public class Test extends AbstractBaseTest {

  @Before
  public void setUp() {
    System.out.println("Test.setUp");
  }

  @After
  public void tearDown() {
    System.out.println("Test.tearDown");
  }

  @Test
  public void test1() throws Exception {
    System.out.println("test1");
  }

  @Test
  public void test2() throws Exception {
    System.out.println("test2");
  }
}

give as a result

AbstractBaseTest.setUp
Test.setUp
test1
Test.tearDown
AbstractBaseTest.tearDown
AbstractBaseTest.setUp
Test.setUp
test2
Test.tearDown
AbstractBaseTest.tearDown

Advantage of this approach: Users of the AbstractBaseTest class cannot override the setUp/tearDown methods by accident. If they want to, they need to know the exact name and can do it.

(Minor) disadvantage of this approach: Users cannot see that there are things happening before or after their setUp/tearDown. They need to know that these things are provided by the abstract class. But I assume that's the reason why they use the abstract class

How do I check if an element is hidden in jQuery?

if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
    // 'element' is hidden
}

The above method does not consider the visibility of the parent. To consider the parent as well, you should use .is(":hidden") or .is(":visible").

For example,

<div id="div1" style="display:none">
  <div id="div2" style="display:block">Div2</div>
</div>

The above method will consider div2 visible while :visible not. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions :visible will not work.

Use .corr to get the correlation between two columns

My solution would be after converting data to numerical type:

Top15[['Citable docs per Capita','Energy Supply per Capita']].corr()

How can I read an input string of unknown length?

If I may suggest a safer approach:

Declare a buffer big enough to hold the string:

char user_input[255];

Get the user input in a safe way:

fgets(user_input, 255, stdin);

A safe way to get the input, the first argument being a pointer to a buffer where the input will be stored, the second the maximum input the function should read and the third is a pointer to the standard input - i.e. where the user input comes from.

Safety in particular comes from the second argument limiting how much will be read which prevents buffer overruns. Also, fgets takes care of null-terminating the processed string.

More info on that function here.

EDIT: If you need to do any formatting (e.g. convert a string to a number), you can use atoi once you have the input.

How do I run a shell script without using "sh" or "bash" commands?

Just make sure it is executable, using chmod +x. By default, the current directory is not on your PATH, so you will need to execute it as ./script.sh - or otherwise reference it by a qualified path. Alternatively, if you truly need just script.sh, you would need to add it to your PATH. (You may not have access to modify the system path, but you can almost certainly modify the PATH of your own current environment.) This also assumes that your script starts with something like #!/bin/sh.

You could also still use an alias, which is not really related to shell scripting but just the shell, and is simple as:

alias script.sh='sh script.sh'

Which would allow you to use just simply script.sh (literally - this won't work for any other *.sh file) instead of sh script.sh.

Can I use tcpdump to get HTTP requests, response header and response body?

I would recommend using Wireshark, which has a "Follow TCP Stream" option that makes it very easy to see the full requests and responses for a particular TCP connection. If you would prefer to use the command line, you can try tcpflow, a tool dedicated to capturing and reconstructing the contents of TCP streams.

Other options would be using an HTTP debugging proxy, like Charles or Fiddler as EricLaw suggests. These have the advantage of having specific support for HTTP to make it easier to deal with various sorts of encodings, and other features like saving requests to replay them or editing requests.

You could also use a tool like Firebug (Firefox), Web Inspector (Safari, Chrome, and other WebKit-based browsers), or Opera Dragonfly, all of which provide some ability to view the request and response headers and bodies (though most of them don't allow you to see the exact byte stream, but instead how the browsers parsed the requests).

And finally, you can always construct requests by hand, using something like telnet, netcat, or socat to connect to port 80 and type the request in manually, or a tool like htty to help easily construct a request and inspect the response.

How do I concatenate two strings in C?

C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.

Use strcat to concatenate two strings. You could use the following function to do it:

#include <stdlib.h>
#include <string.h>

char* concat(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.

Call the function like this:

char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string

If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
    return result;
}

If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

As all of the other answers have already said, it's part of ES2015 arrow function syntax. More specifically, it's not an operator, it's a punctuator token that separates the parameters from the body: ArrowFunction : ArrowParameters => ConciseBody. E.g. (params) => { /* body */ }.

Unable to resolve host "<URL here>" No address associated with host name

I Had the same problem, and it was because the simulator somehow got in airplane mode, once this was disabled my App worked fine :-) I had tried everything, rebuild, clean+build and reboot android studio and reboot the computer, even reinstalling android studio..

Initializing multiple variables to the same value in Java

Works for primitives and immutable classes like String, Wrapper classes Character, Byte.

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

For mutable classes

Reference r1 = Reference r2 = Reference r3 = new Object();`  

Three references + one object are created. All references point to the same object and your program will misbehave.

How can I convert a dictionary into a list of tuples?

A simpler one would be

list(dictionary.items())  # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys()))  # list of (key, value) tuples

Random word generator- Python

There is a package random_word could implement this request very conveniently:

 $ pip install random-word

from random_word import RandomWords
r = RandomWords()

# Return a single random word
r.get_random_word()
# Return list of Random words
r.get_random_words()
# Return Word of the day
r.word_of_the_day()

Appending a list or series to a pandas DataFrame as a row?

If you want to add a Series and use the Series' index as columns of the DataFrame, you only need to append the Series between brackets:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame()

In [3]: row=pd.Series([1,2,3],["A","B","C"])

In [4]: row
Out[4]: 
A    1
B    2
C    3
dtype: int64

In [5]: df.append([row],ignore_index=True)
Out[5]: 
   A  B  C
0  1  2  3

[1 rows x 3 columns]

Whitout the ignore_index=True you don't get proper index.

How can I get form data with JavaScript/jQuery?

You can also use the FormData Objects; The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.

        var formElement = document.getElementById("myform_id");
        var formData = new FormData(formElement);
        console.log(formData);

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

PYTHON 3

import urllib.request

wp = urllib.request.urlopen("http://example.com")

pw = wp.read()

print(pw)

PYTHON 2

import urllib

 import sys

 wp = urllib.urlopen("http://example.com")

 for line in wp:

     sys.stdout.write(line)

While I have tested both the Codes in respective versions.

Getting DOM elements by classname

There is also another approach without the use of DomXPath or Zend_Dom_Query.

Based on dav's original function, I wrote the following function that returns all the children of the parent node whose tag and class match the parameters.

function getElementsByClass(&$parentNode, $tagName, $className) {
    $nodes=array();

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            $nodes[]=$temp;
        }
    }

    return $nodes;
}

suppose you have a variable $html the following HTML:

<html>
 <body>
  <div id="content_node">
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>    
  </div>
  <div id="footer_node">
    <p class="a">I am in the footer node.</p>
  </div>
 </body>
</html>

use of getElementsByClass is as simple as:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$content_node=$dom->getElementById("content_node");

$div_a_class_nodes=getElementsByClass($content_node, 'div', 'a');//will contain the three nodes under "content_node".

Output of git branch in tree like fashion

It's not quite what you asked for, but

git log --graph --simplify-by-decoration --pretty=format:'%d' --all

does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration is the big trick here for limiting the refs shown.

I use a similar command to view my log. I've been able to completely replace my gitk usage with it:

git log --graph --oneline --decorate --all

I use it by including these aliases in my ~/.gitconfig file:

[alias]
    l = log --graph --oneline --decorate
    ll = log --graph --oneline --decorate --branches --tags
    lll = log --graph --oneline --decorate --all

Edit: Updated suggested log command/aliases to use simpler option flags.

jQuery scroll to element

If you are not much interested in the smooth scroll effect and just interested in scrolling to a particular element, you don't require some jQuery function for this. Javascript has got your case covered:

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

So all you need to do is: $("selector").get(0).scrollIntoView();

.get(0) is used because we want to retrieve the JavaScript's DOM element and not the JQuery's DOM element.

Deleting all files from a folder using PHP?

For me, the solution with readdir was best and worked like a charm. With glob, the function was failing with some scenarios.

// Remove a directory recursively
function removeDirectory($dirPath) {
    if (! is_dir($dirPath)) {
        return false;
    }

    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }

    if ($handle = opendir($dirPath)) {

        while (false !== ($sub = readdir($handle))) {
            if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
                $file = $dirPath . $sub;

                if (is_dir($file)) {
                    removeDirectory($file);
                } else {
                    unlink($file);
                }
            }
        }

        closedir($handle);
    }

    rmdir($dirPath);
}

How do I run a program from command prompt as a different user and as an admin

See here: https://superuser.com/questions/42537/is-there-any-sudo-command-for-windows

According to that the command looks like this for admin:

 runas /noprofile /user:Administrator cmd

Convert character to ASCII numeric value in java

You can check the ASCII´s number with this code.

String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97

If I am wrong, apologies.

Example of waitpid() in use?

The syntax is

pid_t waitpid(pid_t pid, int *statusPtr, int options);

1.where pid is the process of the child it should wait.

2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.

3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:

WNOHANG WUNTRACED WCONTINUED

If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.

benifits over wait

1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes

2.waitpid supports job control

3.it supports non blocking of the parent process

How do I run a batch script from within a batch script?

Here is example:

You have a.bat:

@echo off
if exist b.bat goto RUNB
goto END
:RUNB
b.bat
:END

and b.bat called conditionally from a.bat:

@echo off 
echo "This is b.bat"

Angular EXCEPTION: No provider for Http

I just add both these in my app.module.ts:

"import { HttpClientModule }    from '@angular/common/http'; 

&

import { HttpModule } from '@angular/http';"

Now its works fine.... And dont forget to add in the

@NgModule => Imports:[] array

How to set seekbar min and max value

Another solution to handle this case is creating a customized Seekbar, to get ride of converting the real value and SeekBar progress every time:

import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar

//
// Require SeekBar with range [Min, Max] and INCREMENT value,
// However, Android Seekbar starts from 0 and increment is 1 by default, Android supports min attr on API 26,
// To make a increment & range Seekbar, we can do the following conversion:
//
//     seekbar.setMax((Max - Min) / Increment)
//     seekbar.setProgress((actualValue - Min) / Increment)
//     seekbar.getProgress = Min + (progress * Increment)
//
// The RangeSeekBar is responsible for handling all these logic inside the class.

data class Range(val min: Int, val max: Int, private val defaultIncrement: Int) {
    val increment = if ((max - min) < defaultIncrement) 1 else defaultIncrement
}


internal fun Range.toSeekbarMaximum(): Int = (max - min) / increment


class RangeSeekBar: SeekBar, SeekBar.OnSeekBarChangeListener {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    var range: Range = Range(0, 100, 1)
        set(value) {
            field = value
            max = value.toSeekbarMaximum()
        }

    var value: Int = 0
        get() = range.min + progress * range.increment
        set(value) {
            progress = (value - range.min) / range.increment
            field = value
        }

    var onSeekBarChangeListenerDelegate: OnSeekBarChangeListener? = this

    override fun setOnSeekBarChangeListener(l: OnSeekBarChangeListener?) {
        onSeekBarChangeListenerDelegate = l
        super.setOnSeekBarChangeListener(this)
    }

    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        onSeekBarChangeListenerDelegate?.onProgressChanged(seekBar, value, fromUser)
    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
        onSeekBarChangeListenerDelegate?.onStartTrackingTouch(seekBar)
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
        onSeekBarChangeListenerDelegate?.onStopTrackingTouch(seekBar)
    }
}

Then in your fragment,

    // init
    range_seekbar.range = Range(10, 110, 10)
    range_seekbar.value = 20

    // observe value changes
    range_seekbar.userChanges().skipInitialValue().subscribe {
        println("current value=$it")
    }

Keywords: Kotlin, range SeekBar, Rx

Visual Studio : short cut Key : Duplicate Line

Not an answer, just a useful addition: As a freebie, I just invented (well... ehm... adjusted the code posted by Lolo) a RemoveLineOrBlock macro. Enjoy!

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module RemoveLineOrBlock

    Sub RemoveLineOrBlock()
        Dim selection As TextSelection = DTE.ActiveDocument.Selection
        Dim lineNumber As Integer
        Dim line As String

        If selection.IsEmpty Then
            selection.StartOfLine(0)
            selection.EndOfLine(True)
        Else
            Dim top As Integer = selection.TopLine
            Dim bottom As Integer = selection.BottomLine

            selection.MoveToDisplayColumn(top, 0)
            selection.StartOfLine(0)

            selection.MoveToDisplayColumn(bottom, 0, True)
            selection.EndOfLine(True)
        End If

        selection.LineDown(True)
        selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn,True)

        selection.Delete()

        selection.MoveToDisplayColumn(selection.BottomLine, 0)
        selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText)

    End Sub

End Module

angular2: Error: TypeError: Cannot read property '...' of undefined

That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

You can read more about safe navigation operator here.

Update:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

Read more about NgIf directive here.

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

Here is the reproduced error.

>>> d = {}
>>> d.update([(1,)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> 
>>> d
{}
>>> 
>>> d.update([(1, 2)])
>>> d
{1: 2}
>>> 
>>> d.update('hello_some_string')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>  
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> 

If you give the sequence and any element length is 1 and required two then we will get this kind of error. See the above code. First time I gave the sequence with tuple and it's length 1, then we got the error and dictionary is not updated. second time I gave inside tuple with with two elements, dictionary got updated.

Can I find events bound on an element with jQuery?

I'm adding this for posterity; There's an easier way that doesn't involve writing more JS. Using the amazing firebug addon for firefox,

  1. Right click on the element and select 'Inspect element with Firebug'
  2. In the sidebar panels (shown in the screenshot), navigate to the events tab using the tiny > arrow
  3. The events tab shows the events and corresponding functions for each event
  4. The text next to it shows the function location

enter image description here

Using an authorization header with Fetch in React Native

I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:

...
    let headers = {"Content-Type": "application/json"};
    if (token) {
      headers["Authorization"] = `Token ${token}`;
    }
    return fetch("/api/instruments/", {headers,})
      .then(res => {
...

I was running apache.

What solved this problem for me was changing WSGIPassAuthorization to 'On' in wsgi.conf.

I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config, I did this:

container_commands:
  01wsgipass:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

MySQL JOIN with LIMIT 1 on joined table

Another example with 3 nested tables: 1/ User 2/ UserRoleCompanie 3/ Companie

  • 1 user has many UserRoleCompanie.
  • 1 UserRoleCompanie has 1 user and 1 Company
  • 1 Companie has many UserRoleCompanie
SELECT 
u.id as userId, 
u.firstName,
u.lastName,
u.email,
urc.id ,
urc.companieRole,
c.id as companieId,
c.name as companieName
FROM User as u 
JOIN UserRoleCompanie as urc ON u.id = urc.userId
    AND urc.id = (
        SELECT urc2.id
        FROM UserRoleCompanie urc2 
        JOIN Companie ON urc2.companieId = Companie.id
        AND urc2.userId = u.id 
        AND Companie.isPersonal = false
        order by Companie.createdAt DESC
        
        limit 1
    )
    
LEFT JOIN Companie as c ON urc.companieId = c.id
+---------------------------+-----------+--------------------+---------------------------+---------------------------+--------------+---------------------------+-------------------+
| userId                    | firstName | lastName           | email                     | id                        | companieRole | companieId                | companieName      |
+---------------------------+-----------+--------------------+---------------------------+---------------------------+--------------+---------------------------+-------------------+
| cjjt9s9iw037f0748raxmnnde | henry     | pierrot            | [email protected]           | cjtuflye81dwt0748e4hnkiv0 | OWNER        | cjtuflye71dws0748r7vtuqmg | leclerc           |

how to take user input in Array using java?

**How to accept array by user Input

Answer:-

import java.io.*;

import java.lang.*;

class Reverse1  {

   public static void main(String args[]) throws IOException {

     int a[]=new int[25];

     int num=0,i=0;

     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

     System.out.println("Enter the Number of element");

     num=Integer.parseInt(br.readLine());

     System.out.println("Enter the array");

     for(i=1;i<=num;i++) {
        a[i]=Integer.parseInt(br.readLine());
     }

     for(i=num;i>=1;i--) {
        System.out.println(a[i]);    
     }

   }

}

Not able to access adb in OS X through Terminal, "command not found"

The problem is: adb is not in your PATH. This is where the shell looks for executables. You can check your current PATH with echo $PATH.

Bash will first try to look for a binary called adb in your Path, and not in the current directory. Therefore, if you are currently in the platform-tools directory, just call

./adb --help

The dot is your current directory, and this tells Bash to use adb from there.

But actually, you should add platform-tools to your PATH, as well as some other tools that the Android SDK comes with. This is how you do it:

  1. Find out where you installed the Android SDK. This might be (where $HOME is your user's home directory) one of the following (or verify via Configure > SDK Manager in the Android Studio startup screen):

    • Linux: $HOME/Android/Sdk
    • macOS: $HOME/Library/Android/sdk
  2. Find out which shell profile to edit, depending on which file is used:

    • Linux: typically $HOME/.bashrc
    • macOS: typically $HOME/.bash_profile
    • With Zsh: $HOME/.zshrc
  3. Open the shell profile from step two, and at the bottom of the file, add the following lines. Make sure to replace the path with the one where you installed platform-tools if it differs:

    export ANDROID_HOME="$HOME/Android/Sdk"
    export PATH="$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:$PATH"
    
  4. Save the profile file, then, re-start the terminal or run source ~/.bashrc (or whatever you just modified).

Note that setting ANDROID_HOME is required for some third party frameworks, so it does not hurt to add it.

Does Git Add have a verbose switch

You can use git add -i to get an interactive version of git add, although that's not exactly what you're after. The simplest thing to do is, after having git added, use git status to see what is staged or not.

Using git add . isn't really recommended unless it's your first commit. It's usually better to explicitly list the files you want staged, so that you don't start tracking unwanted files accidentally (temp files and such).

How do you change the size of figures drawn with matplotlib?

USING plt.rcParams

There is also this workaround in case you want to change the size without using the figure environment. So in case you are using plt.plot() for example, you can set a tuple with width and height.

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)

This is very useful when you plot inline (e.g. with IPython Notebook). As @asamaier noticed is preferable to not put this statement in the same cell of the imports statements.

Conversion to cm

The figsize tuple accepts inches so if you want to set it in centimetres you have to divide them by 2.54 have a look to this question.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

Just an addition to the answer of @phantomlimb,

while View.generateViewId() require API Level >= 17,
this tool is compatibe with all API.

according to current API Level,
it decide weather using system API or not.

so you can use ViewIdGenerator.generateViewId() and View.generateViewId() in the same time and don't worry about getting same id

import java.util.concurrent.atomic.AtomicInteger;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;

/**
 * {@link View#generateViewId()}??API Level >= 17,??????????API Level
 * <p>
 * ??????API Level,?????{@link View#generateViewId()},???????{@link View#generateViewId()}
 * ??,???????Id??
 * <p>
 * =============
 * <p>
 * while {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API.
 * <p>
 * according to current API Level, it decide weather using system API or not.<br>
 * so you can use {@link ViewIdGenerator#generateViewId()} and {@link View#generateViewId()} in the
 * same time and don't worry about getting same id
 * 
 * @author [email protected]
 */
public class ViewIdGenerator {
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    @SuppressLint("NewApi")
    public static int generateViewId() {

        if (Build.VERSION.SDK_INT < 17) {
            for (;;) {
                final int result = sNextGeneratedId.get();
                // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
                int newValue = result + 1;
                if (newValue > 0x00FFFFFF)
                    newValue = 1; // Roll over to 1, not 0.
                if (sNextGeneratedId.compareAndSet(result, newValue)) {
                    return result;
                }
            }
        } else {
            return View.generateViewId();
        }

    }
}

How to check if a number is a power of 2

int isPowerOfTwo(unsigned int x)
{
    return ((x != 0) && ((x & (~x + 1)) == x));
}

This is really fast. It takes about 6 minutes and 43 seconds to check all 2^32 integers.

Importing CSV data using PHP/MySQL

i think the main things to remember about parsing csv is that it follows some simple rules:

a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns

have a read of this post to see what i am talking about

it's actually very easy to do once you have the hang of it and becomes very useful.

MySQL and PHP - insert NULL rather than empty string

All you have to do is: $variable =NULL; // and pass it in the insert query. This will store the value as NULL in mysql db

Using DISTINCT along with GROUP BY in SQL Server

Perhaps not in the context that you have it, but you could use

SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA

You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.

How do I add a placeholder on a CharField in Django?

The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'

It also allows the placeholder to depend on the instance for ModelForms with instance specified.

HTML: How to limit file upload to be only images?

<script>

    function chng()
    {
        var typ=document.getElementById("fiile").value;
        var res = typ.match(".jp");

        if(res)
        {
            alert("sucess");
        }
        else
        {
            alert("Sorry only jpeg images are accepted");
            document.getElementById("fiile").value="; //clear the uploaded file
        }
    }

</script>

Now in the html part

<input type="file" onchange="chng()">

this code will check if the uploaded file is a jpg file or not and restricts the upload of other types

Example JavaScript code to parse CSV data

I have constructed this JavaScript script to parse a CSV in string to array object. I find it better to break down the whole CSV into lines, fields and process them accordingly. I think that it will make it easy for you to change the code to suit your need.

    //
    //
    // CSV to object
    //
    //

    const new_line_char = '\n';
    const field_separator_char = ',';

    function parse_csv(csv_str) {

        var result = [];

        let line_end_index_moved = false;
        let line_start_index = 0;
        let line_end_index = 0;
        let csr_index = 0;
        let cursor_val = csv_str[csr_index];
        let found_new_line_char = get_new_line_char(csv_str);
        let in_quote = false;

        // Handle \r\n
        if (found_new_line_char == '\r\n') {
            csv_str = csv_str.split(found_new_line_char).join(new_line_char);
        }
        // Handle the last character is not \n
        if (csv_str[csv_str.length - 1] !== new_line_char) {
            csv_str += new_line_char;
        }

        while (csr_index < csv_str.length) {
            if (cursor_val === '"') {
                in_quote = !in_quote;
            } else if (cursor_val === new_line_char) {
                if (in_quote === false) {
                    if (line_end_index_moved && (line_start_index <= line_end_index)) {
                        result.push(parse_csv_line(csv_str.substring(line_start_index, line_end_index)));
                        line_start_index = csr_index + 1;
                    } // Else: just ignore line_end_index has not moved or line has not been sliced for parsing the line
                } // Else: just ignore because we are in a quote
            }
            csr_index++;
            cursor_val = csv_str[csr_index];
            line_end_index = csr_index;
            line_end_index_moved = true;
        }

        // Handle \r\n
        if (found_new_line_char == '\r\n') {
            let new_result = [];
            let curr_row;
            for (var i = 0; i < result.length; i++) {
                curr_row = [];
                for (var j = 0; j < result[i].length; j++) {
                    curr_row.push(result[i][j].split(new_line_char).join('\r\n'));
                }
                new_result.push(curr_row);
            }
            result = new_result;
        }
        return result;
    }

    function parse_csv_line(csv_line_str) {

        var result = [];

        //let field_end_index_moved = false;
        let field_start_index = 0;
        let field_end_index = 0;
        let csr_index = 0;
        let cursor_val = csv_line_str[csr_index];
        let in_quote = false;

        // Pretend that the last char is the separator_char to complete the loop
        csv_line_str += field_separator_char;

        while (csr_index < csv_line_str.length) {
            if (cursor_val === '"') {
                in_quote = !in_quote;
            } else if (cursor_val === field_separator_char) {
                if (in_quote === false) {
                    if (field_start_index <= field_end_index) {
                        result.push(parse_csv_field(csv_line_str.substring(field_start_index, field_end_index)));
                        field_start_index = csr_index + 1;
                    } // Else: just ignore field_end_index has not moved or field has not been sliced for parsing the field
                } // Else: just ignore because we are in quote
            }
            csr_index++;
            cursor_val = csv_line_str[csr_index];
            field_end_index = csr_index;
            field_end_index_moved = true;
        }
        return result;
    }

    function parse_csv_field(csv_field_str) {
        with_quote = (csv_field_str[0] === '"');

        if (with_quote) {
            csv_field_str = csv_field_str.substring(1, csv_field_str.length - 1); // remove the start and end quotes
            csv_field_str = csv_field_str.split('""').join('"'); // handle double quotes
        }
        return csv_field_str;
    }

    // Initial method: check the first newline character only
    function get_new_line_char(csv_str) {
        if (csv_str.indexOf('\r\n') > -1) {
            return '\r\n';
        } else {
            return '\n'
        }
    }

Force flushing of output to a file while bash script is still running

I had this problem with a background process in Mac OS X using the StartupItems. This is how I solve it:

If I make sudo ps aux I can see that mytool is launched.

I found that (due to buffering) when Mac OS X shuts down mytool never transfers the output to the sed command. However, if I execute sudo killall mytool, then mytool transfers the output to the sed command. Hence, I added a stop case to the StartupItems that is executed when Mac OS X shuts down:

start)
    if [ -x /sw/sbin/mytool ]; then
      # run the daemon
      ConsoleMessage "Starting mytool"
      (mytool | sed .... >> myfile.txt) & 
    fi
    ;;
stop)
    ConsoleMessage "Killing mytool"
    killall mytool
    ;;

Mysql password expired. Can't connect

I went through the same issue recently while installing mysql on mac os x capitan. I did not find the correct answer here, so adding this answer.

MySql in current versions, generates a temporary password when you install mysql. Use this password to set a new password using the mysqladmin utility as below;

/usr/local/mysql/bin/mysqladmin -u root -p'<your temp password>' password '<your new password>'

Hope it helps you and others.

How do I get the current username in .NET using C#?

Use System.Windows.Forms.SystemInformation.UserName for the actually logged in user as Environment.UserName still returns the account being used by the current process.

Extract substring from a string

Here is a real world example:

String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1); 

In the example asubstring would return: h

How can I set the default value for an HTML <select> element?

Another example; using JavaScript to set a selected option.

(You could use this example to for loop an array of values into a drop down component)

<select id="yourDropDownElementId"><select/>

// Get the select element
var select = document.getElementById("yourDropDownElementId");
// Create a new option element
var el = document.createElement("option");
// Add our value to the option
el.textContent = "Example Value";
el.value = "Example Value";
// Set the option to selected
el.selected = true;
// Add the new option element to the select element
select.appendChild(el);

DataGridView checkbox column - value and functionality

It is quite simple

DataGridViewCheckBoxCell checkedCell = (DataGridViewCheckBoxCell) grdData.Rows[e.RowIndex].Cells["grdChkEnable"];
    
bool isEnabled = false;
if (checkedCell.AccessibilityObject.State.HasFlag(AccessibleStates.Checked))
{
    isEnabled = true;
}
if (isEnabled)
{
   // do your business process;
}

How to delete and recreate from scratch an existing EF Code First database

dbctx.Database.EnsureDeleted(); dbctx.Database.EnsureCreated();

How to set HTML5 required attribute in Javascript?

What matters isn't the attribute but the property, and its value is a boolean.

You can set it using

 document.getElementById("edName").required = true;

Freemarker iterating over hashmap keys

FYI, it looks like the syntax for retrieving the values has changed according to:

http://freemarker.sourceforge.net/docs/ref_builtins_hash.html

<#assign h = {"name":"mouse", "price":50}>
<#assign keys = h?keys>
<#list keys as key>${key} = ${h[key]}; </#list>

What is a stack trace, and how can I use it to debug my application errors?

There is one more stacktrace feature offered by Throwable family - the possibility to manipulate stack trace information.

Standard behavior:

package test.stack.trace;

public class SomeClass {

    public void methodA() {
        methodB();
    }

    public void methodB() {
        methodC();
    }

    public void methodC() {
        throw new RuntimeException();
    }

    public static void main(String[] args) {
        new SomeClass().methodA();
    }
}

Stack trace:

Exception in thread "main" java.lang.RuntimeException
    at test.stack.trace.SomeClass.methodC(SomeClass.java:18)
    at test.stack.trace.SomeClass.methodB(SomeClass.java:13)
    at test.stack.trace.SomeClass.methodA(SomeClass.java:9)
    at test.stack.trace.SomeClass.main(SomeClass.java:27)

Manipulated stack trace:

package test.stack.trace;

public class SomeClass {

    ...

    public void methodC() {
        RuntimeException e = new RuntimeException();
        e.setStackTrace(new StackTraceElement[]{
                new StackTraceElement("OtherClass", "methodX", "String.java", 99),
                new StackTraceElement("OtherClass", "methodY", "String.java", 55)
        });
        throw e;
    }

    public static void main(String[] args) {
        new SomeClass().methodA();
    }
}

Stack trace:

Exception in thread "main" java.lang.RuntimeException
    at OtherClass.methodX(String.java:99)
    at OtherClass.methodY(String.java:55)

Twitter Bootstrap 3: how to use media queries?

Bootstrap 3

Here are the selectors used in BS3, if you want to stay consistent:

@media(max-width:767px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}

Note: FYI, this may be useful for debugging:

<span class="visible-xs">SIZE XS</span>
<span class="visible-sm">SIZE SM</span>
<span class="visible-md">SIZE MD</span>
<span class="visible-lg">SIZE LG</span>

Bootstrap 4

Here are the selectors used in BS4. There is no "lowest" setting in BS4 because "extra small" is the default. I.e. you would first code the XS size and then have these media overrides afterwards.

@media(min-width:576px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}

Update 2019-02-11: BS3 info is still accurate as of version 3.4.0, updated BS4 for new grid, accurate as of 4.3.0.

How to deal with a slow SecureRandom generator?

On Linux, the default implementation for SecureRandom is NativePRNG (source code here), which tends to be very slow. On Windows, the default is SHA1PRNG, which as others pointed out you can also use on Linux if you specify it explicitly.

NativePRNG differs from SHA1PRNG and Uncommons Maths' AESCounterRNG in that it continuously receives entropy from the operating system (by reading from /dev/urandom). The other PRNGs do not acquire any additional entropy after seeding.

AESCounterRNG is about 10x faster than SHA1PRNG, which IIRC is itself two or three times faster than NativePRNG.

If you need a faster PRNG that acquires entropy after initialization, see if you can find a Java implementation of Fortuna. The core PRNG of a Fortuna implementation is identical to that used by AESCounterRNG, but there is also a sophisticated system of entropy pooling and automatic reseeding.

How to open a file for both reading and writing?

r+ is the canonical mode for reading and writing at the same time. This is not different from using the fopen() system call since file() / open() is just a tiny wrapper around this operating system call.

How to get the ASCII value of a character

From here:

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

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

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

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

In Python 3 you can use chr instead of unichr.


ord() - Python 3.6.5rc1 documentation

ord() - Python 2.7.14 documentation

How to 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.

What is this CSS selector? [class*="span"]

The Following:

.show-grid [class*="span"] {

means that all child elements of '.show-grid' with a class that CONTAINS the word 'span' in it will acquire those CSS properties.

<div class="show-grid">
  <div class="span">.span</div>
  <div class="span6">span6</div>
  <div class="attention-span">attention</div>
  <div class="spanish">spanish</div>
  <div class="mariospan">mariospan</div>
  <div class="espanol">espanol</div>

  <div>
    <div class="span">.span</div>
  </div>

  <p class="span">span</p>
  <span class="span">I do GET HIT</span>

  <span>I DO NOT GET HIT since I need a class of 'span'</span>
</div>

<div class="span">I DO NOT GET HIT since I'm outside of .show-grid</span>

All of the elements get hit except for the <span> by itself.


In Regards to Bootstrap:

  • span6 : this was Bootstrap 2's scaffolding technique which divided a section into a horizontal grid, based on parts of 12. Thus span6 would have a width of 50%.
  • In the current day implementation of Bootstrap (v.3 and v.4), you now use the .col-* classes (e.g. col-sm-6), which also specifies a media breakpoint to handle responsiveness when the window shrinks below a certain size. Check Bootstrap 4.1 and Bootstrap 3.3.7 for more documentation. I would recommend going with a later Bootstrap nowadays

Convert object of any type to JObject with Json.NET

This will work:

var cycles = cycleSource.AllCycles();

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var vm = new JArray();

foreach (var cycle in cycles)
{
    var cycleJson = JObject.FromObject(cycle);
    // extend cycleJson ......
    vm.Add(cycleJson);
}

return vm;

#pragma mark in Swift?

Try this:

// MARK: Reload TableView

func reloadTableView(){

    tableView.reload()
}

How to convert SecureString to System.String?

Obviously you know how this defeats the whole purpose of a SecureString, but I'll restate it anyway.

If you want a one-liner, try this: (.NET 4 and above only)

string password = new System.Net.NetworkCredential(string.Empty, securePassword).Password;

Where securePassword is a SecureString.

How can I delete a user in linux when the system says its currently used in a process

restart your computer and run $sudo deluser username... worked for me

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Spring Boot REST service exception handling

For people that want to response according to http status code, you can use the ErrorController way:

@Controller
public class CustomErrorController extends BasicErrorController {

    public CustomErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status.equals(HttpStatus.INTERNAL_SERVER_ERROR)){
            return ResponseEntity.status(status).body(ResponseBean.SERVER_ERROR);
        }else if (status.equals(HttpStatus.BAD_REQUEST)){
            return ResponseEntity.status(status).body(ResponseBean.BAD_REQUEST);
        }
        return super.error(request);
    }
}

The ResponseBean here is my custom pojo for response.

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along with whatever IP address you're specifying.

You can do this by using IPTABLES to redirect port 80 to 8080.

Writing a pandas DataFrame to CSV file

it could be not the answer for this case, but as I had the same error-message with .to_csvI tried .toCSV('name.csv') and the error-message was different ("SparseDataFrame' object has no attribute 'toCSV'). So the problem was solved by turning dataframe to dense dataframe

df.to_dense().to_csv("submission.csv", index = False, sep=',', encoding='utf-8')

mailto using javascript

I've simply used this javascript code (using jquery but it's not strictly necessary) :

    $( "#button" ).on( "click", function(event) {
         $(this).attr('href', 'mailto:[email protected]?subject=hello');
    });

When users click on the link, we replace the href attribute of the clicked element.

Be careful don't prevent the default comportment (event.preventDefault), we must let do it because we have just replaced the href where to go

I think robots can't see it, the address is protected from spams.

C# Pass Lambda Expression as Method Parameter

Use a Func<T1, T2, TResult> delegate as the parameter type and pass it in to your Query:

public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
  using (SqlConnection connection = new SqlConnection(getConnectionString())) {
    connection.Open();
    return connection.Query<FullTimeJob, Student, FullTimeJob>(sql, 
        lambda,
        splitOn: "user_id",
        param: parameters).ToList<IJob>();   
  }  
}

You would call it:

getJobs((job, student) => {         
        job.Student = student;
        job.StudentId = student.Id;
        return job;
        });

Or assign the lambda to a variable and pass it in.

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

Working for me only after installing Python 2.7.x (not 3.x) and then npm uninstall node-sass && npm install node-sass like @Quinn Comendant said.

How do I clone a github project to run locally?

git clone git://github.com/ryanb/railscasts-episodes.git

Line break (like <br>) using only css

You can use ::after to create a 0px-height block after the <h4>, which effectively moves anything after the <h4> to the next line:

_x000D_
_x000D_
h4 {_x000D_
  display: inline;_x000D_
}_x000D_
h4::after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    Text, text, text, text, text. <h4>Sub header</h4>_x000D_
    Text, text, text, text, text._x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to initialize a List<T> to a given size (as opposed to capacity)?

Use the constructor which takes an int ("capacity") as an argument:

List<string> = new List<string>(10);

EDIT: I should add that I agree with Frederik. You are using the List in a way that goes against the entire reasoning behind using it in the first place.

EDIT2:

EDIT 2: What I'm currently writing is a base class offering default functionality as part of a bigger framework. In the default functionality I offer, the size of the List is known in advanced and therefore I could have used an array. However, I want to offer any base class the chance to dynamically extend it and therefore I opt for a list.

Why would anyone need to know the size of a List with all null values? If there are no real values in the list, I would expect the length to be 0. Anyhow, the fact that this is cludgy demonstrates that it is going against the intended use of the class.

How to run or debug php on Visual Studio Code (VSCode)

There is now a handy guide for configuring PHP debugging in Visual Studio Code at http://blogs.msdn.com/b/nicktrog/archive/2016/02/11/configuring-visual-studio-code-for-php-development.aspx

From the link, the steps are:

  1. Download and install Visual Studio Code
  2. Configure PHP linting in user settings
  3. Download and install the PHP Debug extension from the Visual Studio Marketplace
  4. Configure the PHP Debug extension for XDebug

Note there are specific details in the linked article, including the PHP values for your VS Code user config, and so on.

How to reset AUTO_INCREMENT in MySQL?

I tried to alter the table and set auto_increment to 1 but it did not work. I resolved to delete the column name I was incrementing, then create a new column with your preferred name and set that new column to increment from the onset.

Jquery UI tooltip does not support html content

Instead of this:

$(document).tooltip({
    content: function () {
        return $(this).prop('title');
    }
});

use this for better performance

$(selector).tooltip({
    content: function () {
        return this.getAttribute("title");
    },
});

How do I fix PyDev "Undefined variable from import" errors?

An approximation of what I was doing:

import module.submodule

class MyClass:
    constant = submodule.constant

To which pylint said: E: 4,15: Undefined variable 'submodule' (undefined-variable)

I resolved this by changing my import like:

from module.submodule import CONSTANT

class MyClass:
    constant = CONSTANT

Note: I also renamed by imported variable to have an uppercase name to reflect its constant nature.

Tkinter: "Python may not be configured for Tk"

You need to install tkinter for python3.

On Fedora pip3 install tkinter --user returns Could not find a version that satisfies the requirement... so I have to command: dnf install python3-tkinter. This have solved my problem

Populate unique values into a VBA array from Excel

This VBA function returns an array of distinct values when passed either a range or a 2D array source

It defaults to processing the first column of the source, but you can optionally choose another column.

I wrote a LinkedIn article about it.

Function DistinctVals(a, Optional col = 1)
    Dim i&, v: v = a
    With CreateObject("Scripting.Dictionary")
        For i = 1 To UBound(v): .Item(v(i, col)) = 1: Next
        DistinctVals = Application.Transpose(.Keys)
    End With
End Function

checking if number entered is a digit in jquery

With jQuery's validation plugin you could do something like this, assuming that the form is called form and the value to validate is called nrInput

$("form").validate({
            errorElement: "div",
            errorClass: "error-highlight",
            onblur: true,
            onsubmit: true,
            focusInvalid: true,
            rules:{
                'nrInput': {
                    number: true,
                    required: true
                }
            });

This also handles decimal values.

jQuery Mobile - back button

Newer versions of JQuery mobile API (I guess its newer than 1.5) require adding 'back' button explicitly in header or bottom of each page.

So, try adding this in your page div tags:

data-add-back-btn="true"
data-back-btn-text="Back"

Example:

<div data-role="page" id="page2" data-add-back-btn="true" data-back-btn-text="Back">

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

How to see JavaDoc in IntelliJ IDEA?

I have noticed that selecting the method name and pressing F2(Quick Documentation) dispalys it's JavaDoc. I am using Intellij 2016, and Eclipse Keymap

Copy directory to another directory using ADD command

Indeed ADD go /usr/local/ will add content of go folder and not the folder itself, you can use Thomasleveil solution or if that did not work for some reason you can change WORKDIR to /usr/local/ then add your directory to it like:

WORKDIR /usr/local/
COPY go go/

or

WORKDIR /usr/local/go
COPY go ./

But if you want to add multiple folders, it will be annoying to add them like that, the only solution for now as I see it from my current issue is using COPY . . and exclude all unwanted directories and files in .dockerignore, let's say I got folders and files:

- src 
- tmp 
- dist 
- assets 
- go 
- justforfun 
- node_modules 
- scripts 
- .dockerignore 
- Dockerfile 
- headache.lock 
- package.json 

and I want to add src assets package.json justforfun go so:

in Dockerfile:

FROM galaxy:latest

WORKDIR /usr/local/
COPY . .

in .dockerignore file:

node_modules
headache.lock
tmp
dist

Or for more fun (or you like to confuse more people make them suffer as well :P) can be:

*
!src 
!assets 
!go 
!justforfun 
!scripts 
!package.json 

In this way you ignore everything, but excluding what you want to be copied or added only from "ignore list".

It is a late answer but adding more ways to do the same covering even more cases.