Programs & Examples On #Categories

Get Category name from Post ID

here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

get_the_category

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

Get current category ID of the active page

I used this for breadcrums in the category template page:

$cat_obj = $wp_query->get_queried_object();
$thiscat_id = $cat_obj->term_id;
$thiscat = get_category($thiscat_id);
$parentcat = get_category($thiscat->parent);

Remove category & tag base from WordPress url - without a plugin

WordPress 5.0.2:

To remove category slug from existing posts, do this :

  1. Navigate to Settings > Permalinks and change Custom Structure from /%category%/%postname%/ to: /%postname%/
  2. Keep Category and Tag bases empty (which is the default also)
  3. Save

All posts can now be directly accessed via domain.com/%postname%/ and all categories can be accessed via domain.com/category/xyz/. WordPress will automatically add all the 301 redirects for the old urls. So, if someone accesses domain.com/%category%/%postname%/, they will automatically get redirected to domain.com/%postname%/.

Override console.log(); for production

I would recommend using: https://github.com/sunnykgupta/jsLogger

Features:

  1. It safely overrides the console.log.
  2. Takes care if the console is not available (oh yes, you need to factor that too.)
  3. Stores all logs (even if they are suppressed) for later retrieval.
  4. Handles major console functions like log, warn, error, info.

Is open for modifications and will be updated whenever new suggestions come up.

Disclaimer: I am the author of the plugin.

What's the simplest way of detecting keyboard input in a script from the terminal?

The Python Documentation provides this snippet to get single characters from the keyboard:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            if c:
                print("Got character", repr(c))
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

You can also use the PyHook module to get your job done.

iOS / Android cross platform development

My experience with making something very simple in PhoneGap+jQuery Mobile was fine. I was able to do it quickly for iOS. However, it didn't work on my Android phones without making some changes. The project was a very simple app to take pictures and post them to a web site. And at the end of the day it felt "clunky" compared to a true native app.

I don't believe there will ever be easy cross platform development. I think the browser is as close as you will get. By choosing something like PhoneGap I think you are just trading one set of pain points for a different set of pain points.

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

How can I get a list of locally installed Python modules?

In case you have an anaconda python distribution installed, you could also use

$conda list

in addition to solutions described above.

disable viewport zooming iOS 10+ safari?

this worked for me:

document.documentElement.addEventListener('touchmove', function (event) {
    event.preventDefault();
}, false);

How do I POST JSON data with cURL?

For Windows, having a single quote for the -d value did not work for me, but it did work after changing to double quote. Also I needed to escape double quotes inside curly brackets.

That is, the following did not work:

curl -i -X POST -H "Content-Type: application/json" -d '{"key":"val"}' http://localhost:8080/appname/path

But the following worked:

curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path

Python logging not outputting anything

The default logging level is warning. Since you haven't changed the level, the root logger's level is still warning. That means that it will ignore any logging with a level that is lower than warning, including debug loggings.

This is explained in the tutorial:

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

The 'info' line doesn't print anything, because the level is higher than info.

To change the level, just set it in the root logger:

'root':{'handlers':('console', 'file'), 'level':'DEBUG'}

In other words, it's not enough to define a handler with level=DEBUG, the actual logging level must also be DEBUG in order to get it to output anything.

What is an optional value in Swift?

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type:

var name: String?

You can refer to this link to get knowledge in deep: https://medium.com/@agoiabeladeyemi/optionals-in-swift-2b141f12f870

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

Don't use getApplicationContext() on declaring dialouge

Always use this or your activity.this

Google Chrome forcing download of "f.txt" file

This can occur on android too not just computers. Was browsing using Kiwi when the site I was on began to endlessly redirect so I cut net access to close it out and noticed my phone had DL'd something f.txt in my downloaded files.

Deleted it and didn't open.

How to fix C++ error: expected unqualified-id

There should be no semicolon here:

class WordGame;

...but there should be one at the end of your class definition:

...
private:
    string theWord;
}; // <-- Semicolon should be at the end of your class definition

Shell Script Syntax Error: Unexpected End of File

I have encountered the same error while trying to execute a script file created in windows OS using textpad. so that one can select proper file format like unix/mac etc.. or recreate the script in linux iteself.

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

Are there pointers in php?

To answer the second part of your question - there are no pointers in PHP.

When working with objects, you generally pass by reference rather than by value - so in some ways this operates like a pointer, but is generally completely transparent.

This does depend on the version of PHP you are using.

Python and SQLite: insert into table

there's a better way

# Larger example
rows = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
        ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
        ('2006-04-06', 'SELL', 'IBM', 500, 53.00)]
c.executemany('insert into stocks values (?,?,?,?,?)', rows)
connection.commit()

Python, print all floats to 2 decimal places in output

Not directly in the way you want to write that, no. One of the design tenets of Python is "Explicit is better than implicit" (see import this). This means that it's better to describe what you want rather than having the output format depend on some global formatting setting or something. You could of course format your code differently to make it look nicer:

print         '%.2f' % var1, \
      'kg =' ,'%.2f' % var2, \
      'lb =' ,'%.2f' % var3, \
      'gal =','%.2f' % var4, \
      'l'

Call Javascript onchange event by programmatically changing textbox value

You're misinterpreting what the onchange event does when applied to a textarea. It won't fire until it loses focus or you hit enter. Why not fire the function from an onchange on the select that fills in the text area?

Check out here for more on the onchange event: w3schools

How does RewriteBase work in .htaccess

I believe this excerpt from the Apache documentation, complements well the previous answers :

This directive is required when you use a relative path in a substitution in per-directory (htaccess) context unless either of the following conditions are true:

  • The original request, and the substitution, are underneath the DocumentRoot (as opposed to reachable by other means, such as Alias).

  • The filesystem path to the directory containing the RewriteRule, suffixed by the relative substitution is also valid as a URL path on the server (this is rare).

As previously mentioned, in other contexts, it is only useful to make your rule shorter. Moreover, also as previously mentioned, you can achieve the same thing by placing the htaccess file in the subdirectory.

How to disable and then enable onclick event on <div> with javascript

You can disable the event by applying following code:

with .attr() API

$('#your_id').attr("disabled", "disabled");

or with .prop() API

$('#your_id').prop('disabled', true);

Vertically aligning text next to a radio button

You may try something like;

<p><input type="radio" id="oddsPref" name="oddsPref" value="decimal" /><span>Decimal</span></p>

and give the span a margin top like;

span{
    margin-top: 4px;
    position:absolute;
}

here is the fiddle http://jsfiddle.net/UnA6j/11/

How to make the tab character 4 spaces instead of 8 spaces in nano?

Command-line flag

From man nano:

-T cols (--tabsize=cols)
    Set the size (width) of a tab to cols columns.
    The value of cols must be greater than 0. The default value is 8.
-E (--tabstospaces)
    Convert typed tabs to spaces.

For example, to set the tab size to 4, replace tabs with spaces, and edit the file "foo.txt", you would run the command:

nano -ET4 foo.txt

Config file

From man nanorc:

set tabsize n
    Use a tab size of n columns. The value of n must be greater than 0.
    The default value is 8.
set/unset tabstospaces
    Convert typed tabs to spaces.

Edit your ~/.nanorc file (create it if it does not exist), and add those commands to it. For example:

set tabsize 4
set tabstospaces

Nano will use these settings by default whenever it is launched, but command-line flags will override them.

Adding a simple UIAlertView

Other answers already provide information for iOS 7 and older, however UIAlertView is deprecated in iOS 8.

In iOS 8+ you should use UIAlertController. It is a replacement for both UIAlertView and UIActionSheet. Documentation: UIAlertController Class Reference. And a nice article on NSHipster.

To create a simple Alert View you can do the following:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title"
                                                                         message:@"Message"
                                                                  preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
                                                   style:UIAlertActionStyleDefault
                                                 handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];

Swift 3 / 4 / 5:

let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: "OK",
    style: .default,
    handler: nil) //You can use a block here to handle a press on this button

alertController.addAction(actionOk)

self.present(alertController, animated: true, completion: nil)

Note, that, since it was added in iOS 8, this code won't work on iOS 7 and older. So, sadly, for now we have to use version checks like so:

NSString *alertTitle = @"Title";
NSString *alertMessage = @"Message";
NSString *alertOkButtonText = @"Ok";

if (@available(iOS 8, *)) {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
                                                        message:alertMessage
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:alertOkButtonText, nil];
    [alertView show];
}
else {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
                                                                             message:alertMessage
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    //We add buttons to the alert controller by creating UIAlertActions:
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:alertOkButtonText
                                                       style:UIAlertActionStyleDefault
                                                     handler:nil]; //You can use a block here to handle a press on this button
    [alertController addAction:actionOk];
    [self presentViewController:alertController animated:YES completion:nil];
}

Swift 3 / 4 / 5:

let alertTitle = "Title"
let alertMessage = "Message"
let alertOkButtonText = "Ok"

if #available(iOS 8, *) {
    let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
    //We add buttons to the alert controller by creating UIAlertActions:
    let actionOk = UIAlertAction(title: alertOkButtonText,
        style: .default,
        handler: nil) //You can use a block here to handle a press on this button

    alertController.addAction(actionOk)
    self.present(alertController, animated: true, completion: nil)
}
else {
    let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText)
    alertView.show()
}

UPD: updated for Swift 5. Replaced outdated class presence check with availability check in Obj-C.

Select value from list of tuples where condition

Yes, you can use filter if you know at which position in the tuple the desired column resides. If the case is that the id is the first element of the tuple then you can filter the list like so:

filter(lambda t: t[0]==10, mylist)

This will return the list of corresponding tuples. If you want the age, just pick the element you want. Instead of filter you could also use list comprehension and pick the element in the first go. You could even unpack it right away (if there is only one result):

[age] = [t[1] for t in mylist if t[0]==10]

But I would strongly recommend to use dictionaries or named tuples for this purpose.

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

php - push array into array - key issue

I think you have to go for

$arrayname[indexname] = $value;

Java program to find the largest & smallest number in n numbers without using arrays

import java.util.Scanner;

public class LargestSmallestNumbers {

    private static Scanner input;

    public static void main(String[] args) {
       int count,items;
       int newnum =0 ;
       int highest=0;
       int lowest =0;

       input = new Scanner(System.in);
       System.out.println("How many numbers you want to enter?");
       items = input.nextInt();

       System.out.println("Enter "+items+" numbers: ");


       for (count=0; count<items; count++){
           newnum = input.nextInt();               
           if (highest<newnum)
               highest=newnum;

           if (lowest==0)
               lowest=newnum;

           else if (newnum<=lowest)
               lowest=newnum;
           }

       System.out.println("The highest number is "+highest);
       System.out.println("The lowest number is "+lowest);
    }
}

Infinite Recursion with Jackson JSON and Hibernate JPA issue

You Should use @JsonBackReference with @ManyToOne entity and @JsonManagedReference with @onetomany containing entity classes.

@OneToMany(
            mappedBy = "queue_group",fetch = FetchType.LAZY,
            cascade = CascadeType.ALL
        )
    @JsonManagedReference
    private Set<Queue> queues;



@ManyToOne(cascade=CascadeType.ALL)
        @JoinColumn(name = "qid")
       // @JsonIgnore
        @JsonBackReference
        private Queue_group queue_group;

Add / remove input field dynamically with jQuery

you can do it as follow:

 $("#addButton").click(function () {

    if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
    }   

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
          '<input type="text" name="textbox' + counter + 
          '" id="textbox' + counter + '" value="" >');

    newTextBoxDiv.appendTo("#TextBoxesGroup");


    counter++;
     });

     $("#removeButton").click(function () {
    if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

    counter--;

        $("#TextBoxDiv" + counter).remove();

     });

refer live demo http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

Python installation folder > Lib > idlelib > idle.pyw

Double click on it and you're good to go.

How do I measure time elapsed in Java?

Which types to use in order to accomplish this in Java?

Answer: long

public class Stream {
    public long startTime;
    public long endTime;

    public long getDuration() {
        return endTime - startTime;
    }
    // I  would add
    public void start() {
        startTime = System.currentTimeMillis();
    }
    public void stop() {
         endTime = System.currentTimeMillis();
     }
}

Usage:

  Stream s = .... 

  s.start();

  // do something for a while 

  s.stop();

  s.getDuration(); // gives the elapsed time in milliseconds. 

That's my direct answer for your first question.

For the last "note" I would suggest you to use Joda Time. It contains an interval class suitable for what you need.

Git on Windows: How do you set up a mergetool?

As already answered here (and here and here), mergetool is the command to configure this. For a nice graphical frontend I recommend kdiff3 (GPL).

How can I get a vertical scrollbar in my ListBox?

The problem with your solution is you're putting a scrollbar around a ListBox where you probably want to put it inside the ListBox.

If you want to force a scrollbar in your ListBox, use the ScrollBar.VerticalScrollBarVisibility attached property.

<ListBox 
    ItemsSource="{Binding}" 
    ScrollViewer.VerticalScrollBarVisibility="Visible">
</ListBox>

Setting this value to Auto will popup the scrollbar on an as needed basis.

PHP date() with timezone?

If I understood correct,You need to set time zone first like:

date_default_timezone_set('UTC');

And than you can use date function:

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

How to get HttpClient to pass credentials along with the request?

It worked for me after I set up a user with internet access in the Windows service.

In my code:

HttpClientHandler handler = new HttpClientHandler();
handler.Proxy = System.Net.WebRequest.DefaultWebProxy;
handler.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
.....
HttpClient httpClient = new HttpClient(handler)
.... 

Node.js spawn child process and get terminal output live

I found myself requiring this functionality often enough that I packaged it into a library called std-pour. It should let you execute a command and view the output in real time. To install simply:

npm install std-pour

Then it's simple enough to execute a command and see the output in realtime:

const { pour } = require('std-pour');
pour('ping', ['8.8.8.8', '-c', '4']).then(code => console.log(`Error Code: ${code}`));

It's promised based so you can chain multiple commands. It's even function signature-compatible with child_process.spawn so it should be a drop in replacement anywhere you're using it.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

How can I make content appear beneath a fixed DIV element?

I liked grdevphl's Javascript answer best, but in my own use case, I found that using height() in the calculation still left a little overlap since it didn't take padding into account. If you run into the same issue, try outerHeight() instead to compensate for padding and border.

$(document).ready(function() {
    var contentPlacement = $('#header').position().top + $('#header').outerHeight();
    $('#content').css('margin-top',contentPlacement);
});

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

How to get UTF-8 working in Java webapps?

This is for Greek Encoding in MySql tables when we want to access them using Java:

Use the following connection setup in your JBoss connection pool (mysql-ds.xml)

<connection-url>jdbc:mysql://192.168.10.123:3308/mydatabase</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>nts</user-name>
<password>xaxaxa!</password>
<connection-property name="useUnicode">true</connection-property>
<connection-property name="characterEncoding">greek</connection-property>

If you don't want to put this in a JNDI connection pool, you can configure it as a JDBC-url like the next line illustrates:

jdbc:mysql://192.168.10.123:3308/mydatabase?characterEncoding=greek

For me and Nick, so we never forget it and waste time anymore.....

C#: Dynamic runtime cast

This should work:

public static dynamic Cast(dynamic obj, Type castTo)
{
    return Convert.ChangeType(obj, castTo);
}

Edit

I've written the following test code:

var x = "123";
var y = Cast(x, typeof(int));
var z = y + 7;
var w = Cast(z, typeof(string)); // w == "130"

It does resemble the kind of "typecasting" one finds in languages like PHP, JavaScript or Python (because it also converts the value to the desired type). I don't know if that's a good thing, but it certainly works... :-)

How to reset AUTO_INCREMENT in MySQL?

ALTER TABLE news_feed DROP id

ALTER TABLE news_feed ADD  id BIGINT( 200 ) NOT NULL AUTO_INCREMENT FIRST ,ADD PRIMARY KEY (id)

I used this in some of my scripts , the id field is droped and then added back with previous settings , all the existent fields within the database table are filled in with new auto increment values , this should also work with InnoDB .

Note that all the fields within the table will be recounted and will have other ids !!!.

How to set background image of a view?

It's a very bad idea to directly display any text on an irregular and ever changing background. No matter what you do, some of the time the text will be hard to read.

The best design would be to have the labels on a constant background with the images changing behind that.

You can set the labels background color from clear to white and set the from alpha to 50.0 you get a nice translucent effect. The only problem is that the label's background is a stark rectangle.

To get a label with a background with rounded corners you can use a button with user interaction disabled but the user might mistake that for a button.

The best method would be to create image of the label background you want and then put that in an imageview and put the label with the default transparent background onto of that.

Plain UIViews do not have an image background. Instead, you should make a UIImageView your main view and then rotate the images though its image property. If you set the UIImageView's mode to "Scale to fit" it will scale any image to fit the bounds of the view.

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

Not all of them are required (I think), but after installing the components listed below I got the "Dynamic Web Project" template added to my Eclipse (Indigo). The list is:

  • Eclipse Java EE Developer Tools
  • Eclipse Java Web Developer Tools
  • Eclipse Web Developer Tools
  • Eclipse XML Editors and Tools

You can install those packages by clicking on "Help" > "Install New Software", selecting the repository that corresponds to your Eclipse build (i.e http://download.eclipse.org/releases/indigo for Indigo). The packages are grouped under "Web, XML, Java EE and OSGi Enterprise Development".

Full Screen Theme for AppCompat

Issues arise among before and after versions of Android 4.0 (API level 14).

from here I created my own solution.

@SuppressLint("NewApi")
@Override
protected void onResume()
{
    super.onResume();

    if (Build.VERSION.SDK_INT < 16)
    {
        // Hide the status bar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // Hide the action bar
        getSupportActionBar().hide();
    }
    else
    {
        // Hide the status bar
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        / Hide the action bar
        getActionBar().hide();
    }
}

I write this code in onResume() method because if you exit from your app and then you reopen it, the action bar remains active! (and so this fix the problem)

I hope it was helpful ;)

How to set default value for HTML select?

You first need to add values to your select options and for easy targetting give the select itself an id.

Let's make option b the default:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.

Unable to open debugger port in IntelliJ IDEA

I have the same issue,because my computer's DNS miss 127.0.0.1 localhost. When I add 127.0.0.1 localhost to my host file,it become ok.

Difference between "this" and"super" keywords in Java

When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:

MyClass()
{
   this(default1, default2);
}

MyClass(arg1, arg2)
{
   validate arguments, etc...
   note that your validation logic is only written once now
}

As for the super() constructor, again unlike super.method() access it must be the first line of your constructor. After that it is very much like the this() constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:

YourClass extends MyClass
{
   YourClass(arg1, arg2, arg3)
   {
      super(arg1, arg2) // calls MyClass(arg1, arg2)
      validate and process arg3...
   }
}

Additional information:

Even though you don't see it, the default no argument constructor always calls super() first. Example:

MyClass()
{
}

is equivalent to

MyClass()
{
   super();
}

I see that many have mentioned using the this and super keywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.

FFmpeg on Android

For various reasons, Multimedia was and is never easy in terms of achieving the task without compromising on efficiency. ffmpeg is an effort in improving it day by day. It supports different formats of codecs and containers.

Now to answer the question of how to use this library, i would say that it is not so simple to write it here. But i can guide you in following ways.

1) Inside the ffmpeg directory of source code, you have output_example.c or api_example.c. Here, you can see the code where encoding/decoding is done. You will get an idea as to which API's inside ffmpeg you should call. This would be your first step.

2) Dolphin player is a open source project for Android. Currently it is having bugs but developers are working continuously. In that project you have the whole setup ready which you can use to continue your investigation. Here is a link to the project from code.google.com or run the command "git clone https://code.google.com/p/dolphin-player/" in a terminal. You can see two projects named P and P86 . You can use either of them.

Extra tip i would like to offer is that when you are building the ffmpeg code, inside build.sh you need to enable the muxers/demuxers/encoders/decoders of the formats you want to use. Else the corresponding code will not be included in the libraries. It took a lot of time for me to realize this. So thought of sharing it with you.

Few Basics : When we say a video file, ex : avi, it is combination of both audio and video

Video file = Video + Audio


Video = Codec + Muxer + Demuxer

codec = encoder + Decoder

=> Video = encoder + decoder + Muxer + Demuxer(Mpeg4 + Mpeg4 + avi +avi - Example for avi container)


Audio = Codec + Muxer + Demuxer

codec = encoder + Decoder

=> Audio = encoder + decoder + Muxer + Demuxer(mp2 + mp2 + avi + avi - Example for avi container)


Codec(name is deriverd from a combination of en*co*der/*dec*oder) is just a part of format which defines the algorithms used to encode/decode a frame. AVI is not a codec, it is a container which uses Video codec of Mpeg4 and Audio codec of mp2.

Muxer/demuxer is used to combine/separate the frames from a file used while encoding/decoding.

So if you want to use avi format, you need to enable Video components + Audio components.

Ex, for avi, you need to enable the following. mpeg4 Encoder, mpeg4 decoder, mp2 encoder, mp2 decoder, avi muxer, avi demuxer.

phewwwwwww...

Programmatically build.sh should contain the following code:

--enable-muxer=avi --enable-demuxer=avi (Generic for both audio/video. generally Specific to a container)
--enable-encoder=mpeg4 --enable-decoder=mpeg4(For video support)
--enable-encoder=mp2 --enable-decoder=mp2 (For Audio support)

Hope i idid not confuse you more after all this...

Thanks, Any assistance needed, please let me know.

How can I check whether an array is null / empty?

I believe that what you want is

int[] k = new int[3];

if (k != null) {  // Note, != and not == as above
    System.out.println(k.length);
}

You newed it up so it was never going to be null.

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

Quiet Late though!.

This method is properly tested and it converts the excel to DataSet.

public DataSet Dtl()
        {
            //Instance reference for Excel Application
            Microsoft.Office.Interop.Excel.Application objXL = null;        
            //Workbook refrence
            Microsoft.Office.Interop.Excel.Workbook objWB = null;
            DataSet ds = new DataSet();
            try
            {
                objXL = new Microsoft.Office.Interop.Excel.Application();
                objWB = objXL.Workbooks.Open(@"Book1.xlsx");//Your path to excel file.
                foreach (Microsoft.Office.Interop.Excel.Worksheet objSHT in objWB.Worksheets)
                {
                    int rows = objSHT.UsedRange.Rows.Count;
                    int cols = objSHT.UsedRange.Columns.Count;
                    DataTable dt = new DataTable();
                    int noofrow = 1;
                    //If 1st Row Contains unique Headers for datatable include this part else remove it
                    //Start
                    for (int c = 1; c <= cols; c++)
                    {
                        string colname = objSHT.Cells[1, c].Text;
                        dt.Columns.Add(colname);
                        noofrow = 2;
                    }
                    //END
                    for (int r = noofrow; r <= rows; r++)
                    {
                        DataRow dr = dt.NewRow();
                        for (int c = 1; c <= cols; c++)
                        {
                            dr[c - 1] = objSHT.Cells[r, c].Text;
                        }
                        dt.Rows.Add(dr);
                    }
                   ds.Tables.Add(dt);
                }
                //Closing workbook
                objWB.Close();
                //Closing excel application
                objXL.Quit();
                return ds;
            }

            catch (Exception ex)
            {
               objWB.Saved = true;
                //Closing work book
                objWB.Close();
                //Closing excel application
                objXL.Quit();
                //Response.Write("Illegal permission");
                return ds;
            }
        }

How do I send a POST request as a JSON?

Here is an example of how to use urllib.request object from Python standard library.

import urllib.request
import json
from pprint import pprint

url = "https://app.close.com/hackwithus/3d63efa04a08a9e0/"

values = {
    "first_name": "Vlad",
    "last_name": "Bezden",
    "urls": [
        "https://twitter.com/VladBezden",
        "https://github.com/vlad-bezden",
    ],
}


headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
}

data = json.dumps(values).encode("utf-8")
pprint(data)

try:
    req = urllib.request.Request(url, data, headers)
    with urllib.request.urlopen(req) as f:
        res = f.read()
    pprint(res.decode())
except Exception as e:
    pprint(e)

Bootstrap dropdown menu not working (not dropping down when clicked)

Just Remove the type="text/javascript"

<script src="JavaScript/jquery.js" />
<script src="JavaScript/bootstrap-min.js" />

Here is the update - http://jsfiddle.net/andieje/kRX6n/

Get the first item from an iterable that matches a condition

Damn Exceptions!

I love this answer. However, since next() raise a StopIteration exception when there are no items, i would use the following snippet to avoid an exception:

a = []
item = next((x for x in a), None)

For example,

a = []
item = next(x for x in a)

Will raise a StopIteration exception;

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Unable to connect to any of the specified mysql hosts. C# MySQL

In my case by removing portion "port=3306;" from the connection string solved the problem.

How do I query between two dates using MySQL?

Just Cast date_field as date

SELECT * FROM `objects` 
WHERE (cast(date_field as date) BETWEEN '2010-09-29' AND 
'2010-01-30' )

Why does the jquery change event not trigger when I set the value of a select using val()?

Because the change event requires an actual browser event initiated by the user instead of via javascript code.

Do this instead:

$("#single").val("Single2").trigger('change');

or

$("#single").val("Single2").change();

How do you move a file?

Transferring a file using TortoiseSVN:

Step:1 Please Select the files which you want to move, Right-click and drag the files to the folder which you to move them to, A window will popup after follow the below instruction

SVN option

Step 2: After you click the above the commit the file as below mention

SVN Commit

Remove an onclick listener

Note that if a view is non-clickable (a TextView for example), setting setOnClickListener(null) will mean the view is clickable. Use mMyView.setClickable(false) if you don't want your view to be clickable. For example, if you use a xml drawable for the background, which shows different colours for different states, if your view is still clickable, users can click on it and the different background colour will show, which may look weird.

How to get exact browser name and version?

Use get_browser()

From Manual:

echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);

Will return:

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*/
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

PhpMyAdmin not working on localhost

STOP ALL SERVICES OF XAMPP Edit Apache(httpd.conf) file 1)"Listen 80" if its already 80 and not working then replace it by 81 2) "ServerName localhost:80" if its already 80 and not working then replace it by 81 SAVE EXIT RESTART [WINDOWS USER run as administrator]

"Cloning" row or column vectors

First note that with numpy's broadcasting operations it's usually not necessary to duplicate rows and columns. See this and this for descriptions.

But to do this, repeat and newaxis are probably the best way

In [12]: x = array([1,2,3])

In [13]: repeat(x[:,newaxis], 3, 1)
Out[13]: 
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

In [14]: repeat(x[newaxis,:], 3, 0)
Out[14]: 
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

This example is for a row vector, but applying this to a column vector is hopefully obvious. repeat seems to spell this well, but you can also do it via multiplication as in your example

In [15]: x = array([[1, 2, 3]])  # note the double brackets

In [16]: (ones((3,1))*x).transpose()
Out[16]: 
array([[ 1.,  1.,  1.],
       [ 2.,  2.,  2.],
       [ 3.,  3.,  3.]])

Java rounding up to an int using Math.ceil

Nobody has mentioned the most intuitive:

int x = (int) Math.round(Math.ceil((double) 157 / 32));

This solution fixes the double division imprecision.

How can I suppress all output from a command using Bash?

In your script you can add the following to the lines that you know are going to give an output:

some_code 2>>/dev/null

Or else you can also try

some_code >>/dev/null

A hex viewer / editor plugin for Notepad++?

There is an old plugin called HEX Editor here.

According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.

How to represent a DateTime in Excel

Excel expects dates and times to be stored as a floating point number whose value depends on the Date1904 setting of the workbook, plus a number format such as "mm/dd/yyyy" or "hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" so that the number is displayed to the user as a date / time.

Using SpreadsheetGear for .NET you can do this: worksheet.Cells["A1"].Value = DateTime.Now;

This will convert the DateTime to a double which is the underlying type which Excel uses for a Date / Time, and then format the cell with a default date and / or time number format automatically depending on the value.

SpreadsheetGear also has IWorkbook.DateTimeToNumber(DateTime) and NumberToDateTime(double) methods which convert from .NET DateTime objects to a double which Excel can use.

I would expect XlsIO to have something similar.

Disclaimer: I own SpreadsheetGear LLC

How to check empty object in angular 2 template using *ngIf

A bit of a lengthier way (if interested in it):

In your typescript code do this:

this.objectLength = Object.keys(this.previous_info).length != 0;

And in the template:

ngIf="objectLength != 0"

TSQL - Cast string to integer or return default value

Yes :). Try this:

DECLARE @text AS NVARCHAR(10)

SET @text = '100'
SELECT CASE WHEN ISNUMERIC(@text) = 1 THEN CAST(@text AS INT) ELSE NULL END
-- returns 100

SET @text = 'XXX'
SELECT CASE WHEN ISNUMERIC(@text) = 1 THEN CAST(@text AS INT) ELSE NULL END
-- returns NULL

ISNUMERIC() has a few issues pointed by Fedor Hajdu.

It returns true for strings like $ (is currency), , or . (both are separators), + and -.

Returning first x items from array

array_splice — Remove a portion of the array and replace it with something else:

$input = array(1, 2, 3, 4, 5, 6);
array_splice($input, 5); // $input is now array(1, 2, 3, 4, 5)

From PHP manual:

array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement]])

If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length .

Which programming languages can be used to develop in Android?

  • At launch, Java was the only officially supported programming language for building distributable third-party Android software.

  • Android Native Development Kit (Android NDK) which will allow developers to build Android software components with C and C++.

  • In addition to delivering support for native code, Google is also extending Android to support popular dynamic scripting languages. Earlier this month, Google launched the Android Scripting Environment (ASE) which allows third-party developers to build simple Android applications with perl, JRuby, Python, LUA and BeanShell. For having idea and usage of ASE, refer this Example link.

  • Scala is also supported. For having examples of Scala, refer these Example link-1 , Example link-2 , Example link-3 .

  • Just now i have referred one Article Here in which i found some useful information as follows:

    1. programming language is Java but bridges from other languages exist (C# .net - Mono, etc).
    2. can run script languages like LUA, Perl, Python, BeanShell, etc.

  • I have read 2nd article at Google Releases 'Simple' Android Programming Language . For example of this, refer this .

  • Just now (2 Aug 2010) i have read an article which describes regarding "Frink Programming language and Calculating Tool for Android", refer this links Link-1 , Link-2

  • On 4-Aug-2010, i have found Regarding RenderScript. Basically, It is said to be a C-like language for high performance graphics programming, which helps you easily write efficient Visual effects and animations in your Android Applications. Its not released yet as it isn't finished.

Remove innerHTML from div


var $div = $('#desiredDiv');
$div.contents().remove();
$div.html('<p>This is new HTML.</p>');

That should work just fine.

null terminating a string

To your first question: I would go with Paul R's comment and terminate with '\0'. But the value 0 itself works also fine. A matter of taste. But don't use the MACRO NULLwhich is meant for pointers.

To your second question: If your string is not terminated with\0, it might still print the expected output because following your string is a non-printable character in your memory. This is a really nasty bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'.

Best data type to store money values in MySQL

It depends on your need.

Using DECIMAL(10,2) usually is enough but if you need a little bit more precise values you can set DECIMAL(10,4).

If you work with big values replace 10 with 19.

rotating axis labels in R

Not sure if this is what you mean, but try setting las=1. Here's an example:

require(grDevices)
tN <- table(Ni <- stats::rpois(100, lambda=5))
r <- barplot(tN, col=rainbow(20), las=1)

output

That represents the style of axis labels. (0=parallel, 1=all horizontal, 2=all perpendicular to axis, 3=all vertical)

get size of json object

Consider using underscore.js. It will allow you to check the size i.e. like that:

var data = {one : 1, two : 2, three : 3};
_.size(data);
//=> 3
_.keys(data);
//=> ["one", "two", "three"]
_.keys(data).length;
//=> 3

Updating property value in properties file without deleting other values

You can use Apache Commons Configuration library. The best part of this is, it won't even mess up the properties file and keeps it intact (even comments).

Javadoc

PropertiesConfiguration conf = new PropertiesConfiguration("propFile.properties");
conf.setProperty("key", "value");
conf.save();    

Is the order of elements in a JSON list preserved?

Some JavaScript engines keep keys in insertion order. V8, for instance, keeps all keys in insertion order except for keys that can be parsed as unsigned 32-bit integers.

This means that if you run either of the following:

var animals = {};
animals['dog'] = true;
animals['bear'] = true;
animals['monkey'] = true;
for (var animal in animals) {
  if (animals.hasOwnProperty(animal)) {
    $('<li>').text(animal).appendTo('#animals');
  }
}
var animals = JSON.parse('{ "dog": true, "bear": true, "monkey": true }');
for (var animal in animals) {
  $('<li>').text(animal).appendTo('#animals');
}

You'll consistently get dog, bear, and monkey in that order, on Chrome, which uses V8. Node.js also uses V8. This will hold true even if you have thousands of items. YMMV with other JavaScript engines.

Demo here and here.

Alter table add multiple columns ms sql

Take out the parentheses and the curly braces, neither are required when adding columns.

Resize svg when window is resized in d3.js

In force layouts simply setting the 'height' and 'width' attributes will not work to re-center/move the plot into the svg container. However, there's a very simple answer that works for Force Layouts found here. In summary:

Use same (any) eventing you like.

window.on('resize', resize);

Then assuming you have svg & force variables:

var svg = /* D3 Code */;
var force = /* D3 Code */;    

function resize(e){
    // get width/height with container selector (body also works)
    // or use other method of calculating desired values
    var width = $('#myselector').width(); 
    var height = $('#myselector').height(); 

    // set attrs and 'resume' force 
    svg.attr('width', width);
    svg.attr('height', height);
    force.size([width, height]).resume();
}

In this way, you don't re-render the graph entirely, we set the attributes and d3 re-calculates things as necessary. This at least works when you use a point of gravity. I'm not sure if that's a prerequisite for this solution. Can anyone confirm or deny ?

Cheers, g

Outline effect to text

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

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

Can I get "&&" or "-and" to work in PowerShell?

We can try this command instead of using && method:

try {hostname; if ($lastexitcode -eq 0) {ipconfig /all | findstr /i bios}} catch {echo err} finally {}

How to config routeProvider and locationProvider in angularJS?

you could try:

<a href="#/controllerone">Controller One</a>||
<a href="#/controllerTwo">Controller Two</a>||
<a href="#/controllerThree">Controller Three</a>

<div>
    <div ng-view=""></div>
</div>

C++: constructor initializer for arrays

You can use C++0x auto keyword together with template specialization on for example a function named boost::make_array() (similar to make_pair()). For the case of where N is either 1 or 2 arguments we can then write variant A as

namespace boost
{
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
    return boost::array<T,2> ({{ a }});
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
    return boost::array<T,2> ({{ a, b }});
}
}

and variant B as

namespace boost {
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
    boost::array<T,1> x;
    x[0] = a;
    return x;
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
    boost::array<T,2> x;
    x[0] = a;
    x[1] = b;
    return x;
}
}

GCC-4.6 with -std=gnu++0x and -O3 generates the exact same binary code for

auto x = boost::make_array(1,2);

using both A and B as it does for

boost::array<int, 2> x = {{1,2}};

For user defined types (UDT), though, variant B results in an extra copy constructor, which usually slow things down, and should therefore be avoided.

Note that boost::make_array errors when calling it with explicit char array literals as in the following case

auto x = boost::make_array("a","b");

I believe this is a good thing as const char* literals can be deceptive in their use.

Variadic templates, available in GCC since 4.5, can further be used reduce all template specialization boiler-plate code for each N into a single template definition of boost::make_array() defined as

/*! Construct Array from @p a, @p b. */
template <typename T, typename ... R>
boost::array<T,1+sizeof...(R)> make_array(T a, const R & ... b)
{
    return boost::array<T,1+sizeof...(R)>({{ a, b... }});
}

This works pretty much as we expect. The first argument determines boost::array template argument T and all other arguments gets converted into T. For some cases this may undesirable, but I'm not sure how if this is possible to specify using variadic templates.

Perhaps boost::make_array() should go into the Boost Libraries?

CSS horizontal scroll

Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html

<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {  
    overflow: scroll;  
    width:100%;
}
#outer_wrapper #inner_wrapper {
    width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
    width: 250px;
    height:300px;
    float: left;
    margin: 0 4px 0 0;
    border:1px grey solid;
}
</style>
</head>
<body>

<div id="outer_wrapper">
    <div id="inner_wrapper">
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <!-- more boxes here -->
    </div>
</div>
</body>
</html>

Android view layout_width - how to change programmatically?

I believe your question is to change only width of view dynamically, whereas above methods will change layout properties completely to new one, so I suggest to getLayoutParams() from view first, then set width on layoutParams, and finally set layoutParams to the view, so following below steps to do the same.

View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);

How to test abstract class in Java with JUnit?

With the example class you posted it doesn't seem to make much sense to test getFuel() and getSpeed() since they can only return 0 (there are no setters).

However, assuming that this was just a simplified example for illustrative purposes, and that you have legitimate reasons to test methods in the abstract base class (others have already pointed out the implications), you could setup your test code so that it creates an anonymous subclass of the base class that just provides dummy (no-op) implementations for the abstract methods.

For example, in your TestCase you could do this:

c = new Car() {
       void drive() { };
   };

Then test the rest of the methods, e.g.:

public class CarTest extends TestCase
{
    private Car c;

    public void setUp()
    {
        c = new Car() {
            void drive() { };
        };
    }

    public void testGetFuel() 
    {
        assertEquals(c.getFuel(), 0);
    }

    [...]
}

(This example is based on JUnit3 syntax. For JUnit4, the code would be slightly different, but the idea is the same.)

How to determine equality for two JavaScript objects?

The default equality operator in JavaScript for Objects yields true when they refer to the same location in memory.

var x = {};
var y = {};
var z = x;

x === y; // => false
x === z; // => true

If you require a different equality operator you'll need to add an equals(other) method, or something like it to your classes and the specifics of your problem domain will determine what exactly that means.

Here's a playing card example:

function Card(rank, suit) {
  this.rank = rank;
  this.suit = suit;
  this.equals = function(other) {
     return other.rank == this.rank && other.suit == this.suit;
  };
}

var queenOfClubs = new Card(12, "C");
var kingOfSpades = new Card(13, "S");

queenOfClubs.equals(kingOfSpades); // => false
kingOfSpades.equals(new Card(13, "S")); // => true

How to call any method asynchronously in c#

public partial class MainForm : Form
{
    Image img;
    private void button1_Click(object sender, EventArgs e)
    {
        LoadImageAsynchronously("http://media1.santabanta.com/full5/Indian%20%20Celebrities(F)/Jacqueline%20Fernandez/jacqueline-fernandez-18a.jpg");
    }

    private void LoadImageAsynchronously(string url)
    {
        /*
        This is a classic example of how make a synchronous code snippet work asynchronously.
        A class implements a method synchronously like the WebClient's DownloadData(…) function for example
            (1) First wrap the method call in an Anonymous delegate.
            (2) Use BeginInvoke(…) and send the wrapped anonymous delegate object as the last parameter along with a callback function name as the first parameter.
            (3) In the callback method retrieve the ar's AsyncState as a Type (typecast) of the anonymous delegate. Along with this object comes EndInvoke(…) as free Gift
            (4) Use EndInvoke(…) to retrieve the synchronous call’s return value in our case it will be the WebClient's DownloadData(…)’s return value.
        */
        try
        {
            Func<Image> load_image_Async = delegate()
            {
                WebClient wc = new WebClient();
                Bitmap bmpLocal = new Bitmap(new MemoryStream(wc.DownloadData(url)));
                wc.Dispose();
                return bmpLocal;
            };

            Action<IAsyncResult> load_Image_call_back = delegate(IAsyncResult ar)
            {
                Func<Image> ss = (Func<Image>)ar.AsyncState;
                Bitmap myBmp = (Bitmap)ss.EndInvoke(ar);

                if (img != null) img.Dispose();
                if (myBmp != null)
                    img = myBmp;
                Invalidate();
                //timer.Enabled = true;
            };
            //load_image_Async.BeginInvoke(callback_load_Image, load_image_Async);             
            load_image_Async.BeginInvoke(new AsyncCallback(load_Image_call_back), load_image_Async);             
        }
        catch (Exception ex)
        {

        }
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        if (img != null)
        {
            Graphics grfx = e.Graphics;
            grfx.DrawImage(img,new Point(0,0));
        }
    }

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

What's causing my java.net.SocketException: Connection reset?

This error happens on your side and NOT the other side. If the other side reset the connection, then the exception message should say:

java.net.SocketException reset by peer

The cause is the connection inside HttpClient is stale. Check stale connection for SSL does not fix this error. Solution: dump your client and recreate.

Delete files in subfolder using batch script

I had to complete the same task and I used a "for" loop and a "del" command as follows:

@ECHO OFF

set dir=%cd%

FOR /d /r %dir% %%x in (archive\) do (
    if exist "%%x" del %%x\*.txt /f /q
)

You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.

These are the options for "for" command:

  • /d For directories
  • /r For recursive

These are the options for "del" command:

  • /f Force deletes read-only files
  • /q Quiet mode; suppresses prompts for delete confirmations.

What is the difference between --save and --save-dev?

Let me give you an example,

  • You are a developer of a very SERIOUS npm library. Which uses different testing libraries to test the package.
  • An user Downloaded your library and want to use it in their code. Do they need to download your testing libraries as well? Maybe you use jest for testing and they use mocha. Do you want them to install jest as well? Just To run your library?

No. right? That's why they are in devDependencies.

When someone does, npm i yourPackage only the libraries required to RUN your library will be installed. Other libraries you used to bundle your code with or testing and mocking will not be installed because you put them in devDependencies. Pretty neat right?

So, Why do the developers need to expose the devDependancies?

Let's say your package is an open source package and 100s of people are sending pull requests to your package. Then how they will test the package? They will git clone your repo and when they would do an npm i the dependencies as well as devDependencies.
Because they are not using your package. They are developing the package further, thus, in order to test your package they need to pass the existing test cases as well write new. So, they need to use your devDependencies which contain all the testing/building/mocking libraries that YOU used.

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

You can view which modules (compiled in) are available via terminal through php -m

How to comment multiple lines in Visual Studio Code?

In Windows

Select the lines you want to comment. Then press Ctrl + /

ImportError: No module named matplotlib.pyplot

I had a similar problem, using pip3 and all these things worked for installing matplotlib but not pyplot. This solved it for me:

import matplotlib as plt
from matplotlib import pyplot as pllt

Flutter: Run method on Widget build complete

Flutter 1.2 - dart 2.2

According with the official guidelines and sources if you want to be certain that also the last frame of your layout was drawned you can write for example:

import 'package:flutter/scheduler.dart';

void initState() {
   super.initState();
   if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
        SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));
   }
}

How to extract an assembly from the GAC?

Yes.

Add DisableCacheViewer Registry Key

Create a new dword key under HKLM\Software\Microsoft\Fusion\ with the name DisableCacheViewer and set it’s [DWORD] value to 1.

Go back to Windows Explorer to the assembly folder and it will be the normal file system view.

Init method in Spring Controller (annotation version)

There are several ways to intercept the initialization process in Spring. If you have to initialize all beans and autowire/inject them there are at least two ways that I know of that will ensure this. I have only testet the second one but I belive both work the same.

If you are using @Bean you can reference by initMethod, like this.

@Configuration
public class BeanConfiguration {

  @Bean(initMethod="init")
  public BeanA beanA() {
    return new BeanA();
  }
}

public class BeanA {

  // method to be initialized after context is ready
  public void init() {
  }

} 

If you are using @Component you can annotate with @EventListener like this.

@Component
public class BeanB {

  @EventListener
  public void onApplicationEvent(ContextRefreshedEvent event) {
  }
}

In my case I have a legacy system where I am now taking use of IoC/DI where Spring Boot is the choosen framework. The old system brings many circular dependencies to the table and I therefore must use setter-dependency a lot. That gave me some headaches since I could not trust @PostConstruct since autowiring/injection by setter was not yet done. The order is constructor, @PostConstruct then autowired setters. I solved it with @EventListener annotation which wil run last and at the "same" time for all beans. The example shows implementation of InitializingBean aswell.

I have two classes (@Component) with dependency to each other. The classes looks the same for the purpose of this example displaying only one of them.

@Component
public class BeanA implements InitializingBean {
  private BeanB beanB;

  public BeanA() {
    log.debug("Created...");
  }

  @PostConstruct
  private void postConstruct() {
    log.debug("@PostConstruct");
  }

  @Autowired
  public void setBeanB(BeanB beanB) {
    log.debug("@Autowired beanB");
    this.beanB = beanB;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    log.debug("afterPropertiesSet()");
  }

  @EventListener
  public void onApplicationEvent(ContextRefreshedEvent event) {
    log.debug("@EventListener");
  } 
}

This is the log output showing the order of the calls when the container starts.

2018-11-30 18:29:30.504 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : Created...
2018-11-30 18:29:30.509 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : Created...
2018-11-30 18:29:30.517 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @Autowired beanA
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : afterPropertiesSet()
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @Autowired beanB
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : afterPropertiesSet()
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @EventListener
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @EventListener

As you can see @EventListener is run last after everything is ready and configured.

$on and $broadcast in angular

If you want to $broadcast use the $rootScope:

$scope.startScanner = function() {

    $rootScope.$broadcast('scanner-started');
}

And then to receive, use the $scope of your controller:

$scope.$on('scanner-started', function(event, args) {

    // do what you want to do
});

If you want you can pass arguments when you $broadcast:

$rootScope.$broadcast('scanner-started', { any: {} });

And then receive them:

$scope.$on('scanner-started', function(event, args) {

    var anyThing = args.any;
    // do what you want to do
});

Documentation for this inside the Scope docs.

Spring Boot application can't resolve the org.springframework.boot package

Solution is change the version of Spring in file pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>

Preventing twitter bootstrap carousel from auto sliding on page load

Below are the list of parameters for bootstrap carousel. Like Interval, pause, wrap:

enter image description here

For more details refer this link:

http://www.w3schools.com/bootstrap/bootstrap_ref_js_carousel.asp

Hope this will help you :)

Note: This is for further help. I mean how you can customise or change default behaviour once carousel is loaded.

Open the terminal in visual studio?

For Microsoft Visual Studio Community 2017 use Ctrl+Alt+A

Alternatively from command panel view -> Other Windows -> Command Window

Command Window menu

get all keys set in memcached

Bash

To get list of keys in Bash, follow the these steps.

First, define the following wrapper function to make it simple to use (copy and paste into shell):

function memcmd() {
  exec {memcache}<>/dev/tcp/localhost/11211
  printf "%s\n%s\n" "$*" quit >&${memcache}
  cat <&${memcache}
}

Memcached 1.4.31 and above

You can use lru_crawler metadump all command to dump (most of) the metadata for (all of) the items in the cache.

As opposed to cachedump, it does not cause severe performance problems and has no limits on the amount of keys that can be dumped.

Example command by using the previously defined function:

memcmd lru_crawler metadump all

See: ReleaseNotes1431.


Memcached 1.4.30 and below

Get list of slabs by using items statistics command, e.g.:

memcmd stats items

For each slub class, you can get list of items by specifying slub id along with limit number (0 - unlimited):

memcmd stats cachedump 1 0
memcmd stats cachedump 2 0
memcmd stats cachedump 3 0
memcmd stats cachedump 4 0
...

Note: You need to do this for each memcached server.

To list all the keys from all stubs, here is the one-liner (per one server):

for id in $(memcmd stats items | grep -o ":[0-9]\+:" | tr -d : | sort -nu); do
    memcmd stats cachedump $id 0
done

Note: The above command could cause severe performance problems while accessing the items, so it's not advised to run on live.


Notes:

stats cachedump only dumps the HOT_LRU (IIRC?), which is managed by a background thread as activity happens. This means under a new enough version which the 2Q algo enabled, you'll get snapshot views of what's in just one of the LRU's.

If you want to view everything, lru_crawler metadump 1 (or lru_crawler metadump all) is the new mostly-officially-supported method that will asynchronously dump as many keys as you want. you'll get them out of order but it hits all LRU's, and unless you're deleting/replacing items multiple runs should yield the same results.

Source: GH-405.


Related:

fetch from origin with deleted remote branches?

From http://www.gitguys.com/topics/adding-and-removing-remote-branches/

After someone deletes a branch from a remote repository, git will not automatically delete the local repository branches when a user does a git pull or git fetch. However, if the user would like to have all tracking branches removed from their local repository that have been deleted in a remote repository, they can type:

git remote prune origin

As a note, the -p param from git fetch -p actually means "prune".
Either way you chose, the non-existing remote branches will be deleted from your local repository.

Serializing class instance to JSON

There's one way that works great for me that you can try out:

json.dumps() can take an optional parameter default where you can specify a custom serializer function for unknown types, which in my case looks like

def serialize(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, date):
        serial = obj.isoformat()
        return serial

    if isinstance(obj, time):
        serial = obj.isoformat()
        return serial

    return obj.__dict__

First two ifs are for date and time serialization and then there is a obj.__dict__ returned for any other object.

the final call looks like:

json.dumps(myObj, default=serialize)

It's especially good when you are serializing a collection and you don't want to call __dict__ explicitly for every object. Here it's done for you automatically.

So far worked so good for me, looking forward for your thoughts.

Why is 1/1/1970 the "epoch time"?

http://en.wikipedia.org/wiki/Unix_time#History explains a little about the origins of Unix time and the chosen epoch. The definition of unix time and the epoch date went through a couple of changes before stabilizing on what it is now.

But it does not say why exactly 1/1/1970 was chosen in the end.

Notable excerpts from the Wikipedia page:

The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".

Because of [the] limited range, the epoch was redefined more than once, before the rate was changed to 1 Hz and the epoch was set to its present value.

Several later problems, including the complexity of the present definition, result from Unix time having been defined gradually by usage rather than fully defined to start with.

Laravel Controller Subfolder routing

For those using Laravel 5 you need to set the namespace for the controller within the sub-directory (Laravel 5 is still in development and changes are happening daily)

To get a folder structure like:

Http
----Controllers
    ----Admin
            PostsController.php
    PostsController.php

namespace Admin\PostsController.php file like so:

<?php namespace App\Http\Controller\Admin;

use App\Http\Controllers\Controller;

class PostsController extends Controller {

    //business logic here
}

Then your route for this is:

$router->get('/', 'Admin\PostsController@index');

And lastly, don't for get to do either composer or artisan dump

composer dump-autoload

or

php artisan dump

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

I use these methods in my personal library:

Array.prototype.sum = Array.prototype.sum || function() {
  return this.reduce(function(sum, a) { return sum + Number(a) }, 0);
}

Array.prototype.average = Array.prototype.average || function() {
  return this.sum() / (this.length || 1);
}

EDIT: To use them, simply ask the array for its sum or average, like:

[1,2,3].sum() // = 6
[1,2,3].average() // = 2

must appear in the GROUP BY clause or be used in an aggregate function

Yes, this is a common aggregation problem. Before SQL3 (1999), the selected fields must appear in the GROUP BY clause[*].

To workaround this issue, you must calculate the aggregate in a sub-query and then join it with itself to get the additional columns you'd need to show:

SELECT m.cname, m.wmname, t.mx
FROM (
    SELECT cname, MAX(avg) AS mx
    FROM makerar
    GROUP BY cname
    ) t JOIN makerar m ON m.cname = t.cname AND t.mx = m.avg
;

 cname  | wmname |          mx           
--------+--------+------------------------
 canada | zoro   |     2.0000000000000000
 spain  | usopp  |     5.0000000000000000

But you may also use window functions, which looks simpler:

SELECT cname, wmname, MAX(avg) OVER (PARTITION BY cname) AS mx
FROM makerar
;

The only thing with this method is that it will show all records (window functions do not group). But it will show the correct (i.e. maxed at cname level) MAX for the country in each row, so it's up to you:

 cname  | wmname |          mx           
--------+--------+------------------------
 canada | zoro   |     2.0000000000000000
 spain  | luffy  |     5.0000000000000000
 spain  | usopp  |     5.0000000000000000

The solution, arguably less elegant, to show the only (cname, wmname) tuples matching the max value, is:

SELECT DISTINCT /* distinct here matters, because maybe there are various tuples for the same max value */
    m.cname, m.wmname, t.avg AS mx
FROM (
    SELECT cname, wmname, avg, ROW_NUMBER() OVER (PARTITION BY avg DESC) AS rn 
    FROM makerar
) t JOIN makerar m ON m.cname = t.cname AND m.wmname = t.wmname AND t.rn = 1
;


 cname  | wmname |          mx           
--------+--------+------------------------
 canada | zoro   |     2.0000000000000000
 spain  | usopp  |     5.0000000000000000

[*]: Interestingly enough, even though the spec sort of allows to select non-grouped fields, major engines seem to not really like it. Oracle and SQLServer just don't allow this at all. Mysql used to allow it by default, but now since 5.7 the administrator needs to enable this option (ONLY_FULL_GROUP_BY) manually in the server configuration for this feature to be supported...

Entity framework left join

adapted from MSDN, how to left join using EF 4

var query = from u in usergroups
            join p in UsergroupPrices on u.UsergroupID equals p.UsergroupID into gj
            from x in gj.DefaultIfEmpty()
            select new { 
                UsergroupID = u.UsergroupID,
                UsergroupName = u.UsergroupName,
                Price = (x == null ? String.Empty : x.Price) 
            };

How to execute only one test spec with angular-cli

If you want to be able to control which files are selected from the command line, I managed to do this for Angular 7.

In summary, you need to install @angular-devkit/build-angular:browser and then create a custom webpack plugin to pass the test file regex through. For example:

angular.json - change the test builder from @angular-devkit/build-angular:browser and set a custom config file:

...

        "test": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./extra-webpack.config.js"
            },
...

extra-webpack.config.js - create a webpack configuration that reads the regex from the command line:

const webpack = require('webpack');
const FILTER = process.env.KARMA_FILTER;
let KARMA_SPEC_FILTER = '/.spec.ts$/';
if (FILTER) {
  KARMA_SPEC_FILTER = `/${FILTER}.spec.ts$/`;
}
module.exports = {
  plugins: [new webpack.DefinePlugin({KARMA_SPEC_FILTER})]
}

test.ts - edit the spec

...
// Then we find all the tests.
declare const KARMA_CONTEXT_SPEC: any;
const context = require.context('./', true, KARMA_CONTEXT_SPEC);

Then use as follows to override the default:

KARMA_FILTER='somefile-.*\.spec\.ts$' npm run test

I documented the backstory here, apologies in advance for types and mis-links. Credit to the answer above by @Aish-Anu for pointing me in the right direction.

Best Way to View Generated Source of Webpage?

[updating in response to more details in the edited question]

The problem you're running into is that, once a page is modified by ajax requests, the current HTML exists only inside the browser's DOM-- there's no longer any independent source HTML that you can validate other than what you can pull out of the DOM.

As you've observed, IE's DOM stores tags in upper case, fixes up unclosed tags, and makes lots of other alterations to the HTML it got originally. This is because browsers are generally very good at taking HTML with problems (e.g. unclosed tags) and fixing up those problems to display something useful to the user. Once the HTML has been canonicalized by IE, the original source HTML is essentially lost from the DOM's perspective, as far as I know.

Firefox most likley makes fewer of these changes, so Firebug is probably your better bet.

A final (and more labor-intensive) option may work for pages with simple ajax alterations, e.g. fetching some HTML from the server and importing this into the page inside a particular element. In that case, you can use fiddler or similar tool to manually stitch together the original HTML with the Ajax HTML. This is probably more trouble than it's worth, and is error prone, but it's one more possibility.

[Original response here to the original question]

Fiddler (http://www.fiddlertool.com/) is a free, browser-independent tool which works very well to fetch the exact HTML received by a browser. It shows you exact bytes on the wire as well as decoded/unzipped/etc content which you can feed into any HTML analysis tool. It also shows headers, timings, HTTP status, and lots of other good stuff.

You can also use fiddler to copy and rebuild requests if you want to test how a server responds to slightly different headers.

Fiddler works as a proxy server, sitting in between your browser and the website, and logs traffic going both ways.

Safely turning a JSON string into an object

I'm not sure about other ways to do it but here's how you do it in Prototype (JSON tutorial).

new Ajax.Request('/some_url', {
  method:'get',
  requestHeaders: {Accept: 'application/json'},
  onSuccess: function(transport){
    var json = transport.responseText.evalJSON(true);
  }
});

Calling evalJSON() with true as the argument sanitizes the incoming string.

How to use cookies in Python Requests

From the documentation:

  1. get cookie from response

    url = 'http://example.com/some/cookie/setting/url'
    r = requests.get(url)
    r.cookies
    

    {'example_cookie_name': 'example_cookie_value'}

  2. give cookie back to server on subsequent request

    url = 'http://httpbin.org/cookies'
    cookies = dict(cookies_are='working')
    r = requests.get(url, cookies=cookies)`
    

Pandas dataframe fillna() only some columns in place

You can select your desired columns and do it by assignment:

df[['a', 'b']] = df[['a','b']].fillna(value=0)

The resulting output is as expected:

     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

PSQLException: current transaction is aborted, commands ignored until end of transaction block

This is very weird behavior of PostgreSQL, it is even not " in-line with the PostgreSQL philosophy of forcing the user to make everything explicit" - as the exception was caught and ignored explicitly. So even this defense does not hold. Oracle in this case behaves much more user-friendly and (as for me) correctly - it leaves a choice to the developer.

OnItemClickListener using ArrayAdapter for ListView

you can use this way...

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {

          String main = listView.getSelectedItem().toString();
        }
    });

How to jump to a particular line in a huge text file?

I'm probably spoiled by abundant ram, but 15 M is not huge. Reading into memory with readlines() is what I usually do with files of this size. Accessing a line after that is trivial.

Empty responseText from XMLHttpRequest

This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.

In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.

Now sure why it worked, but it did.

Is there a simple way to use button to navigate page as a link does in angularjs

<button type="button" href="location.href='#/nameOfState'">Title on button</button>

Even more simple... (note the single quotes around the address)

How to run stored procedures in Entity Framework Core?

Create the special class according the fields in your Select query of your stored procedure. For example I will call this class ResulData

Add to context of you EF

modelBuilder.Entity<ResultData>(e =>
        {
            e.HasNoKey();
        });

And this a sample function to get data using the store procedure

public async Task<IEnumerable<ResultData>> GetDetailsData(int id, string name)
{
    var pId = new SqlParameter("@Id", id);
  var pName = new SqlParameter("@Name", name);
    return await _context.Set<ResultData>()
             .FromSqlRaw("Execute sp_GetDeailsData  @Id @Name", parameters: new[] { pId, pName })
            .ToArrayAsync();
}

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

pandas.isnull() (also pd.isna(), in newer versions) checks for missing values in both numeric and string/object arrays. From the documentation, it checks for:

NaN in numeric arrays, None/NaN in object arrays

Quick example:

import pandas as pd
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
pd.isnull(s)
Out[9]: 
0    False
1     True
2    False
dtype: bool

The idea of using numpy.nan to represent missing values is something that pandas introduced, which is why pandas has the tools to deal with it.

Datetimes too (if you use pd.NaT you won't need to specify the dtype)

In [24]: s = Series([Timestamp('20130101'),np.nan,Timestamp('20130102 9:30')],dtype='M8[ns]')

In [25]: s
Out[25]: 
0   2013-01-01 00:00:00
1                   NaT
2   2013-01-02 09:30:00
dtype: datetime64[ns]``

In [26]: pd.isnull(s)
Out[26]: 
0    False
1     True
2    False
dtype: bool

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

<?php
  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result
  }
?>

<html>
  <head></head>
  <body>

  <?php
    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
      else
        echo "<script type='text/javascript'>alert('failed!')</script>";
    }
  ?>
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>
    </form>
  </body>
</html>

How to determine the Schemas inside an Oracle Data Pump Export file

The running the impdp command to produce an sqlfile, you will need to run it as a user which has the DATAPUMP_IMP_FULL_DATABASE role.

Or... run it as a low privileged user and use the MASTER_ONLY=YES option, then inspect the master table. e.g.

select value_t 
from SYS_IMPORT_TABLE_01 
where name = 'CLIENT_COMMAND' 
and process_order = -59;

col object_name for a30
col processing_status head STATUS for a6
col processing_state head STATE for a5
select distinct
  object_schema,
  object_name,
  object_type,
  object_tablespace,
  process_order,
  duplicate,
  processing_status,
  processing_state
from sys_import_table_01
where process_order > 0
and object_name is not null
order by object_schema, object_name
/

http://download.oracle.com/otndocs/products/database/enterprise_edition/utilities/pdf/oow2011_dp_mastering.pdf

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

Call a Class From another class

Simply create an instance of Class2 and call the desired method.

Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/

Convert URL to File or Blob for FileReader.readAsDataURL

I know this is an expansion off of @tibor-udvari's answer, but for a nicer copy and paste.

async function createFile(url, type){
  if (typeof window === 'undefined') return // make sure we are in the browser
  const response = await fetch(url)
  const data = await response.blob()
  const metadata = {
    type: type || 'video/quicktime'
  }
  return new File([data], url, metadata)
}

How can I search an array in VB.NET?

It's not exactly clear how you want to search the array. Here are some alternatives:

Find all items containing the exact string "Ra" (returns items 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))

Find all items starting with the exact string "Ra" (returns items 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))

Find all items containing any case version of "ra" (returns items 0, 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))

Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

-

If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.

Example:

Function ContainsRa(s As String) As Boolean
   Return s.Contains("Ra")
End Function

Usage:

Dim result As String() = Array.FindAll(arr, ContainsRa)

Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:

Public Class ArrayComparer

   Private _compareTo As String

   Public Sub New(compareTo As String)
      _compareTo = compareTo
   End Sub

   Function Contains(s As String) As Boolean
      Return s.Contains(_compareTo)
   End Function

   Function StartsWith(s As String) As Boolean
      Return s.StartsWith(_compareTo)
   End Function

End Class

Usage:

Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

class Program
{
    static void Main(string[] args)
    {

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
        else
            Console.WriteLine("Out of date ranges!");
    }
}

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

Storing sex (gender) in database

Option 3 is your best bet, but not all DB engines have a "bit" type. If you don't have a bit, then TinyINT would be your best bet.

JavaScript: Is there a way to get Chrome to break on all errors?

This is now supported in Chrome by the "Pause on all exceptions" button.

To enable it:

  • Go to the "Sources" tab in Chrome Developer Tools
  • Click the "Pause" button at the bottom of the window to switch to "Pause on all exceptions mode".

Note that this button has multiple states. Keep clicking the button to switch between

  • "Pause on all exceptions" - the button is colored light blue
  • "Pause on uncaught exceptions", the button is colored purple.
  • "Dont pause on exceptions" - the button is colored gray

How do I clear my Jenkins/Hudson build history?

Use the script console (Manage Jenkins > Script Console) and something like this script to bulk delete a job's build history https://github.com/jenkinsci/jenkins-scripts/blob/master/scriptler/bulkDeleteBuilds.groovy

That script assumes you want to only delete a range of builds. To delete all builds for a given job, use this (tested):

// change this variable to match the name of the job whose builds you want to delete
def jobName = "Your Job Name"
def job = Jenkins.instance.getItem(jobName)

job.getBuilds().each { it.delete() }
// uncomment these lines to reset the build number to 1:
//job.nextBuildNumber = 1
//job.save()

How do I join two lists in Java?

I can't improve on the two-liner in the general case without introducing your own utility method, but if you do have lists of Strings and you're willing to assume those Strings don't contain commas, you can pull this long one-liner:

List<String> newList = new ArrayList<String>(Arrays.asList((listOne.toString().subString(1, listOne.length() - 1) + ", " + listTwo.toString().subString(1, listTwo.length() - 1)).split(", ")));

If you drop the generics, this should be JDK 1.4 compliant (though I haven't tested that). Also not recommended for production code ;-)

Remove shadow below actionbar

add app:elevation="0dp" in AppBarLayout for hiding shadow in appbar

How can I loop over entries in JSON?

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']

Do you need to dispose of objects and set them to null?

If they implement the IDisposable interface then you should dispose them. The garbage collector will take care of the rest.

EDIT: best is to use the using command when working with disposable items:

using(var con = new SqlConnection("..")){ ...

100% Min Height CSS layout

Try this:

body{ height: 100%; }
#content { 
    min-height: 500px;
    height: 100%;
}
#footer {
    height: 100px;
    clear: both !important;
}

The div element below the content div must have clear:both.

Resize iframe height according to content height in it

Below is my onload event handler.

I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments. This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5. It might need some extra tweaking, but the general idea should be clear.

    function onLoadDialog(frame) {
    try {
        var body = frame.contentDocument.body;
        var $body = $(body);
        var $frame = $(frame);
        var contentDiv = frame.parentNode;
        var $contentDiv = $(contentDiv);

        var savedShow = $contentDiv.dialog('option', 'show');
        var position = $contentDiv.dialog('option', 'position');
        // disable show effect to enable re-positioning (UI bug?)
        $contentDiv.dialog('option', 'show', null);
        // show dialog, otherwise sizing won't work
        $contentDiv.dialog('open');

        // Maximize frame width in order to determine minimal scrollHeight
        $frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
                contentDiv.offsetWidth + frame.offsetWidth);

        var minScrollHeight = body.scrollHeight;
        var maxWidth = body.offsetWidth;
        var minWidth = 0;
        // decrease frame width until scrollHeight starts to grow (wrapping)
        while (Math.abs(maxWidth - minWidth) > 10) {
            var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
            $body.css('width', width);
            if (body.scrollHeight > minScrollHeight) {
                minWidth = width;
            } else {
                maxWidth = width;
            }
        }
        $frame.css('width', maxWidth);
        // use maximum height to avoid vertical scrollbar (if possible)
        var maxHeight = $contentDiv.dialog('option', 'maxHeight')
        $frame.css('height', maxHeight);
        $body.css('width', '');
        // correct for vertical scrollbar (if necessary)
        while (body.clientWidth < maxWidth) {
            $frame.css('width', maxWidth + (maxWidth - body.clientWidth));
        }

        var minScrollWidth = body.scrollWidth;
        var minHeight = Math.min(minScrollHeight, maxHeight);
        // descrease frame height until scrollWidth decreases (wrapping)
        while (Math.abs(maxHeight - minHeight) > 10) {
            var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
            $body.css('height', height);
            if (body.scrollWidth < minScrollWidth) {
                minHeight = height;
            } else {
                maxHeight = height;
            }
        }
        $frame.css('height', maxHeight);
        $body.css('height', '');

        // reset widths to 'auto' where possible
        $contentDiv.css('width', 'auto');
        $contentDiv.css('height', 'auto');
        $contentDiv.dialog('option', 'width', 'auto');

        // re-position the dialog
        $contentDiv.dialog('option', 'position', position);

        // hide dialog
        $contentDiv.dialog('close');
        // restore show effect
        $contentDiv.dialog('option', 'show', savedShow);
        // open using show effect
        $contentDiv.dialog('open');
        // remove show effect for consecutive requests
        $contentDiv.dialog('option', 'show', null);

        return;
    }

    //An error is raised if the IFrame domain != its container's domain
    catch (e) {
        window.status = 'Error: ' + e.number + '; ' + e.description;
        alert('Error: ' + e.number + '; ' + e.description);
    }
};

How to get a microtime in Node.js?

process.hrtime() not give current ts.

This should work.

 const loadNs       = process.hrtime(),
        loadMs       = new Date().getTime(),
        diffNs       = process.hrtime(loadNs),
        microSeconds = (loadMs * 1e6) + (diffNs[0] * 1e9) + diffNs[1]

  console.log(microSeconds / 1e3)

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

Have you tried using Project > Clean... from the menu? This will force a new build on the selected projects in Eclipse.

Why does ANT tell me that JAVA_HOME is wrong when it is not?

  1. In Eclipse click RunExternal ToolsExternal Tools Configurations.
  2. Click the JRE tab.
  3. Click the Installed JREs... button.
  4. Click the Add button.
    (Select Standard VM, where applicable.)
  5. Click the Directory button.
  6. Browse to your JDK version (not JRE) of your installed Java
    (e.g. C:\Program Files\Java\jdk1.7.0_04).
  7. Click Finish and OK.
  8. Select the JDK at Separate JRE and click Close.
  9. Re-run your Ant script — have fun!

This worked in a particular scenario I encountered.

how to get files from <input type='file' .../> (Indirect) with javascript

Above answers are pretty sufficient. Additional to the onChange, if you upload a file using drag and drop events, you can get the file in drop event by accessing eventArgs.dataTransfer.files.

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

SelectedValue vs SelectedItem.Value of DropDownList

SelectedValue returns the same value as SelectedItem.Value.

SelectedItem.Value and SelectedItem.Text might have different values and the performance is not a factor here, only the meanings of these properties matters.

<asp:DropDownList runat="server" ID="ddlUserTypes">
    <asp:ListItem Text="Admins" Value="1" Selected="true" />
    <asp:ListItem Text="Users" Value="2"/>
</asp:DropDownList>

Here, ddlUserTypes.SelectedItem.Value == ddlUserTypes.SelectedValue and both would return the value "1".

ddlUserTypes.SelectedItem.Text would return "Admins", which is different from ddlUserTypes.SelectedValue

edit

under the hood, SelectedValue looks like this

public virtual string SelectedValue
{
    get
    {
        int selectedIndex = this.SelectedIndex;
        if (selectedIndex >= 0)
        {
            return this.Items[selectedIndex].Value;
        }
        return string.Empty;
    }
}

and SelectedItem looks like this:

public virtual ListItem SelectedItem
{
    get
    {
        int selectedIndex = this.SelectedIndex;
        if (selectedIndex >= 0)
        {
            return this.Items[selectedIndex];
        }
        return null;
    }
}

One major difference between these two properties is that the SelectedValue has a setter also, since SelectedItem doesn't. The getter of SelectedValue is faster when writing code, and the problem of execution performance has no real reason to be discussed. Also a big advantage of SelectedValue is when using Binding expressions.

edit data binding scenario (you can't use SelectedItem.Value)

<asp:Repeater runat="server">
 <ItemTemplate>
     <asp:DropDownList ID="ddlCategories" runat="server" 
                       SelectedValue='<%# Eval("CategoryId")%>'>
     </asp:DropDownList>
 </ItemTemplate>
</asp:Repeater>

Cache an HTTP 'Get' service response in AngularJS?

As AngularJS factories are singletons, you can simply store the result of the http request and retrieve it next time your service is injected into something.

angular.module('myApp', ['ngResource']).factory('myService',
  function($resource) {
    var cache = false;
    return {
      query: function() {
        if(!cache) {
          cache = $resource('http://example.com/api').query();
        }
        return cache;
      }
    };
  }
);

JSP : JSTL's <c:out> tag

As said Will Wagner, in old version of jsp you should always use c:out to output dynamic text.

Moreover, using this syntax:

<c:out value="${person.name}">No name</c:out>

you can display the text "No name" when name is null.

JQuery .hasClass for multiple values in an if statement

For fun, I wrote a little jQuery add-on method that will check for any one of multiple class names:

$.fn.hasAnyClass = function() {
    for (var i = 0; i < arguments.length; i++) {
        if (this.hasClass(arguments[i])) {
            return true;
        }
    }
    return false;
}

Then, in your example, you could use this:

if ($('html').hasAnyClass('m320', 'm768')) {

// do stuff 

}

You can pass as many class names as you want.


Here's an enhanced version that also lets you pass multiple class names separated by a space:

$.fn.hasAnyClass = function() {
    for (var i = 0; i < arguments.length; i++) {
        var classes = arguments[i].split(" ");
        for (var j = 0; j < classes.length; j++) {
            if (this.hasClass(classes[j])) {
                return true;
            }
        }
    }
    return false;
}

if ($('html').hasAnyClass('m320 m768')) {
    // do stuff 
}

Working demo: http://jsfiddle.net/jfriend00/uvtSA/

psql: command not found Mac

As a postgreSQL newbie I found the os x setup instructions on the postgresql site impenetrable. I got all kinds of errors. Fortunately the uninstaller worked fine.

cd /Library/PostgreSQL/11; open uninstall-postgresql.app/

Then I started over with a brew install followed by this article How to setup PostgreSQL on MacOS

It works fine now.

Creating a LINQ select from multiple tables

You must create a new anonymous type:

 select new { op, pg }

Refer to the official guide.

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Creating a JSON array in C#

new {var_data[counter] =new [] { 
                new{  "S NO":  "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
        }
    };

ASP.NET MVC Razor render without encoding

Since ASP.NET MVC 3, you can use:

@Html.Raw(myString)

bool to int conversion

int x = 4<5;

Completely portable. Standard conformant. bool to int conversion is implicit!

§4.7/4 from the C++ Standard says (Integral Conversion)

If the source type is bool, the value false is converted to zero and the value true is converted to one.


As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

§7.16 from C99 says,

The macro bool expands to _Bool.

[..] true which expands to the integer constant 1, false which expands to the integer constant 0,[..]

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

How do you serialize a model instance in Django?

.values() is what I needed to convert a model instance to JSON.

.values() documentation: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#values

Example usage with a model called Project.

Note: I'm using Django Rest Framework

    @csrf_exempt
    @api_view(["GET"])
    def get_project(request):
        id = request.query_params['id']
        data = Project.objects.filter(id=id).values()
        if len(data) == 0:
            return JsonResponse(status=404, data={'message': 'Project with id {} not found.'.format(id)})
        return JsonResponse(data[0])

Result from a valid id:

{
    "id": 47,
    "title": "Project Name",
    "description": "",
    "created_at": "2020-01-21T18:13:49.693Z",
}

Factory Pattern. When to use factory methods?

It is good idea to use factory methods inside object when:

  1. Object's class doesn't know what exact sub-classes it have to create
  2. Object's class is designed so that objects it creates were specified by sub-classes
  3. Object's class delegates its duties to auxiliary sub-classes and doesn't know what exact class will take these duties

It is good idea to use abstract factory class when:

  1. Your object shouldn't depend on how its inner objects are created and designed
  2. Group of linked objects should be used together and you need to serve this constraint
  3. Object should be configured by one of several possible families of linked objects that will be a part of your parent object
  4. It is required to share child objects showing interfaces only but not an implementation

How to read value of a registry key c#

Change:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))

To:

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

How to run a method every X seconds

You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().

Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds.  One second = 1000 milliseconds.


@Override
protected void onResume() {
   //start handler as activity become visible

    handler.postDelayed( runnable = new Runnable() {
        public void run() {
            //do something

            handler.postDelayed(runnable, delay);
        }
    }, delay);

    super.onResume();
}

// If onPause() is not included the threads will double up when you 
// reload the activity 

@Override
protected void onPause() {
    handler.removeCallbacks(runnable); //stop handler when activity not visible
    super.onPause();
}

Stretch background image css?

Just paste this into your line of codes:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

How to calculate the median of an array?

Arrays.sort(numArray);
return (numArray[size/2] + numArray[(size-1)/2]) / 2;

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

This solution is (only) for SQL Server 2005

You guys are lifesavers, but as @Dan Mork said, you need to add EXEC to the mix. What was tripping me up was:

  • 'EXEC ' before the Proc Name
  • Commas in between Params
  • Chopping off '@' on the Param Definitions (not sure that bit is required though).

:

context.Database.SqlQuery<EntityType>(
    "EXEC ProcName @param1, @param2", 
    new SqlParameter("param1", param1), 
    new SqlParameter("param2", param2)
);

Check if url contains string with JQuery

window.location is an object, not a string so you need to use window.location.href to get the actual string url

if (window.location.href.indexOf("?added-to-cart=555") >= 0) {
    alert("found it");
}

Prevent line-break of span element

If you only need to prevent line-breaks on space characters, you can use &nbsp; entities between words:

No&nbsp;line&nbsp;break

instead of

<span style="white-space:nowrap">No line break</span>

Simple java program of pyramid

enter image description here

 import java.util.Scanner;
    public class Print {
        public static void main(String[] args) {
            int row,temp,c,n;
            Scanner s=new Scanner(System.in);
            n=s.nextInt();
            temp = n;
            for ( row = 1 ; row <= n ; row++ )
               {
                  for ( c = 1 ; c < temp ; c++ )
                    System.out.print(" ");

                  temp--;

                  for ( c = 1 ; c <= 2*row - 1 ; c++ )
                      System.out.print("*");

                  System.out.println("");
               }
        }

    }

Force Internet Explorer to use a specific Java Runtime Environment install?

First, disable the currently installed version of Java. To do this, go to Control Panel > Java > Advanced > Default Java for Browsers and uncheck Microsoft Internet Explorer.

Next, enable the version of Java you want to use instead. To do this, go to (for example) C:\Program Files\Java\jre1.5.0_15\bin (where jre1.5.0_15 is the version of Java you want to use), and run javacpl.exe. Go to Advanced > Default Java for Browsers and check Microsoft Internet Explorer.

To get your old version of Java back you need to reverse these steps.

Note that in older versions of Java, Default Java for Browsers is called <APPLET> Tag Support (but the effect is the same).

The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE.

VBA for clear value in specific range of cell and protected cell from being wash away formula

Try this

Sheets("your sheetname").range("A5:X50").Value = ""

You can also use

ActiveSheet.range

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

Action Image MVC3 Razor

This would be work very fine

<a href="<%:Url.Action("Edit","Account",new {  id=item.UserId }) %>"><img src="../../Content/ThemeNew/images/edit_notes_delete11.png" alt="Edit" width="25px" height="25px" /></a>

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

The algorithm you are using, "AES", is a shorthand for "AES/ECB/NoPadding". What this means is that you are using the AES algorithm with 128-bit key size and block size, with the ECB mode of operation and no padding.

In other words: you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception.

If you want to encrypt data in sizes that are not multiple of 16 bytes, you are either going to have to use some kind of padding, or a cipher-stream. For instance, you could use CBC mode (a mode of operation that effectively transforms a block cipher into a stream cipher) by specifying "AES/CBC/NoPadding" as the algorithm, or PKCS5 padding by specifying "AES/ECB/PKCS5", which will automatically add some bytes at the end of your data in a very specific format to make the size of the ciphertext multiple of 16 bytes, and in a way that the decryption algorithm will understand that it has to ignore some data.

In any case, I strongly suggest that you stop right now what you are doing and go study some very introductory material on cryptography. For instance, check Crypto I on Coursera. You should understand very well the implications of choosing one mode or another, what are their strengths and, most importantly, their weaknesses. Without this knowledge, it is very easy to build systems which are very easy to break.


Update: based on your comments on the question, don't ever encrypt passwords when storing them at a database!!!!! You should never, ever do this. You must HASH the passwords, properly salted, which is completely different from encrypting. Really, please, don't do what you are trying to do... By encrypting the passwords, they can be decrypted. What this means is that you, as the database manager and who knows the secret key, you will be able to read every password stored in your database. Either you knew this and are doing something very, very bad, or you didn't know this, and should get shocked and stop it.

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

How do I dynamically assign properties to an object in TypeScript?

If you are using Typescript, presumably you want to use the type safety; in which case naked Object and 'any' are counterindicated.

Better to not use Object or {}, but some named type; or you might be using an API with specific types, which you need extend with your own fields. I've found this to work:

class Given { ... }  // API specified fields; or maybe it's just Object {}

interface PropAble extends Given {
    props?: string;  // you can cast any Given to this and set .props
    // '?' indicates that the field is optional
}
let g:Given = getTheGivenObject();
(g as PropAble).props = "value for my new field";

// to avoid constantly casting: 
let k:PropAble = getTheGivenObject();
k.props = "value for props";

Mockito test a void method throws an exception

The parentheses are poorly placed.

You need to use:

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

and NOT use:

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

This is explained in the documentation

Display date in dd/mm/yyyy format in vb.net

I found this catered for dates in 21st Century that could be entered as dd/mm or dd/mm/yy. It is intended to print an attendance register and asks for the meeting date to start with.

Sub Print_Register()

Dim MeetingDate, Answer

    Sheets("Register").Select
    Range("A1").Select
GetDate:
    MeetingDate = DateValue(InputBox("Enter the date of the meeting." & Chr(13) & _
    "Note Format" & Chr(13) & "Format DD/MM/YY or DD/MM", "Meeting Date", , 10000, 10000))
    If MeetingDate = "" Then GoTo TheEnd
    If MeetingDate < 36526 Then MeetingDate = MeetingDate + 36526
    Range("Current_Meeting_Date") = MeetingDate
    Answer = MsgBox("Date OK?", 3)
    If Answer = 2 Then GoTo TheEnd
    If Answer = 7 Then GoTo GetDate
    ExecuteExcel4Macro "PRINT(1,,,1,,,,,,,,2,,,TRUE,,FALSE)"
TheEnd:
End Sub

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

In addition to Alex B's answer.

It is even required to use the setUp method to instantiate resources in a certain state. Doing this in the constructor is not only a matter of timings, but because of the way JUnit runs the tests, each test state would be erased after running one.

JUnit first creates instances of the testClass for each test method and starts running the tests after each instance is created. Before running the test method, its setup method is ran, in which some state can be prepared.

If the database state would be created in the constructor, all instances would instantiate the db state right after each other, before running each tests. As of the second test, tests would run with a dirty state.

JUnits lifecycle:

  1. Create a different testclass instance for each test method
  2. Repeat for each testclass instance: call setup + call the testmethod

With some loggings in a test with two test methods you get: (number is the hashcode)

  • Creating new instance: 5718203
  • Creating new instance: 5947506
  • Setup: 5718203
  • TestOne: 5718203
  • Setup: 5947506
  • TestTwo: 5947506

Change color of bootstrap navbar on hover link?

.nav > li > a:focus, 
.nav > li > a:hover 
{
    text-decoration: underline;
    background-color: pink;
}

Using css transform property in jQuery

If you want to use a specific transform function, then all you need to do is include that function in the value. For example:

$('.user-text').css('transform', 'scale(' + ui.value + ')');

Secondly, browser support is getting better, but you'll probably still need to use vendor prefixes like so:

$('.user-text').css({
  '-webkit-transform' : 'scale(' + ui.value + ')',
  '-moz-transform'    : 'scale(' + ui.value + ')',
  '-ms-transform'     : 'scale(' + ui.value + ')',
  '-o-transform'      : 'scale(' + ui.value + ')',
  'transform'         : 'scale(' + ui.value + ')'
});

jsFiddle with example: http://jsfiddle.net/jehka/230/

How can I use numpy.correlate to do autocorrelation?

Auto-correlation comes in two versions: statistical and convolution. They both do the same, except for a little detail: The statistical version is normalized to be on the interval [-1,1]. Here is an example of how you do the statistical one:

def acf(x, length=20):
    return numpy.array([1]+[numpy.corrcoef(x[:-i], x[i:])[0,1]  \
        for i in range(1, length)])

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

Comparing two input values in a form validation with AngularJS

You should be able to use ng-pattern/regex for comparing 2 input values

Email:<input type="email" name="email1" ng-model="emailReg">
Repeat Email:<input type="email" name="email2" ng-model="emailReg2" ng-pattern="emailReg">

and validation with:

<span ng-show="registerForm.email2.$error.pattern">Repeat Email should have the same value with email!</span>

Unable to make the session state request to the session state server

One of my clients was facing the same issue. Following steps are taken to fix this.

 (1) Open Run. 

 (2) Type Services.msc

 (3) Select ASP.NET State Service

 (4) Right Click and Start it.

How do you convert a DataTable into a generic list?

With C# 3.0 and System.Data.DataSetExtensions.dll,

List<DataRow> rows = table.Rows.Cast<DataRow>().ToList();

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

try if install lampp

sudo chown www-data:www-data -R /opt/lampp/phpmyadmin/*
sudo chown www-data:www-data -R /opt/lampp/phpmyadmin

or if install phpmyadmin

sudo chown www-data:www-data -R /etc/phpmyadmin/*
sudo chown www-data:www-data -R /etc/phpmyadmin

Get dates from a week number in T-SQL

Quassnoi's answer works, but kind of leaves you on the hook for cleaning up the dates if they are dates in the middle of the day (his start of week leaves you one day earlier than you need to be if you use a time in the middle of the day -- you can test using GETDATE()).

I've used something like this in the past:

SELECT 
   CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL), DATECOL)), 101),
   CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL) - 6, DATECOL)), 101)

A side benefit of this is that by using @@DATEFIRST you can handle nonstandard week starting days (the default is Sunday, but with SET @@DATEFIRST you can change this).

It seems crazy that simple date manipulation in SQL Server has to be this arcane, but there you go...

How to call a button click event from another method

In WPF, you can easily do it in this way:

this.button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

Center button under form in bootstrap

If you're using Bootstrap 4, try this:

<div class="mx-auto text-center">
    <button id="button" name="button" class="btn btn-primary">Press Me!</button>
</div>

How to add new DataRow into DataTable?

//?Creating a new row with the structure of the table:

DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);

//Giving values to the columns of the row(this row is supposed to have 28 columns):

for (int i = 0; i < 28; i++)
{
    row[i] = i.ToString();
}

Any way to limit border length?

The ::after pseudo-element rocks :)

If you play a bit you can even set your resized border element to appear centered or to appear only if there is another element next to it (like in menus). Here is an example with a menu:

#menu > ul > li {
    position: relative;
    float: left;
    padding: 0 10px;
}

#menu > ul > li + li::after {
    content:"";
    background: #ccc;
    position: absolute;
    bottom: 25%;
    left: 0;
    height: 50%;
    width: 1px;
}

_x000D_
_x000D_
#menu > ul > li {
  position: relative;
  float: left;
  padding: 0 10px;
  list-style: none;
}
#menu > ul > li + li::after {
  content: "";
  background: #ccc;
  position: absolute;
  bottom: 25%;
  left: 0;
  height: 50%;
  width: 1px;
}
_x000D_
<div id="menu">
  <ul>
    <li>Foo</li>
    <li>Bar</li>
    <li>Baz</li>
  </ul>
</div>
_x000D_
_x000D_
_x000D_

How to avoid pressing Enter with getchar() for reading a single character only?

This code worked for me. Attention : this is not part of the standard library, even if most compilers (I use GCC) supports it.

#include <stdio.h>
#include <conio.h>
int main(int argc, char const *argv[]) {
    char a = getch();
    printf("You typed a char with an ASCII value of %d, printable as '%c'\n", a, a);
    return 0;
}

This code detects the first key press.

How do I generate a random number between two variables that I have stored?

rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber

How to show form input fields based on select value?

You have to use val() instead of value() and you have missed starting quote id=dbType" should be id="dbType"

Live Demo

Change

selection = $('this').value();

To

selection = $(this).val();

or

selection = this.value;