Programs & Examples On #Delphi 2005

Delphi 2005 is a specific version of Delphi. It was released in October 2004. Use this tag for issues related to development in Delphi 2005.

How to check whether a Storage item is set?

For TRUE

localStorage.infiniteScrollEnabled = 1;

FOR FALSE

localStorage.removeItem("infiniteScrollEnabled")

CHECK EXISTANCE

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}

Create boolean column in MySQL with false as default value?

You can set a default value at creation time like:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
Married boolean DEFAULT false);

get selected value in datePicker and format it

$('#scheduleDate').datepicker({ dateFormat : 'dd, MM, yy'});

var dateFormat = $('#scheduleDate').datepicker('option', 'dd, MM, yy');

$('#scheduleDate').datepicker('option', 'dateFormat', 'dd, MM, yy');

var result = $('#scheduleDate').val();

alert('result: ' + result);

result: 20, April, 2012

How to do a SQL NOT NULL with a DateTime?

I faced this problem where the following query doesn't work as expected:

select 1 where getdate()<>null

we expect it to show 1 because getdate() doesn't return null. I guess it has something to do with SQL failing to cast null as datetime and skipping the row! of course we know we should use IS or IS NOT keywords to compare a variable with null but when comparing two parameters it gets hard to handle the null situation. as a solution you can create your own compare function like the following:

CREATE FUNCTION [dbo].[fnCompareDates]
(
    @DateTime1 datetime,
    @DateTime2 datetime
)
RETURNS bit
AS
BEGIN
    if (@DateTime1 is null and @DateTime2 is null) return 1;
    if (@DateTime1 = @DateTime2) return 1;
    return 0
END

and re writing the query like:

select 1 where dbo.fnCompareDates(getdate(),null)=0

what is the multicast doing on 224.0.0.251?

Those look much like Bonjour / mDNS requests to me. Those packets use multicast IP address 224.0.0.251 and port 5353.

The most likely source for this is Apple iTunes, which comes pre-installed on Mac computers (and is a popular install on Windows machines as well). Apple iTunes uses it to discover other iTunes-compatible devices in the same WiFi network.

mDNS is also used (primarily by Apple's Mac and iOS devices) to discover mDNS-compatible devices such as printers on the same network.

If this is a Linux box instead, it's probably the Avahi daemon then. Avahi is ZeroConf/Bonjour compatible and installed by default, but if you don't use DNS-SD or mDNS, it can be disabled.

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

You can assign the DataFrame to a filtered version of itself:

df = df[df.score > 50]

This is faster than drop:

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test[test.x < 0]
# 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test.drop(test[test.x > 0].index, inplace=True)
# 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test.drop(test[test.x > 0].index)
# 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

How to get a .csv file into R?

As Dirk said, the function you are after is 'read.csv' or one of the other read.table variants. Given your sample data above, I think you will want to do something like this:

setwd("c:/random/directory")

df <- read.csv("myRandomFile.csv", header=TRUE)

All we did in the above was set the directory to where your .csv file is and then read the .csv into a dataframe named df. You can check that the data loaded properly by checking the structure of the object with:

str(df)

Assuming the data loaded properly, you can think go on to perform any number of statistical methods with the data in your data frame. I think summary(df) would be a good place to start. Learning how to use the help in R will be immensely useful, and a quick read through the help on CRAN will save you lots of time in the future: http://cran.r-project.org/

How do I check if a PowerShell module is installed?

You can use the Get-InstalledModule

If (-not(Get-InstalledModule SomeModule -ErrorAction silentlycontinue)) {
  Write-Host "Module does not exist"
}
Else {
  Write-Host "Module exists"
}

Creating a singleton in Python

I'll toss mine into the ring. It's a simple decorator.

from abc import ABC

def singleton(real_cls):

    class SingletonFactory(ABC):

        instance = None

        def __new__(cls, *args, **kwargs):
            if not cls.instance:
                cls.instance = real_cls(*args, **kwargs)
            return cls.instance

    SingletonFactory.register(real_cls)
    return SingletonFactory

# Usage
@singleton
class YourClass:
    ...  # Your normal implementation, no special requirements.

Benefits I think it has over some of the other solutions:

  • It's clear and concise (to my eye ;D).
  • Its action is completely encapsulated. You don't need to change a single thing about the implementation of YourClass. This includes not needing to use a metaclass for your class (note that the metaclass above is on the factory, not the "real" class).
  • It doesn't rely on monkey-patching anything.
  • It's transparent to callers:
    • Callers still simply import YourClass, it looks like a class (because it is), and they use it normally. No need to adapt callers to a factory function.
    • What YourClass() instantiates is still a true instance of the YourClass you implemented, not a proxy of any kind, so no chance of side effects resulting from that.
    • isinstance(instance, YourClass) and similar operations still work as expected (though this bit does require abc so precludes Python <2.6).

One downside does occur to me: classmethods and staticmethods of the real class are not transparently callable via the factory class hiding it. I've used this rarely enough that I've never happen to run into that need, but it would be easily rectified by using a custom metaclass on the factory that implements __getattr__() to delegate all-ish attribute access to the real class.

A related pattern I've actually found more useful (not that I'm saying these kinds of things are required very often at all) is a "Unique" pattern where instantiating the class with the same arguments results in getting back the same instance. I.e. a "singleton per arguments". The above adapts to this well and becomes even more concise:

def unique(real_cls):

    class UniqueFactory(ABC):

        @functools.lru_cache(None)  # Handy for 3.2+, but use any memoization decorator you like
        def __new__(cls, *args, **kwargs):
            return real_cls(*args, **kwargs)

    UniqueFactory.register(real_cls)
    return UniqueFactory

All that said, I do agree with the general advice that if you think you need one of these things, you really should probably stop for a moment and ask yourself if you really do. 99% of the time, YAGNI.

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

I use this website and this pattern do leap year validation as well.

<input type="text" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" required />

Need to remove href values when printing in Chrome

It doesn't. Somewhere in your print stylesheet, you must have this section of code:

a[href]::after {
    content: " (" attr(href) ")"
}

The only other possibility is you have an extension doing it for you.

How can one see the structure of a table in SQLite?

You will get the structure by typing the command:

.schema <tableName>

how to pass this element to javascript onclick function and add a class to that clicked element

You can use addEventListener to pass this to a JavaScript function.

HTML

<button id="button">Year</button>

JavaScript

(function () {
    var btn = document.getElementById('button');
    btn.addEventListener('click', function () {
        Date('#year');
    }, false);
})();

 function Data(string)
          {
                $('.filter').removeClass('active');
                $(this).parent().addClass('active') ;
          } 

Android checkbox style

Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.


My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.

At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.

First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.

<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox in a different name. So let's look at that parent style.

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

This style references both a background and button drawable. btn_check_label_background is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox.

As listChoiceIndicatorMultiple is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):

<style name="Theme">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
    ...
</style>

<style name="Theme.Holo">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
    ...
</style>

<style name="Theme.Holo.Light" parent="Theme.Light">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
    ...
</style>

So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple attribute, the actual appearance of the CheckBox is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo, you will always get the CheckBox appearance matching the theme.

Now, if you want to change your CheckBox's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.

As for your second question:

Also can you set styles to individual widgets if you set a style to the application?

Absolutely, and they will override any activity- or application-set styles.

Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?


Update:

Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.

However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:

int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);

The first line will actually return the resource id of the btn_check_holo_light drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox, we can set it as 'button drawable' on the widget. The result is a CheckBox with the appearance of the Holo.Light version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.

Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo styling (non-light, that is).

Screenshot showing the result


Update2:

With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):

Lollipop added the ability to overwrite the theme at a view by view level by using the android:theme XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to use android:theme for Toolbars (deprecating the app:theme used previously) and, even better, brings android:theme support to all views on API 11+ devices.

In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo" />

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo.Light" />

The first CheckBox is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.

Of course you should no longer be using the Holo theme, but instead use Material.

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

When to use setAttribute vs .attribute= in JavaScript?

None of the previous answers are complete and most contain misinformation.

There are three ways of accessing the attributes of a DOM Element in JavaScript. All three work reliably in modern browsers as long as you understand how to utilize them.

1. element.attributes

Elements have a property attributes that returns a live NamedNodeMap of Attr objects. The indexes of this collection may be different among browsers. So, the order is not guaranteed. NamedNodeMap has methods for adding and removing attributes (getNamedItem and setNamedItem, respectively).

Notice that though XML is explicitly case sensitive, the DOM spec calls for string names to be normalized, so names passed to getNamedItem are effectively case insensitive.

Example Usage:

_x000D_
_x000D_
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//you can look up specific attributes_x000D_
var classAttr = div.attributes.getNamedItem('CLASS');_x000D_
document.write('attributes.getNamedItem() Name: ' + classAttr.name + ' Value: ' + classAttr.value + '<br>');_x000D_
_x000D_
//you can enumerate all defined attributes_x000D_
for(var i = 0; i < div.attributes.length; i++) {_x000D_
  var attr = div.attributes[i];_x000D_
  document.write('attributes[] Name: ' + attr.name + ' Value: ' + attr.value + '<br>');_x000D_
}_x000D_
_x000D_
//create custom attribute_x000D_
var customAttr = document.createAttribute('customTest');_x000D_
customAttr.value = '567';_x000D_
div.attributes.setNamedItem(customAttr);_x000D_
_x000D_
//retreive custom attribute_x000D_
customAttr = div.attributes.getNamedItem('customTest');_x000D_
document.write('attributes.getNamedItem() Name: ' + customAttr.name + ' Value: ' + customAttr.value + '<br>');
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
_x000D_
_x000D_

2. element.getAttribute & element.setAttribute

These methods exist directly on the Element without needing to access attributes and its methods but perform the same functions.

Again, notice that string name are case insensitive.

Example Usage:

_x000D_
_x000D_
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//get specific attributes_x000D_
document.write('Name: class Value: ' + div.getAttribute('class') + '<br>');_x000D_
document.write('Name: ID Value: ' + div.getAttribute('ID') + '<br>');_x000D_
document.write('Name: DATA-TEST Value: ' + div.getAttribute('DATA-TEST') + '<br>');_x000D_
document.write('Name: nonStandard Value: ' + div.getAttribute('nonStandard') + '<br>');_x000D_
_x000D_
_x000D_
//create custom attribute_x000D_
div.setAttribute('customTest', '567');_x000D_
_x000D_
//retreive custom attribute_x000D_
document.write('Name: customTest Value: ' + div.getAttribute('customTest') + '<br>');
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
_x000D_
_x000D_

3. Properties on the DOM object, such as element.id

Many attributes can be accessed using convenient properties on the DOM object. Which attributes exist depends on the DOM node's type, not which attributes are defined in the HTML. The properties are defined somewhere in the prototype chain of DOM object in question. The specific properties defined will depend on the type of Element you are accessing. For example, className and id are defined on Element and exist on all DOM nodes that are elements (ie. not text or comment nodes). But value is more narrow. It's defined on HTMLInputElement and may not exist on other elements.

Notice that JavaScript properties are case sensitive. Although most properties will use lowercase, some are camelCase. So always check the spec to be sure.

This "chart" captures a portion of the prototype chain for these DOM objects. It's not even close to complete, but it captures the overall structure.

                      ____________Node___________
                      |               |         |
                   Element           Text   Comment
                   |     |
           HTMLElement   SVGElement
           |         |
HTMLInputElement   HTMLSpanElement

Example Usage:

_x000D_
_x000D_
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//get specific attributes_x000D_
document.write('Name: class Value: ' + div.className + '<br>');_x000D_
document.write('Name: id Value: ' + div.id + '<br>');_x000D_
document.write('Name: ID Value: ' + div.ID + '<br>'); //undefined_x000D_
document.write('Name: data-test Value: ' + div.dataset.test + '<br>'); //.dataset is a special case_x000D_
document.write('Name: nonStandard Value: ' + div.nonStandard + '<br>'); //undefined
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
_x000D_
_x000D_

Caveat: This is an explanation of how the HTML spec defines and modern browsers handle attributes. I did not attempt to deal with limitations of ancient, broken browsers. If you need to support old browsers, in addition to this information, you will need to know what is broken in the those browsers.

Load image with jQuery and append it to the DOM

With jQuery 3.x use something like:

$('<img src="'+ imgPath +'">').on('load', function() {
  $(this).width(some).height(some).appendTo('#some_target');
});

How to specify different Debug/Release output directories in QMake .pro file

It's also useful to have a slightly different name for the output executable. You can't use something like:

release: Target = ProgramName
debug: Target = ProgramName_d

Why it doesn't work is not clear, but it does not. But:

CONFIG(debug, debug|release) {
    TARGET = ProgramName
} else {
    TARGET = ProgramName_d
}

This does work as long as the CONFIG += line precedes it.

How to enable core dump in my Linux C++ program

By default many profiles are defaulted to 0 core file size because the average user doesn't know what to do with them.

Try ulimit -c unlimited before running your program.

ElasticSearch - Return Unique Values

Elasticsearch 1.1+ has the Cardinality Aggregation which will give you a unique count

Note that it is actually an approximation and accuracy may diminish with high-cardinality datasets, but it's generally pretty accurate in my testing.

You can also tune the accuracy with the precision_threshold parameter. The trade-off, or course, is memory usage.

This graph from the docs shows how a higher precision_threshold leads to much more accurate results.


Relative error vs threshold

center a row using Bootstrap 3

We can also use col-md-offset like this, it would save us from an extra divs code. So instead of three divs we can do by using only one div:

<div class="col-md-4 col-md-offset-4">Centered content</div>

How do I use LINQ Contains(string[]) instead of Contains(string)

This is an example of one way of writing an extension method (note: I wouldn't use this for very large arrays; another data structure would be more appropriate...):

namespace StringExtensionMethods
{
    public static class StringExtension
    {
        public static bool Contains(this string[] stringarray, string pat)
        {
            bool result = false;

            foreach (string s in stringarray)
            {
                if (s == pat)
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
    }
}

Random number from a range in a Bash Script

On Mac OS X and FreeBSD you may also use jot:

jot -r 1  2000 65000

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

Rename a column in MySQL

In mysql your query should be like

ALTER TABLE table_name change column_1 column_2 Data_Type;

you have written the query in Oracle.

Change SVN repository URL

Grepping the URL before and after might give you some peace of mind:

svn info | grep URL

  URL: svn://svnrepo.rz.mycompany.org/repos/trunk/DataPortal
  Relative URL: (...doesn't matter...)

And checking on your version (to be >1.7) to ensure, svn relocate is the right thing to use:

svn --version

Lastly, adding to the above, if your repository url change also involves a change of protocol you might need to state the before and after url (also see here)

svn relocate svn://svnrepo.rz.mycompany.org/repos/trunk/DataPortal
    https://svngate.mycompany.org/svn/repos/trunk/DataPortal

All in one single line of course.Thereafter, get the good feeling, that all went smoothly:

svn info | grep URL:

If you feel like it, a bit more of self-assurance, the new svn repo URL is connected and working:

svn status --show-updates
svn diff

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".")1 returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath() in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

  • Server.MapPath(".")1 returns D:\WebApps\shop\products
  • Server.MapPath("..") returns D:\WebApps\shop
  • Server.MapPath("~") returns D:\WebApps\shop
  • Server.MapPath("/") returns C:\Inetpub\wwwroot
  • Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward slash (/) or backward slash (\), the MapPath() returns a path as if Path was a full, virtual path.

If Path doesn't start with a slash, the MapPath() returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

  1. Server.MapPath(null) and Server.MapPath("") will produce this effect too.

How to use a wildcard in the classpath to add multiple jars?

From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

This should work in Java6, not sure about Java5

(If it seems it does not work as expected, try putting quotes. eg: "foo/*")

Concatenate string with field value in MySQL

MySQL uses CONCAT() to concatenate strings

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)

Change User Agent in UIWebView

The only problem I have found was change user agent only

- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSDictionary *dictionary = [NSDictionary 
        dictionaryWithObjectsAndKeys:
        @"Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; ja-jp) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5", 
        @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}

Regex to check if valid URL that ends in .jpg, .png, or .gif

In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details.

If you are keen on doing this, though, check out this question:

Getting parts of a URL (Regex)

Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like

(?i)\.(jpg|png|gif)$

What is a NullReferenceException, and how do I fix it?

A NullReferenceException is thrown when we are trying to access Properties of a null object or when a string value becomes empty and we are trying to access string methods.

For example:

  1. When a string method of an empty string accessed:

    string str = string.Empty;
    str.ToLower(); // throw null reference exception
    
  2. When a property of a null object accessed:

    Public Class Person {
        public string Name { get; set; }
    }
    Person objPerson;
    objPerson.Name  /// throw Null refernce Exception 
    

Sizing elements to percentage of screen width/height

This is a supplemental answer showing the implementation of a couple of the solutions mentioned.

FractionallySizedBox

If you have a single widget you can use a FractionallySizedBox widget to specify a percentage of the available space to fill. Here the green Container is set to fill 70% of the available width and 30% of the available height.

FractionallySizedBox
Widget myWidget() {
  return FractionallySizedBox(
    widthFactor: 0.7,
    heightFactor: 0.3,
    child: Container(
      color: Colors.green,
    ),
  );
}

Expanded

The Expanded widget allows a widget to fill the available space, horizontally if it is in a row, or vertically if it is in a column. You can use the flex property with multiple widgets to give them weights. Here the green Container takes 70% of the width and the yellow Container takes 30% of the width.

Expanded

If you want to do it vertically, then just replace Row with Column.

Widget myWidget() {
  return Row(
    children: <Widget>[
      Expanded(
        flex: 7,
        child: Container(
          color: Colors.green,
        ),
      ),
      Expanded(
        flex: 3,
        child: Container(
          color: Colors.yellow,
        ),
      ),
    ],
  );
}

Supplemental code

Here is the main.dart code for your reference.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("FractionallySizedBox"),
        ),
        body: myWidget(),
      ),
    );
  }
}

// replace with example code above
Widget myWidget() {
  return ...
}

GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    };
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA
}

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
{
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
{
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;
}

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

SQL select only rows with max value on a column

This solution makes only one selection from YourTable, therefore it's faster. It works only for MySQL and SQLite(for SQLite remove DESC) according to test on sqlfiddle.com. Maybe it can be tweaked to work on other languages which I am not familiar with.

SELECT *
FROM ( SELECT *
       FROM ( SELECT 1 as id, 1 as rev, 'content1' as content
              UNION
              SELECT 2, 1, 'content2'
              UNION
              SELECT 1, 2, 'content3'
              UNION
              SELECT 1, 3, 'content4'
            ) as YourTable
       ORDER BY id, rev DESC
   ) as YourTable
GROUP BY id

Using Java to find substring of a bigger string using Regular Expression

the non-regex way:

String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf("["),input.indexOf("]"));

alternatively, for slightly better performance/memory usage (thanks Hosam):

String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf('['),input.lastIndexOf(']'));

How can I enable cURL for an installed Ubuntu LAMP stack?

From Install Curl Extension for PHP in Ubuntu:

sudo apt-get install php5-curl

After installing libcurl, you should restart the web server with one of the following commands,

sudo /etc/init.d/apache2 restart

or

sudo service apache2 restart

String format currency

As others have said, you can achieve this through an IFormatProvider. But bear in mind that currency formatting goes well beyond the currency symbol. For example a correctly-formatted price in the US may be "$ 12.50" but in France this would be written "12,50 $" (the decimal point is different as is the position of the currency symbol). You don't want to lose this culture-appropriate formatting just for the sake of changing the currency symbol. And the good news is that you don't have to, as this code demonstrates:

var cultureInfo = Thread.CurrentThread.CurrentCulture;   // You can also hardcode the culture, e.g. var cultureInfo = new CultureInfo("fr-FR"), but then you lose culture-specific formatting such as decimal point (. or ,) or the position of the currency symbol (before or after)
var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "€"; // Replace with "$" or "£" or whatever you need

var price = 12.3m;
var formattedPrice = price.ToString("C", numberFormatInfo); // Output: "€ 12.30" if the CurrentCulture is "en-US", "12,30 €" if the CurrentCulture is "fr-FR".

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

Set an intermediate page where you change $_POST variables into $_SESSION. In your actual page, unset them after usage.

You may pass also the initial page URL to set the browser back button.

How to pass List<String> in post method using Spring MVC?

You are using wrong JSON. In this case you should use JSON that looks like this:

["orange", "apple"]

If you have to accept JSON in that form :

{"fruits":["apple","orange"]}

You'll have to create wrapper object:

public class FruitWrapper{

    List<String> fruits;

    //getter
    //setter
}

and then your controller method should look like this:

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST, 
    consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}

Set focus on TextBox in WPF from view model

For Silverlight:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace MyProject.Behaviors
{
    public class FocusBehavior : Behavior<Control>
    {
        protected override void OnAttached()
        {
            this.AssociatedObject.Loaded += AssociatedObject_Loaded;
            base.OnAttached();
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            this.AssociatedObject.Loaded -= AssociatedObject_Loaded;
            if (this.HasInitialFocus || this.IsFocused)
            {
                this.GotFocus();
            }
        }

        private void GotFocus()
        {
            this.AssociatedObject.Focus();
            if (this.IsSelectAll)
            {
                if (this.AssociatedObject is TextBox)
                {
                    (this.AssociatedObject as TextBox).SelectAll();
                }
                else if (this.AssociatedObject is PasswordBox)
                {
                    (this.AssociatedObject as PasswordBox).SelectAll();
                }
                else if (this.AssociatedObject is RichTextBox)
                {
                    (this.AssociatedObject as RichTextBox).SelectAll();
                }
            }
        }

        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.Register(
                "IsFocused",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, 
                    (d, e) => 
                    {
                        if ((bool)e.NewValue)
                        {
                            ((FocusBehavior)d).GotFocus();
                        }
                    }));

        public bool IsFocused
        {
            get { return (bool)GetValue(IsFocusedProperty); }
            set { SetValue(IsFocusedProperty, value); }
        }

        public static readonly DependencyProperty HasInitialFocusProperty =
            DependencyProperty.Register(
                "HasInitialFocus",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, null));

        public bool HasInitialFocus
        {
            get { return (bool)GetValue(HasInitialFocusProperty); }
            set { SetValue(HasInitialFocusProperty, value); }
        }

        public static readonly DependencyProperty IsSelectAllProperty =
            DependencyProperty.Register(
                "IsSelectAll",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, null));

        public bool IsSelectAll
        {
            get { return (bool)GetValue(IsSelectAllProperty); }
            set { SetValue(IsSelectAllProperty, value); }
        }

    }
}

LoginViewModel.cs:

    public class LoginModel : ViewModelBase
    {
        ....

        private bool _EmailFocus = false;
        public bool EmailFocus
        {
            get
            {
                return _EmailFocus;
            }
            set
            {
                if (value)
                {
                    _EmailFocus = false;
                    RaisePropertyChanged("EmailFocus");
                }
                _EmailFocus = value;
                RaisePropertyChanged("EmailFocus");
            }
        }
       ...
   }

Login.xaml:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:beh="clr-namespace:MyProject.Behaviors"

<TextBox Text="{Binding Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <i:Interaction.Behaviors>
        <beh:FocusBehavior IsFocused="{Binding EmailFocus}" IsSelectAll="True"/>
    </i:Interaction.Behaviors>
</TextBox>

OR

<TextBox Text="{Binding Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <i:Interaction.Behaviors>
        <beh:FocusBehavior HasInitialFocus="True" IsSelectAll="True"/>
    </i:Interaction.Behaviors>
</TextBox>

To set the focus should just do it in code:

EmailFocus = true;

Remember that this plugin is part of an html page, so other controls in the page might have the focus

if (!Application.Current.IsRunningOutOfBrowser)
{
    System.Windows.Browser.HtmlPage.Plugin.Focus();
}

How do I set session timeout of greater than 30 minutes

If you want to never expire a session use 0 or negative value -1.

<session-config>
    <session-timeout>0</session-timeout>
</session-config>

or mention 1440 it indicates 1440 minutes [24hours * 60 minutes]

<session-config>
  <session-timeout>1440</session-timeout><!-- 24hours -->
</session-config>

Session will be expire after 24hours.

How do you set up use HttpOnly cookies in PHP

<?php
//None HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, FALSE); 

//HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE); 

?>

Source

How to select the comparison of two columns as one column in Oracle

If you want to consider null values equality too, try the following

select column1, column2, 
   case
      when column1 is NULL and column2 is NULL then 'true'  
      when column1=column2 then 'true' 
      else 'false' 
   end 
from table;

How to perform string interpolation in TypeScript?

In JavaScript you can use template literals:

let value = 100;
console.log(`The size is ${ value }`);

Find provisioning profile in Xcode 5

xCode 6 allows you to right click on the provisioning profile under account -> detail (the screen shot you have there) & shows a popup "show in finder".

Creating a div element inside a div element in javascript

'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()
{

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
 //document.body.appendChild(element);
 }

How to create a new object instance from a Type

I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)

With generic method you can require that the type implements New().

Public Function CloneObject(Of T As New)(ByVal src As T) As T
    Dim result As T = Nothing
    Dim cloneable = TryCast(src, ICloneable)
    If cloneable IsNot Nothing Then
        result = cloneable.Clone()
    Else
        result = New T
        CopySimpleProperties(src, result, Nothing, "clone")
    End If
    Return result
End Function

With non-generic assume the type has a default constructor and catch an exception if it doesn't.

Public Function CloneObject(ByVal src As Object) As Object
    Dim result As Object = Nothing
    Dim cloneable As ICloneable
    Try
        cloneable = TryCast(src, ICloneable)
        If cloneable IsNot Nothing Then
            result = cloneable.Clone()
        Else
            result = Activator.CreateInstance(src.GetType())
            CopySimpleProperties(src, result, Nothing, "clone")
        End If
    Catch ex As Exception
        Trace.WriteLine("!!! CloneObject(): " & ex.Message)
    End Try
    Return result
End Function

.htaccess redirect http to https

Replace your domain with domainname.com , it's working with me .

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domainname.com/$1 [R,L]

How do I sort strings alphabetically while accounting for value when a string is numeric?

Pass a custom comparer into OrderBy. Enumerable.OrderBy will let you specify any comparer you like.

This is one way to do that:

void Main()
{
    string[] things = new string[] { "paul", "bob", "lauren", "007", "90", "101"};

    foreach (var thing in things.OrderBy(x => x, new SemiNumericComparer()))
    {    
        Console.WriteLine(thing);
    }
}


public class SemiNumericComparer: IComparer<string>
{
    /// <summary>
    /// Method to determine if a string is a number
    /// </summary>
    /// <param name="value">String to test</param>
    /// <returns>True if numeric</returns>
    public static bool IsNumeric(string value)
    {
        return int.TryParse(value, out _);
    }

    /// <inheritdoc />
    public int Compare(string s1, string s2)
    {
        const int S1GreaterThanS2 = 1;
        const int S2GreaterThanS1 = -1;

        var IsNumeric1 = IsNumeric(s1);
        var IsNumeric2 = IsNumeric(s2);

        if (IsNumeric1 && IsNumeric2)
        {
            var i1 = Convert.ToInt32(s1);
            var i2 = Convert.ToInt32(s2);

            if (i1 > i2)
            {
                return S1GreaterThanS2;
            }

            if (i1 < i2)
            {
                return S2GreaterThanS1;
            }

            return 0;
        }

        if (IsNumeric1)
        {
            return S2GreaterThanS1;
        }

        if (IsNumeric2)
        {
            return S1GreaterThanS2;
        }

        return string.Compare(s1, s2, true, CultureInfo.InvariantCulture);
    }
}

What is the best way to determine a session variable is null or empty in C#?

I also like to wrap session variables in properties. The setters here are trivial, but I like to write the get methods so they have only one exit point. To do that I usually check for null and set it to a default value before returning the value of the session variable. Something like this:

string Name
{
   get 
   {
       if(Session["Name"] == Null)
           Session["Name"] = "Default value";
       return (string)Session["Name"];
   }
   set { Session["Name"] = value; }
}

}

Compare two List<T> objects for equality, ignoring order

try this!!!

using following code you could compare one or many fields to generate a result list as per your need. result list will contain only modified item(s).

// veriables been used
List<T> diffList = new List<T>();
List<T> gotResultList = new List<T>();



// compare First field within my MyList
gotResultList = MyList1.Where(a => !MyList2.Any(a1 => a1.MyListTField1 == a.MyListTField1)).ToList().Except(gotResultList.Where(a => !MyList2.Any(a1 => a1.MyListTField1 == a.MyListTField1))).ToList();
// Generate result list
diffList.AddRange(gotResultList);

// compare Second field within my MyList
gotResultList = MyList1.Where(a => !MyList2.Any(a1 => a1.MyListTField2 == a.MyListTField2)).ToList().Except(gotResultList.Where(a => !MyList2.Any(a1 => a1.MyListTField2 == a.MyListTField2))).ToList();
// Generate result list
diffList.AddRange(gotResultList);


MessageBox.Show(diffList.Count.ToString);

Keyboard shortcuts are not active in Visual Studio with Resharper installed

I had the same problem and reset didn't fix it. Then the resharper support helped me. Solution was very simple! I'm from Russia and usually my default keyboard is Russian. In control panel | language settings | change keyboard - I changed default keyboard to English. Then reapply settings in VS: Resharper|Options|Keyboard&Menus - apply R# scheme. And the problem was fixed :)

How to round up a number to nearest 10?

to nearest 10 , should be as below

$number = ceil($input * 0.1)/0.1 ;

Python: CSV write by column rather than row

Read it in by row and then transpose it in the command line. If you're using Unix, install csvtool and follow the directions in: https://unix.stackexchange.com/a/314482/186237

get value from DataTable

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

How to determine the current language of a wordpress page when using polylang?

To show current language, you can use:

 <?php echo $lang=get_bloginfo("language"); ?>

Plain and simple

Is there any way to do HTTP PUT in python

I also recommend httplib2 by Joe Gregario. I use this regularly instead of httplib in the standard lib.

Delete many rows from a table using id in Mysql

Others have suggested IN, this is fine. You can also use a range:

DELETE from tablename where id<254 and id>3;

If the ids to delete are contiguous.

What's the difference between map() and flatMap() methods in Java 8?

This is very confusing for beginners. The basic difference is map emits one item for each entry in the list and flatMap is basically a map + flatten operation. To be more clear, use flatMap when you require more than one value, eg when you are expecting a loop to return arrays, flatMap will be really helpful in this case.

I have written a blog about this, you can check it out here.

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

Background images: how to fill whole div if image is small and vice versa

Try below code segment, I've tried it myself before :

#your-div {
    background: url("your-image-link") no-repeat;
    background-size: cover;
    background-clip: border-box;
}

Target WSGI script cannot be loaded as Python module

The solution that finally worked for me, after trying many of these options unsuccessfully was simple, but elusive because I struggled to figure out what actual paths to use.

I created a mezzanine project, which is based on django, with the following commands. I list them here to make the paths explicit.

/var/www/mysite$ python3 -m venv ./venv
/var/www/mysite$ source ./venv/bin/activate
(venv) /var/www/mysite$ mezzanine-project mysite
(venv) /var/www/mysite$ cd mysite
(venv) /var/www/mysite/mysite$

Now, the path to the wsgi.py file is:

/var/www/mysite/mysite/mysite/wsgi.py

The directives that worked for this installation within my /etc/apache2/sites-available/mysite.conf file follow:

...<VirtualHost...>
    ...
    WSGIDaemonProcess mysite python-home=/var/www/mysite/venv python-path=/var/www/mysite/mysite
    WSGIProcessGroup mysite
    WSGIScriptAlias / /var/www/mysite/mysite/mysite/wsgi.py process-group=accounting
    <Directory /var/www/mysite/mysite/mysite>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>
    ...
</VirtualHost>...

I tried numerous versions of python-home and python-path and got the OP's error repeatedly. Using the correct paths here should also accomplish the same things as @Dev's answer without having to add paths in the wsgi.py file (supplied by mezzanine, and no editing necessary in my case).

React won't load local images

By doing a simple import you can access the image in React

import logo from "../images/logo.png";
<img src={logo}/>

Everything solved! Just a simple fix =)

What is the most efficient way to store tags in a database?

If you don't mind using a bit of non-standard stuff, Postgres version 9.4 and up has an option of storing a record of type JSON text array.

Your schema would be:

Table: Items
Columns: Item_ID:int, Title:text, Content:text

Table: Tags
Columns: Item_ID:int, Tag_Title:text[]

For more info, see this excellent post by Josh Berkus: http://www.databasesoup.com/2015/01/tag-all-things.html

There are more various options compared thoroughly for performance and the one suggested above is the best overall.

How does one get started with procedural generation?

the most important thing is to analyze how roads, cities, blocks and buildings are structured. find out what all eg buildings have in common. look at photos, maps, plans and reality. if you do that you will be one step ahead of people who consider city building as a merely computer-technological matter.

next you should develop solutions on how to create that geometry in tiny, distinct steps. you have to define rules that make up a believable city. if you are into 3d modelling you have to rethink a lot of what you have learned so the computer can follow your instructions in any situation.

in order to not loose track you should set up a lot of operators that are only responsible for little parts of the whole process. that makes debugging, expanding and improving your system much easier. in the next step you should link those operators and check the results by changing parameters.

i have seen too many "city generators" that mainly consist of random-shaped boxes with some window textures on them : (

Docker is installed but Docker Compose is not ? why?

I suggest using the official pkg on Mac. I guess docker-compose is no longer included with docker by default: https://docs.docker.com/toolbox/toolbox_install_mac/

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

Enabling WiFi on Android Emulator

The emulator does not provide virtual hardware for Wi-Fi if you use API 24 or earlier. From the Android Developers website:

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

You can disable Wi-Fi in the emulator by running the emulator with the command-line parameter -feature -Wifi.

https://developer.android.com/studio/run/emulator.html#wi-fi

What's not supported

The Android Emulator doesn't include virtual hardware for the following:

  • Bluetooth
  • NFC
  • SD card insert/eject
  • Device-attached headphones
  • USB

The watch emulator for Android Wear doesn't support the Overview (Recent Apps) button, D-pad, and fingerprint sensor.

(read more at https://developer.android.com/studio/run/emulator.html#about)

https://developer.android.com/studio/run/emulator.html#wi-fi

How to force a web browser NOT to cache images

You must use a unique filename(s). Like this

<img src="cars.png?1287361287" alt="">

But this technique means high server usage and bandwidth wastage. Instead, you should use the version number or date. Example:

<img src="cars.png?2020-02-18" alt="">

But you want it to never serve image from cache. For this, if the page does not use page cache, it is possible with PHP or server side.

<img src="cars.png?<?php echo time();?>" alt="">

However, it is still not effective. Reason: Browser cache ... The last but most effective method is Native JAVASCRIPT. This simple code finds all images with a "NO-CACHE" class and makes the images almost unique. Put this between script tags.

var items = document.querySelectorAll("img.NO-CACHE");
for (var i = items.length; i--;) {
    var img = items[i];
    img.src = img.src + '?' + Date.now();
}

USAGE

<img class="NO-CACHE" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png" alt="">

RESULT(s) Like This

https://example.com/image.png?1582018163634

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

Running

set terminal pngcairo dashed
set output 'test.png'
test
set output

gives:

enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
test
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2
    

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
    
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
    
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

How to connect TFS in Visual Studio code

I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).

This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.

Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.

Azure_Repo_Settings

Then under Tfvc: Location you can paste the location of the executable.

Location_Settings

For 2017 it'll be

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Or for 2019 (Preview)

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.

Git_URL

After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone pasted my repo:

Git_Repo

Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen

Team_Button

Then chose the new method of authentication

New_Method

Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).

Enter_Code_Screen

Click Continue

Continue_Button

Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.

Bottom_Bar

Cheers!

How to validate a form with multiple checkboxes to have atleast one checked

The above addMethod by Lod Lawson is not completely correct. It's $.validator and not $.validate and the validator method name cb_selectone requires quotes. Here is a corrected version that I tested:

$.validator.addMethod('cb_selectone', function(value,element){
    if(element.length>0){
        for(var i=0;i<element.length;i++){
            if($(element[i]).val('checked')) return true;
        }
        return false;
    }
    return false;
}, 'Please select at least one option');

Check if xdebug is working

Just to extend KsaRs answer and provide a possibility to check xdebug from command line:

php -r "echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';"

How to use the ProGuard in Android Studio?

You're probably not actually signing the release build of the APK via the signing wizard. You can either build the release APK from the command line with the command:

./gradlew assembleRelease

or you can choose the release variant from the Build Variants view and build it from the GUI:

IDE main window showing Build Variants

Good PHP ORM Library?

Give a shot to dORM, an object relational mapper for PHP 5. It supports all kinds of relationships (1-to-1), (1-to-many), (many-to-many) and data types. It is completely unobtrusive: no code generation or class extending required. In my opinion it is superior to any ORM out there, Doctrine and Propel included. However, it is still in beta and might change significantly in the next couple months. http://www.getdorm.com

It also has a very small learning curve. The three main methods you will use are:

<?php 
$object = $dorm->getClassName('id_here');
$dorm->save($object);
$dorm->delete($object);

Manually install Gradle and use it in Android Studio

https://services.gradle.org/distributions/

Download The Latest Gradle Distribution File and Extract It, Then Copy all Files and Paste it Under:

C:\Users\{USERNAME}\.gradle\wrapper\dists\

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

Could you post the connection string you're using that's giving you trouble?
You might need to add the port number to the Data Source value, as omitting it can also produce SQL Error 26.

E.g.: Data Source=ServerHostName\SQLServerInstanceName,1433

Which regular expression operator means 'Don't' match this character?

^ used at the beginning of a character range, or negative lookahead/lookbehind assertions.

>>> re.match('[^f]', 'foo')
>>> re.match('[^f]', 'bar')
<_sre.SRE_Match object at 0x7f8b102ad6b0>
>>> re.match('(?!foo)...', 'foo')
>>> re.match('(?!foo)...', 'bar')
<_sre.SRE_Match object at 0x7f8b0fe70780>

How to use ConfigurationManager

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

How do I display a text file content in CMD?

If you want it to display the content of the file live, and update when the file is altered, just use this script:

@echo off
:start
cls
type myfile.txt
goto start

That will repeat forever until you close the cmd window.

Convert Python dict into a dataframe

d = {'Date': list(yourDict.keys()),'Date_Values': list(yourDict.values())}
df = pandas.DataFrame(data=d)

If you don't encapsulate yourDict.keys() inside of list() , then you will end up with all of your keys and values being placed in every row of every column. Like this:

Date \ 0 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
1 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
2 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
3 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
4 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...

But by adding list() then the result looks like this:

Date Date_Values 0 2012-06-08 388 1 2012-06-09 388 2 2012-06-10 388 3 2012-06-11 389 4 2012-06-12 389 ...

How to fix the height of a <div> element?

You can try max-height: 70px; See if that works.

Vertically align an image inside a div with responsive height

Make another div and add both 'dummy' and 'img-container' inside the div

Do HTML and CSS like follows

_x000D_
_x000D_
html , body {height:100%;}_x000D_
.responsive-container { height:100%; display:table; text-align:center; width:100%;}_x000D_
.inner-container {display:table-cell; vertical-align:middle;}
_x000D_
<div class="responsive-container">_x000D_
    <div class="inner-container">_x000D_
  <div class="dummy">Sample</div>_x000D_
  <div class="img-container">_x000D_
   Image tag_x000D_
  </div>_x000D_
 </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Instead of 100% for the 'responsive-container' you can give the height that you want.,

How to use hex() without 0x in Python?

>>> format(3735928559, 'x')
'deadbeef'

Run Stored Procedure in SQL Developer?

With simple parameter types (i.e. not refcursors etc.) you can do something like this:

SET serveroutput on;
DECLARE
    InParam1 number;
    InParam2 number;
    OutParam1 varchar2(100);
    OutParam2 varchar2(100);
    OutParam3 varchar2(100);
    OutParam4 number;
BEGIN
    /* Assign values to IN parameters */
    InParam1 := 33;
    InParam2 := 89;

    /* Call procedure within package, identifying schema if necessary */
    schema.package.procedure(InParam1, InParam2,
        OutParam1, OutParam2, OutParam3, OutParam4);

    /* Display OUT parameters */
    dbms_output.put_line('OutParam1: ' || OutParam1);
    dbms_output.put_line('OutParam2: ' || OutParam2);
    dbms_output.put_line('OutParam3: ' || OutParam3);
    dbms_output.put_line('OutParam4: ' || OutParam4);
END;
/


Edited to use the OP's spec, and with an alternative approach to utilise :var bind variables:

var InParam1 number;
var InParam2 number;
var OutParam1 varchar2(100);
var OutParam2 varchar2(100);
var OutParam3 varchar2(100);
var OutParam4 number;

BEGIN
    /* Assign values to IN parameters */
    :InParam1 := 33;
    :InParam2 := 89;

    /* Call procedure within package, identifying schema if necessary */
    schema.package.procedure(:InParam1, :InParam2,
        :OutParam1, :OutParam2, :OutParam3, :OutParam4);
END;
/

-- Display OUT parameters
print :OutParam1;
print :OutParam2;
print :OutParam3;
print :OutParam4;

Convert timestamp in milliseconds to string formatted time in Java

Doing

logEvent.timeStamp / (1000*60*60)

will give you hours, not minutes. Try:

logEvent.timeStamp / (1000*60)

and you will end up with the same answer as

TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)

How to delete from a text file, all lines that contain a specific string?

You can use good old ed to edit a file in a similar fashion to the answer that uses ex. The big difference in this case is that ed takes its commands via standard input, not as command line arguments like ex can. When using it in a script, the usual way to accomodate this is to use printf to pipe commands to it:

printf "%s\n" "g/pattern/d" w | ed -s filename

or with a heredoc:

ed -s filename <<EOF
g/pattern/d
w
EOF

Is an entity body allowed for an HTTP DELETE request?

Just a heads up, if you supply a body in your DELETE request and are using a google cloud HTTPS load balancer, it will reject your request with a 400 error. I was banging my head against a wall and came to found out that Google, for whatever reason, thinks a DELETE request with a body is a malformed request.

jQuery Ajax Request inside Ajax Request

Here is an example:

$.ajax({
        type: "post",
        url: "ajax/example.php",
        data: 'page=' + btn_page,
        success: function (data) {
            var a = data; // This line shows error.
            $.ajax({
                type: "post",
                url: "example.php",
                data: 'page=' + a,
                success: function (data) {

                }
            });
        }
    });

How to run sql script using SQL Server Management Studio?

Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.

Socket send and receive byte array

First, do not use DataOutputStream unless it’s really necessary. Second:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

Sending JSON to PHP using ajax

Lose the contentType: "application/json; charset=utf-8",. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).

That should make what you have work.

Thing is, you don't need to use JSON.stringify or json_decode here at all. Just do:

data: {myData:postData},

Then in PHP:

$obj = $_POST['myData'];

How to loop through an associative array and get the key?

Nobody answered with regular for loop? Sometimes I find it more readable and prefer for over foreach
So here it is:

$array = array('key1' => 'value1', 'key2' => 'value2'); 

$keys = array_keys($array);

for($i=0; $i < count($keys); ++$i) {
    echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n";
}

/*
  prints:
  key1 value1
  key2 value2
*/

Reading an image file in C/C++

Check out Intel Open CV library ...

Get selected element's outer HTML

jQuery plugin as a shorthand to directly get the whole element HTML:

jQuery.fn.outerHTML = function () {
    return jQuery('<div />').append(this.eq(0).clone()).html();
};

And use it like this: $(".element").outerHTML();

How to dismiss keyboard iOS programmatically when pressing return

Try to get an idea about what a first responder is in iOS view hierarchy. When your textfield becomes active(or first responder) when you touch inside it (or pass it the messasge becomeFirstResponder programmatically), it presents the keyboard. So to remove your textfield from being the first responder, you should pass the message resignFirstResponder to it there.

[textField resignFirstResponder];

And to hide the keyboard on its return button, you should implement its delegate method textFieldShouldReturn: and pass the resignFirstResponder message.

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

How to show first commit by 'git log'?

You can just reverse your log and just head it for the first result.

git log --pretty=oneline --reverse | head -1

`getchar()` gives the same output as the input string

According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:

putchar(c);
printf("\n");     
c = getchar();

Now look at the output compared to the original code.

Another example that will explain you the concept of getchar and buffered stdin :

void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}

Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.

This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.

Wrapping long text without white space inside of a div

You can't wrap that text as it's unbroken without any spaces. You need a JavaScript or server side solution which splits the string after a few characters.

EDIT

You need to add this property in CSS.

word-wrap: break-word;

Better way to set distance between flexbox items

I came across the same issue earlier, then stumbled upon the answer for this. Hope it will help others for future reference.

long answer short, add a border to your child flex-items. then you can specify margins between flex-items to whatever you like. In the snippet, i use black for illustration purposes, you can use 'transparent' if you like.

_x000D_
_x000D_
#box {_x000D_
  display: flex;_x000D_
  width: 100px;_x000D_
  /* margin: 0 -5px; *remove this*/_x000D_
}_x000D_
.item {_x000D_
  background: gray;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  /* margin: 0 5px; *remove this*/_x000D_
  border: 1px solid black; /* add this */_x000D_
}_x000D_
.item.special{ margin: 0 10px; }
_x000D_
<div id='box'>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item special'></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Change image source in code behind - Wpf

You just need one line:

ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));

Force Java timezone as GMT/UTC

Hope below code will help you.

    DateFormat formatDate = new SimpleDateFormat(ISO_DATE_TIME_PATTERN);
    formatDate.setTimeZone(TimeZone.getTimeZone("UTC")); 
    formatDate.parse(dateString);

Do HttpClient and HttpClientHandler have to be disposed between requests?

Dispose() calls the code below, which closes the connections opened by the HttpClient instance. The code was created by decompiling with dotPeek.

HttpClientHandler.cs - Dispose

ServicePointManager.CloseConnectionGroups(this.connectionGroupName);

If you don't call dispose then ServicePointManager.MaxServicePointIdleTime, which runs by a timer, will close the http connections. The default is 100 seconds.

ServicePointManager.cs

internal static readonly TimerThread.Callback s_IdleServicePointTimeoutDelegate = new TimerThread.Callback(ServicePointManager.IdleServicePointTimeoutCallback);
private static volatile TimerThread.Queue s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(100000);

private static void IdleServicePointTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
  ServicePoint servicePoint = (ServicePoint) context;
  if (Logging.On)
    Logging.PrintInfo(Logging.Web, SR.GetString("net_log_closed_idle", (object) "ServicePoint", (object) servicePoint.GetHashCode()));
  lock (ServicePointManager.s_ServicePointTable)
    ServicePointManager.s_ServicePointTable.Remove((object) servicePoint.LookupString);
  servicePoint.ReleaseAllConnectionGroups();
}

If you haven't set the idle time to infinite then it appears safe not to call dispose and let the idle connection timer kick-in and close the connections for you, although it would be better for you to call dispose in a using statement if you know you are done with an HttpClient instance and free up the resources faster.

Difference between setUp() and setUpBeforeClass()

The @BeforeClass and @AfterClass annotated methods will be run exactly once during your test run - at the very beginning and end of the test as a whole, before anything else is run. In fact, they're run before the test class is even constructed, which is why they must be declared static.

The @Before and @After methods will be run before and after every test case, so will probably be run multiple times during a test run.

So let's assume you had three tests in your class, the order of method calls would be:

setUpBeforeClass()

  (Test class first instance constructed and the following methods called on it)
    setUp()
    test1()
    tearDown()

  (Test class second instance constructed and the following methods called on it)
    setUp()
    test2()
    tearDown()

  (Test class third instance constructed and the following methods called on it)
    setUp()
    test3()
    tearDown()

tearDownAfterClass()

How to convert a Java object (bean) to key-value pairs (and vice versa)?

We can use the Jackson library to convert a Java object into a Map easily.

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.6.3</version>
</dependency>

If using in an Android project, you can add jackson in your app's build.gradle as follows:

implementation 'com.fasterxml.jackson.core:jackson-core:2.9.8'
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.9.8'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.8'

Sample Implementation

public class Employee {

    private String name;
    private int id;
    private List<String> skillSet;

    // getters setters
}

public class ObjectToMap {

 public static void main(String[] args) {

    ObjectMapper objectMapper = new ObjectMapper();

    Employee emp = new Employee();
    emp.setName("XYZ");
    emp.setId(1011);
    emp.setSkillSet(Arrays.asList("python","java"));

    // object -> Map
    Map<String, Object> map = objectMapper.convertValue(emp, 
    Map.class);
    System.out.println(map);

 }

}

Output:

{name=XYZ, id=1011, skills=[python, java]}

How do I find Waldo with Mathematica?

I don't know Mathematica . . . too bad. But I like the answer above, for the most part.

Still there is a major flaw in relying on the stripes alone to glean the answer (I personally don't have a problem with one manual adjustment). There is an example (listed by Brett Champion, here) presented which shows that they, at times, break up the shirt pattern. So then it becomes a more complex pattern.

I would try an approach of shape id and colors, along with spacial relations. Much like face recognition, you could look for geometric patterns at certain ratios from each other. The caveat is that usually one or more of those shapes is occluded.

Get a white balance on the image, and red a red balance from the image. I believe Waldo is always the same value/hue, but the image may be from a scan, or a bad copy. Then always refer to an array of the colors that Waldo actually is: red, white, dark brown, blue, peach, {shoe color}.

There is a shirt pattern, and also the pants, glasses, hair, face, shoes and hat that define Waldo. Also, relative to other people in the image, Waldo is on the skinny side.

So, find random people to obtain an the height of people in this pic. Measure the average height of a bunch of things at random points in the image (a simple outline will produce quite a few individual people). If each thing is not within some standard deviation from each other, they are ignored for now. Compare the average of heights to the image's height. If the ratio is too great (e.g., 1:2, 1:4, or similarly close), then try again. Run it 10(?) of times to make sure that the samples are all pretty close together, excluding any average that is outside some standard deviation. Possible in Mathematica?

This is your Waldo size. Walso is skinny, so you are looking for something 5:1 or 6:1 (or whatever) ht:wd. However, this is not sufficient. If Waldo is partially hidden, the height could change. So, you are looking for a block of red-white that ~2:1. But there has to be more indicators.

  1. Waldo has glasses. Search for two circles 0.5:1 above the red-white.
  2. Blue pants. Any amount of blue at the same width within any distance between the end of the red-white and the distance to his feet. Note that he wears his shirt short, so the feet are not too close.
  3. The hat. Red-white any distance up to twice the top of his head. Note that it must have dark hair below, and probably glasses.
  4. Long sleeves. red-white at some angle from the main red-white.
  5. Dark hair.
  6. Shoe color. I don't know the color.

Any of those could apply. These are also negative checks against similar people in the pic -- e.g., #2 negates wearing a red-white apron (too close to shoes), #5 eliminates light colored hair. Also, shape is only one indicator for each of these tests . . . color alone within the specified distance can give good results.

This will narrow down the areas to process.

Storing these results will produce a set of areas that should have Waldo in it. Exclude all other areas (e.g., for each area, select a circle twice as big as the average person size), and then run the process that @Heike laid out with removing all but red, and so on.

Any thoughts on how to code this?


Edit:

Thoughts on how to code this . . . exclude all areas but Waldo red, skeletonize the red areas, and prune them down to a single point. Do the same for Waldo hair brown, Waldo pants blue, Waldo shoe color. For Waldo skin color, exclude, then find the outline.

Next, exclude non-red, dilate (a lot) all the red areas, then skeletonize and prune. This part will give a list of possible Waldo center points. This will be the marker to compare all other Waldo color sections to.

From here, using the skeletonized red areas (not the dilated ones), count the lines in each area. If there is the correct number (four, right?), this is certainly a possible area. If not, I guess just exclude it (as being a Waldo center . . . it may still be his hat).

Then check if there is a face shape above, a hair point above, pants point below, shoe points below, and so on.

No code yet -- still reading the docs.

Creating a list of pairs in java

just fixing some small mistakes in Mark Elliot's code:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

This occurred for me when I had a source ip constraint on the policy being used by the user (access key / secret key) to create the s3 bucket. My IP was accurate--but for some reason it wouldn't work and gave this error.

What does the 'Z' mean in Unix timestamp '120314170138Z'?

Yes. 'Z' stands for Zulu time, which is also GMT and UTC.

From http://en.wikipedia.org/wiki/Coordinated_Universal_Time:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.

Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.

From wikipedia again, http://en.wikipedia.org/wiki/Nautical_time:

Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.

Getting date format m-d-Y H:i:s.u from milliseconds

With PHP 7.0+ now here you can do the following:

$dateString = substr($millseconds_go_here,0,10);
$drawDate = new \DateTime(Date('Y-m-d H:i',$dateString));
$drawDate->setTimezone(new \DateTimeZone('UTC'));

This does the following in order:

  1. Trims the last 4 zeros off the string so Date() can handle the date.
  2. Uses date to format the milliseconds into a date time string that DateTime can understand.
  3. DateTime() can then allow you to modify the time zone you are in, but ensure that date_default_timezone_set("Timezone"); is set before you use DateTime() functions and classes.
  4. It is good practice to use a constructor in your classes to make sure your in the correct timezone when DateTime() classes or functions are used.

PHP Curl And Cookies

First create temporary cookie using tempnam() function:

$ckfile = tempnam ("/tmp", "CURLCOOKIE");

Then execute curl init witch saves the cookie as a temporary file:

$ch = curl_init ("http://uri.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

Or visit a page using the cookie stored in the temporary file:

$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);

This will initialize the cookie for the page:

curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);

Button Center CSS

Consider adding this to your CSS to resolve the problem:

.btn {
  width: 20%;
  margin-left: 40%;
  margin-right: 30%;
}

exclude @Component from @ComponentScan

I needed to exclude an auditing @Aspect @Component from the app context but only for a few test classes. I ended up using @Profile("audit") on the aspect class; including the profile for normal operations but excluding it (don't put it in @ActiveProfiles) on the specific test classes.

JavaFX 2.1 TableView refresh items

JavaFX8

I'm adding new Item by a DialogBox. Here is my code.

ObservableList<Area> area = FXCollections.observableArrayList();

At initialize() or setApp()

this.areaTable.setItems(getAreaData());

getAreaData()

private ObservableList<Area> getAreaData() {
    try {
        area = AreaDAO.searchEmployees(); // To inform ObservableList
        return area;
    } catch (ClassNotFoundException | SQLException e) {
        System.out.println("Error: " + e);
        return null;
    }
}

Add by dialog box.

@FXML
private void handleNewArea() {
    Area tempArea = new Area();
    boolean okClicked = showAreaDialog(tempArea);
    if (okClicked) {
        addNewArea(tempArea);
        this.area.add(tempArea); // To inform ObservableList
    }

}

Area is an ordinary JavaFX POJO. Hope this helps someone.

How do I enable TODO/FIXME/XXX task tags in Eclipse?

There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)

Installing Python 2.7 on Windows 8

How to install Python / Pip on Windows Steps

  1. Visit the official Python download page and grab the Windows installer for the latest version of Python 3. python.org/downloads/
  2. Run the installer. Be sure to check the option to add Python to your PATH while installing.

  3. Open PowerShell as admin by right clicking on the PowerShell icon and selecting ‘Run as Admin’

  4. To solve permission issues, run the following command:

Set-ExecutionPolicy Unrestricted

  1. Next, set the system’s PATH variable to include directories that include Python components and packages we’ll add later. To do this: C:\Python35-32;C:\Python35-32\Lib\site-packages\;C:\Python35-32\Scripts\

  2. download the bootstrap scripts for easy_install and pip from https://bootstrap.pypa.io/ ez_setup.py get-pip.py

  3. Save both the files in Python Installed folder Go to Python folder and run following: Python ez_setup.py Python get-pip.py

  4. To create a Virtual Environment, use the following commands:

cd c:\python pip install virtualenv virtualenv test .\test\Scripts\activate.ps1 pip install IPython ipython3 Now You can install any Python package with pip

That’s it !! happy coding Visit This link for Easy steps of Installation python and pip in windows http://rajendralora.com/?p=183

find index of an int in a list

Use the .IndexOf() method of the list. Specs for the method can be found on MSDN.

installing python packages without internet and using source code as .tar.gz and .whl

We have a similar situation at work, where the production machines have no access to the Internet; therefore everything has to be managed offline and off-host.

Here is what I tried with varied amounts of success:

  1. basket which is a small utility that you run on your internet-connected host. Instead of trying to install a package, it will instead download it, and everything else it requires to be installed into a directory. You then move this directory onto your target machine. Pros: very easy and simple to use, no server headaches; no ports to configure. Cons: there aren't any real showstoppers, but the biggest one is that it doesn't respect any version pinning you may have; it will always download the latest version of a package.

  2. Run a local pypi server. Used pypiserver and devpi. pypiserver is super simple to install and setup; devpi takes a bit more finagling. They both do the same thing - act as a proxy/cache for the real pypi and as a local pypi server for any home-grown packages. localshop is a new one that wasn't around when I was looking, it also has the same idea. So how it works is your internet-restricted machine will connect to these servers, they are then connected to the Internet so that they can cache and proxy the actual repository.

The problem with the second approach is that although you get maximum compatibility and access to the entire repository of Python packages, you still need to make sure any/all dependencies are installed on your target machines (for example, any headers for database drivers and a build toolchain). Further, these solutions do not cater for non-pypi repositories (for example, packages that are hosted on github).

We got very far with the second option though, so I would definitely recommend it.

Eventually, getting tired of having to deal with compatibility issues and libraries, we migrated the entire circus of servers to commercially supported docker containers.

This means that we ship everything pre-configured, nothing actually needs to be installed on the production machines and it has been the most headache-free solution for us.

We replaced the pypi repositories with a local docker image server.

getting the X/Y coordinates of a mouse click on an image with jQuery

Here is a better script:

$('#mainimage').click(function(e)
{   
    var offset_t = $(this).offset().top - $(window).scrollTop();
    var offset_l = $(this).offset().left - $(window).scrollLeft();

    var left = Math.round( (e.clientX - offset_l) );
    var top = Math.round( (e.clientY - offset_t) );

    alert("Left: " + left + " Top: " + top);

});

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

We added some WCF SOAP related things to an existing IIS site and it caused this problem, with the site refusing to honour the web.config authentication redirect.

We tried the various fixes listed without success, and invented a work around of mapping the new weird URL back to the one we've been using for years:

<urlMappings enabled="true">
<add mappedUrl="~/loginout.aspx" url="~/Account/Login"/>
</urlMappings>

That worked but it's ugly. Eventually we traced it down to a web.config entry added by Visual Studio some time earlier:

<add key="webpages:Enabled" value="true" />

As we'd been unable to work out precisely what that does, we took it out, which solved the problem for us immediately.

Android Studio doesn't start, fails saying components not installed

One possible solution is to open Android SDK Manager from

C:\Users\%user%\AppData\Local\Android\sdk

Check Android SDK build tool 21.1.1 download and install. Restart Android Studio

pip install from git repo branch

You used the egg files install procedure. This procedure supports installing over git, git+http, git+https, git+ssh, git+git and git+file. Some of these are mentioned.

It's good you can use branches, tags, or hashes to install.

@Steve_K noted it can be slow to install with "git+" and proposed installing via zip file:

pip install https://github.com/user/repository/archive/branch.zip

Alternatively, I suggest you may install using the .whl file if this exists.

pip install https://github.com/user/repository/archive/branch.whl

It's pretty new format, newer than egg files. It requires wheel and setuptools>=0.8 packages. You can find more in here.

Error in model.frame.default: variable lengths differ

Joran suggested to first remove the NAs before running the model. Thus, I removed the NAs, run the model and obtained the residuals. When I updated model2 by inclusion of the lagged residuals, the error message did not appear again.

Remove NAs

df2<-df1[complete.cases(df1),]

Run the main model

model2<-gam(death ~ pm10 + s(trend,k=14*7)+ s(temp,k=5), data=df2, family=poisson)

Obtain residuals

resid2 <- residuals(model2,type="deviance")

Update model2 by including the lag 1 residuals

model2_1 <- update(model2,.~.+ Lag(resid2,1),  na.action=na.omit)

When should a class be Comparable and/or Comparator?

Comparable is for providing a default ordering on data objects, for example if the data objects have a natural order.

A Comparator represents the ordering itself for a specific use.

Change default text in input type="file"?

You can use this approach, it works even if a lot of files inputs.

_x000D_
_x000D_
const fileBlocks = document.querySelectorAll('.file-block')_x000D_
const buttons = document.querySelectorAll('.btn-select-file')_x000D_
_x000D_
;[...buttons].forEach(function (btn) {_x000D_
  btn.onclick = function () {_x000D_
    btn.parentElement.querySelector('input[type="file"]').click()_x000D_
  }_x000D_
})_x000D_
_x000D_
;[...fileBlocks].forEach(function (block) {_x000D_
  block.querySelector('input[type="file"]').onchange = function () {_x000D_
    const filename = this.files[0].name_x000D_
_x000D_
    block.querySelector('.btn-select-file').textContent = 'File selected: ' + filename_x000D_
  }_x000D_
})
_x000D_
.btn-select-file {_x000D_
  border-radius: 20px;_x000D_
}_x000D_
_x000D_
input[type="file"] {_x000D_
  display: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="file-block">_x000D_
  <button class="btn-select-file">Select Image 1</button>_x000D_
  <input type="file">_x000D_
</div>_x000D_
<br>_x000D_
<div class="file-block">_x000D_
  <button class="btn-select-file">Select Image 2</button>_x000D_
  <input type="file">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Today I also met this problem. Here is how I solved it:

  1. I built the app, then I saw the errors in the message window. They said the picture (with the full path) was malformed.
  2. Then I found the malformed png which had the name xxx.9.png.
  3. I renamed it to xxx9.png and rebuilt. There were no errors, and the java files with the red wave under the name are gone too.

How do I see which version of Swift I'm using?

hi frind code type in terminal swift -v

print teminal Welcome to Apple Swift version 5.2.4 (swiftlang-1103.0.32.9 clang-1103.0.32.53).

C++ unordered_map using a custom class type as the key

check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.

  • the custom class must implement the == operator
  • must create a hash function for the class (for primitive types like int and also types like string the hash function is predefined)

How to add parameters into a WebRequest?

The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.

//Visual Basic Implementation Request and Response String
  Dim params = "key1=value1&key2=value2"
    Dim byteArray = UTF8.GetBytes(params)
    Dim url = "https://okay.com"
    Dim client = WebRequest.Create(url)
    client.Method = "POST"
    client.ContentType = "application/x-www-form-urlencoded"
    client.ContentLength = byteArray.Length
    Dim stream = client.GetRequestStream()

    //sending the data
    stream.Write(byteArray, 0, byteArray.Length)
    stream.Close()

//getting the full response in a stream        
Dim response = client.GetResponse().GetResponseStream()

//reading the response 
Dim result = New StreamReader(response)

//Writes response string to Console
    Console.WriteLine(result.ReadToEnd())
    Console.ReadKey()

How can I combine flexbox and vertical scroll in a full-height app?

Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

The solution is setting a height to the vertical scrollable element. For example:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 0px;
}

The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px;

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 100px; /* == min-height: 100px*/
}

So the best solution if you want a min-height in the vertical scroll:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 100px;
}

If you just want full vertical scroll in case there is no enough space to see the article:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 0px;
}

The final code: http://jsfiddle.net/ch7n6/867/

How to import an existing project from GitHub into Android Studio

Unzip the github project to a folder. Open Android Studio. Go to File -> New -> Import Project. Then choose the specific project you want to import and then click Next->Finish. It will build the Gradle automatically and'll be ready for you to use.

P.S: In some versions of Android Studio a certain error occurs-
error:package android.support.v4.app does not exist.
To fix it go to Gradle Scripts->build.gradle(Module:app) and the add the dependecies:

dependencies {      
    compile fileTree(dir: 'libs', include: ['*.jar'])  
    compile 'com.android.support:appcompat-v7:21.0.3'  
}

Enjoy working in Android Studio

How can I use jQuery to make an input readonly?

The setReadOnly(state) is very useful for forms, we can set any field to setReadOnly(state) directly or from various condition.But I prefer to use readOnly for setting opacity to the selector otherwise the attr='disabled' also worked like the same way.

readOnly examples:

$('input').setReadOnly(true);

or through the various codition like

var same = this.checked;
$('input').setReadOnly(same);

here we are using the state boolean value to set and remove readonly attribute from the input depending on a checkbox click.

Convert List to Pandas Dataframe Column

if your list looks like this: [1,2,3] you can do:

lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']
df

to get this:

    col1    col2    col3
0   1       2       3

alternatively you can create a column as follows:

import numpy as np
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df

to get this:

  col1
0   1
1   2
2   3

Calling a particular PHP function on form submit

Assuming that your script is named x.php, try this

<?php 
   function display($s) {
      echo $s;
   }
?>
<html>
    <body>
        <form method="post" action="x.php">
            <input type="text" name="studentname">
            <input type="submit" value="click">
        </form>
        <?php
           if($_SERVER['REQUEST_METHOD']=='POST')
           {
               display();
           } 
        ?>
    </body>
</html>

How to find whether MySQL is installed in Red Hat?

If you're looking for the RPM.

rpm -qa | grep MySQL

Most of it's data is stored in /var/lib/mysql so that's another good place to look.

If it is installed

which mysql

will give you the location of the binary.

You could also do an

updatedb

and a

locate mysql

to find any mysql files.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

mAddTaskButton is null because you never initialize it with:

mAddTaskButton = (Button) findViewById(R.id.addTaskButton);

before you call mAddTaskButton.setOnClickListener().

Vertical align text in block element

According to the CSS Flexible Box Layout Module, you can declare the a element as a flex container (see figure) and use align-items to vertically align text along the cross axis (which is perpendicular to the main axis).

enter image description here

All you need to do is:

display: flex;
align-items: center;

See this fiddle.

Convert list to dictionary using linq and not worrying about duplicates

        DataTable DT = new DataTable();
        DT.Columns.Add("first", typeof(string));
        DT.Columns.Add("second", typeof(string));

        DT.Rows.Add("ss", "test1");
        DT.Rows.Add("sss", "test2");
        DT.Rows.Add("sys", "test3");
        DT.Rows.Add("ss", "test4");
        DT.Rows.Add("ss", "test5");
        DT.Rows.Add("sts", "test6");

        var dr = DT.AsEnumerable().GroupBy(S => S.Field<string>("first")).Select(S => S.First()).
            Select(S => new KeyValuePair<string, string>(S.Field<string>("first"), S.Field<string>("second"))).
           ToDictionary(S => S.Key, T => T.Value);

        foreach (var item in dr)
        {
            Console.WriteLine(item.Key + "-" + item.Value);
        }

How Do I Make Glyphicons Bigger? (Change Size?)

try to use heading, no need extra css

<h1 class="glyphicon glyphicon-plus"></h1>

PHP Configuration: It is not safe to rely on the system's timezone settings

try this, it works for me.

date_default_timezone_set('America/New_York');

In the actual file that was complaining.

How to remove margin space around body or clear default css styles

body has default margins: http://www.w3.org/TR/CSS2/sample.html

body { margin:0; } /* Remove body margins */

Or you could use this useful Global reset

* { margin:0; padding:0; box-sizing:border-box; }

If you want something less * global than:

html, body, body div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, figure, footer, header, hgroup, menu, nav, section, time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent;
}

some other CSS Reset:

http://yui.yahooapis.com/3.5.0/build/cssreset/cssreset-min.css
http://meyerweb.com/eric/tools/css/reset/
https://github.com/necolas/normalize.css/
http://html5doctor.com/html-5-reset-stylesheet/

Adjust icon size of Floating action button (fab)

As your content is 24dp x 24dp you should use 24dp icon. And then set android:scaleType="center" in your ImageButton to avoid auto resize.

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

I've been having the same issue for days now with an integration that also just "used to work before".

Out of sheer depression, I just tried

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

This solved it for me..even though the integration strictly only makes use of SSLv3.

I came to the realization that something if off since Fiddler reported saying that there is an "empty TLS negotiation cipher" or something of the like.

Hopefully it works!

Javascript string/integer comparisons

Parse the string into an integer using parseInt:

javascript:alert(parseInt("2", 10)>parseInt("10", 10))

PHP - If variable is not empty, echo some html code

You're using isset, what isset does is check if the variable is set ('exists') and is not NULL. What you're looking for is empty, which checks if a variable is empty or not, even if it's set. To check what is empty and what is not take a look at:

http://php.net/manual/en/function.empty.php

Also check http://php.net/manual/en/function.isset.php for what isset does exactly, so you understand why it doesn't do what you expect it to do.

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

How does one extract each folder name from a path?

string mypath = @"..\folder1\folder2\folder2";
string[] directories = mypath.Split(Path.DirectorySeparatorChar);

Edit: This returns each individual folder in the directories array. You can get the number of folders returned like this:

int folderCount = directories.Length;

How do I get length of list of lists in Java?

count of the contained lists in the outmost list

int count = data.size();

lambda to get the count of the contained inner lists

int count = data.stream().collect( summingInt(l -> l.size()) );

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

I addition to the accepted answer, the error can also occur when the destination folder is read-only (Common when using TFS)

tsql returning a table from a function or store procedure

You don't need (shouldn't use) a function as far as I can tell. The stored procedure will return tabular data from any SELECT statements you include that return tabular data.

A stored proc does not use RETURN statements.

 CREATE PROCEDURE name
 AS

 SELECT stuff INTO #temptbl1

 .......


 SELECT columns FROM #temptbln

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

How to convert a GUID to a string in C#?

you are missing () on the end of ToString.

multiple plot in one figure in Python

EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday

I found this a while back when learning python

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure() 
# create figure window

gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns 


ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]


ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)


fig.add_subplot(ax) #add 'ax' to figure

you can make different sizes in one figure as well, use slices in that case:

 gs = gridspec.GridSpec(3, 3)
 ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns

consult the docs for more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)

SQLException : String or binary data would be truncated

Most of the answers here are to do the obvious check, that the length of the column as defined in the database isn't smaller than the data you are trying to pass into it.

Several times I have been bitten by going to SQL Management Studio, doing a quick:

sp_help 'mytable'

and be confused for a few minutes until I realize the column in question is an nvarchar, which means the length reported by sp_help is really double the real length supported because it's a double byte (unicode) datatype.

i.e. if sp_help reports nvarchar Length 40, you can store 20 characters max.

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

size_t is defined by the C standard to be the unsigned integer return type of the sizeof operator (C99 6.3.5.4.4), and the argument of malloc and friends (C99 7.20.3.3 etc). The actual range is set such that the maximum (SIZE_MAX) is at least 65535 (C99 7.18.3.2).

However, this doesn't let us determine sizeof(size_t). The implementation is free to use any representation it likes for size_t - so there is no upper bound on size - and the implementation is also free to define a byte as 16-bits, in which case size_t can be equivalent to unsigned char.

Putting that aside, however, in general you'll have 32-bit size_t on 32-bit programs, and 64-bit on 64-bit programs, regardless of the data model. Generally the data model only affects static data; for example, in GCC:

`-mcmodel=small'
     Generate code for the small code model: the program and its
     symbols must be linked in the lower 2 GB of the address space.
     Pointers are 64 bits.  Programs can be statically or dynamically
     linked.  This is the default code model.

`-mcmodel=kernel'
     Generate code for the kernel code model.  The kernel runs in the
     negative 2 GB of the address space.  This model has to be used for
     Linux kernel code.

`-mcmodel=medium'
     Generate code for the medium model: The program is linked in the
     lower 2 GB of the address space but symbols can be located
     anywhere in the address space.  Programs can be statically or
     dynamically linked, but building of shared libraries are not
     supported with the medium model.

`-mcmodel=large'
     Generate code for the large model: This model makes no assumptions
     about addresses and sizes of sections.

You'll note that pointers are 64-bit in all cases; and there's little point to having 64-bit pointers but not 64-bit sizes, after all.

Github: error cloning my private repository

I received this error after moving git across hard drives. Deleting and reinstalling in the new location fixed things

Calling remove in foreach loop in Java

for (String name : new ArrayList<String>(names)) {
    // Do something
    names.remove(nameToRemove);
}

You clone the list names and iterate through the clone while you remove from the original list. A bit cleaner than the top answer.

How to import component into another root component in Angular 2

For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations key, so add CoursesComponent in your main module declarations as below and remove directives from AppComponent metadata.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, CoursesComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

How to ping ubuntu guest on VirtualBox

In most cases simply switching the virtual machine network adapter to bridged mode is enough to make the guest machine accessible from outside.

Switching virtual machine network adapter type

Sometimes it's possible for the guest machine to not automatically receive an IP which matches the host's IP range after switching to bridged mode (even after rebooting the guest machine). This is often caused by a malfunctioning or badly configured DHCP on the host network.

For example, if the host IP is 192.168.1.1 the guest machine needs to have an IP in the format 192.168.1.* where only the last group of numbers is allowed to be different from the host IP.

You can use a terminal (shell) and type ifconfig (ipconfig for Windows guests) to check what IP is assigned to the guest machine and change it if required.

Getting the guest's machine IP

If the host and guest IPs do not match simply setting a static IP for the guest machine explicitly should resolve the issue.

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

How to delete a remote tag?

Seems like a lot of work for something xargs already does. Looking back through this thread, I'm guessing the slowness with xargs that you experienced is because the original answer used xargs -n 1 when it didn't really need to.

This is equivalent to your method one except that xargs automatically deals with the maximum command line length:

git tag | sorting_processing_etc | xargs git push --delete origin

xargs can run processes in parallel too. Method 2 with xargs:

git tag | sorting_processing_etc | xargs -P 5 -n 100 git push --delete origin

The above uses a maximum of 5 processes to handle a maximum of 100 arguments in each process. You can experiment with the arguments to find what works best for your needs.

Entity Framework : How do you refresh the model when the db changes?

Here:

  1. Delete the Tables from the EDMX designer
  2. Rebuild Project/SLN (this will clear the model class)
  3. Update Model from Database(readd all the tables you want)
  4. Rebuild project/SLN (this will recreate your model class including the new columns)

How to center align the ActionBar title in Android?

Here's a quick tip to center align the action:

android:label=" YourTitle"

Assuming that you have Actionbar Enable, You can add this in your activity with some space (Can be adjusted) to place the title at the center.

However, This is just diddly and unreliable method. You probably shouldn't do that. So, The best thing to do is to create a custom ActionBar. So, What you wanna do is remove the default Actionbar and use this to replace it as an ActionBar.

<androidx.constraintlayout.widget.ConstraintLayout
        android:elevation="30dp"
        android:id="@+id/customAction"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="@color/colorOnMain"
        android:orientation="horizontal">
        

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:textAllCaps="true"
            android:textColor="#FFF"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

I have used Constraint Layout to center the textView and used 10dp elevation with 56dp height so that it looks as same as the default ActionBar.

how to call scalar function in sql server 2008

For Scalar Function Syntax is

Select dbo.Function_Name(parameter_name)

Select dbo.Department_Employee_Count('HR')

Making an asynchronous task in Flask

You can also try using multiprocessing.Process with daemon=True; the process.start() method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.

I experienced similar problem while working with falcon framework and using daemon process helped.

You'd need to do the following:

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
        target=my_func,
        daemon=True
    )
    heavy_process.start()
    return Response(
        mimetype='application/json',
        status=200
    )

# Define some heavy function
def my_func():
    time.sleep(10)
    print("Process finished")

You should get a response immediately and, after 10s you should see a printed message in the console.

NOTE: Keep in mind that daemonic processes are not allowed to spawn any child processes.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

jQuery: Currency Format Number

$(document).ready(function() {
    var num = $('div.number').text()
    num = addPeriod(num);
    $('div.number').text('Rp. '+num)
});

function addPeriod(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

Sending files using POST with HttpURLConnection

Here is what i did for uploading photo using post request.

public void uploadFile(int directoryID, String filePath) {
    Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();

    String upload_url = BASE_URL + UPLOAD_FILE;
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

    byte[] data = bao.toByteArray();

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(upload_url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    try {
        // Set Data and Content-type header for the image
        FileBody fb = new FileBody(new File(filePath), "image/jpeg");
        StringBody contentString = new StringBody(directoryID + "");

        entity.addPart("file", fb);
        entity.addPart("directory_id", contentString);
        postRequest.setEntity(entity);

        HttpResponse response = httpClient.execute(postRequest);
        // Read the response
        String jsonString = EntityUtils.toString(response.getEntity());
        Log.e("response after uploading file ", jsonString);

    } catch (Exception e) {
        Log.e("Error in uploadFile", e.getMessage());
    }
}

NOTE: This code requires libraries so Follow the instructions here in order to get the libraries.

C# error: Use of unassigned local variable

The compiler only knows that the code is or isn't reachable if you use "return". Think of Environment.Exit() as a function that you call, and the compiler don't know that it will close the application.

How to make a smooth image rotation in Android?

Rotation Object programmatically.

// clockwise rotation :

    public void rotate_Clockwise(View view) {
        ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", 180f, 0f);
//        rotate.setRepeatCount(10);
        rotate.setDuration(500);
        rotate.start();
    }

// AntiClockwise rotation :

 public void rotate_AntiClockwise(View view) {
        ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", 0f, 180f);
//        rotate.setRepeatCount(10);
        rotate.setDuration(500);
        rotate.start();
    } 

view is object of your ImageView or other widgets.

rotate.setRepeatCount(10); use to repeat your rotation.

500 is your animation time duration.

Error - is not marked as serializable

If you store an object in session state, that object must be serializable.

http://www.hpenterprisesecurity.com/vulncat/en/vulncat/dotnet/asp_dotnet_bad_practices_non_serializable_object_stored_in_session.html


edit:

In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable] attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable interface.

https://vulncat.hpefod.com/en/detail?id=desc.structural.dotnet.asp_dotnet_bad_practices_non_serializable_object_stored_in_session#C%23%2fVB.NET%2fASP.NET

Writing html form data to a txt file without the use of a webserver

You can use JavaScript:

<script type ="text/javascript">
 function WriteToFile(passForm) {

    set fso = CreateObject("Scripting.FileSystemObject");  
    set s = fso.CreateTextFile("C:\test.txt", True);
    s.writeline(document.passForm.input1.value);
    s.writeline(document.passForm.input2.value);
    s.writeline(document.passForm.input3.value);
    s.Close();
 }
  </script>

If this does not work, an alternative is the ActiveX object:

<script type = "text/javascript">
function WriteToFile(passForm)
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\Test.txt", true);
s.WriteLine(document.passForm.input.value);
s.Close();
}
</script>

Unfortunately, the ActiveX object, to my knowledge, is only supported in IE.

Could not insert new outlet connection: Could not find any information for the class named

enter image description here

I selected Automatic option to select the ViewController.swift file. And then I can able to take outlets.

include antiforgerytoken in ajax post ASP.NET MVC

The token won't work if it was supplied by a different controller. E.g. it won't work if the view was returned by the Accounts controller, but you POST to the Clients controller.

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

Macbook solution:

Step 1: stop the server running Java :

Open Activity Monitor by going to Applications > Utilities > Activity Monitor. Or simple press CMD + Spacebar and start typing Activity Monitor. Look for process running Java and kill it by giving the following command in Terminal

kill -STOP <PID> 

where PID is the process ID of the Java process as displayed in the Activity Monitor. Do it a couple of times and close and reopen Activity Monitor to check Java isn't running.

Step 2: change the port :

right-click on the server in Eclipse and click 'Open'. Change port number from 8080 to 8081 or something greater in value.

This should hopefully start your server.

How can I solve a connection pool problem between ASP.NET and SQL Server?

I just had the same problem and wanted to share what helped me find the source: Add the Application name to your connection string and then monitor the open connections to the SQL Server

select st.text,
    es.*, 
    ec.*
from sys.dm_exec_sessions as es
    inner join sys.dm_exec_connections as ec on es.session_id = ec.session_id
    cross apply sys.dm_exec_sql_text(ec.most_recent_sql_handle) st
where es.program_name = '<your app name here>'

How to index into a dictionary?

oh, that's a tough one. What you have here, basically, is two values for each item. Then you are trying to call them with a number as the key. Unfortunately, one of your values is already set as the key!

Try this:

colors = {1: ["blue", "5"], 2: ["red", "6"], 3: ["yellow", "8"]}

Now you can call the keys by number as if they are indexed like a list. You can also reference the color and number by their position within the list.

For example,

colors[1][0]
// returns 'blue'

colors[3][1]
// returns '8'

Of course, you will have to come up with another way of keeping track of what location each color is in. Maybe you can have another dictionary that stores each color's key as it's value.

colors_key = {'blue': 1, 'red': 6, 'yllow': 8}

Then, you will be able to also look up the colors key if you need to.

colors[colors_key['blue']][0] will return 'blue'

Something like that.

And then, while you're at it, you can make a dict with the number values as keys so that you can always use them to look up your colors, you know, if you need.

values = {5: [1, 'blue'], 6: [2, 'red'], 8: [3, 'yellow']}

Then, (colors[colors_key[values[5][1]]][0]) will return 'blue'.

Or you could use a list of lists.

Good luck!

How do I add a custom script to my package.json file that runs a javascript file?

Steps are below:

  1. In package.json add:

    "bin":{
        "script1": "bin/script1.js" 
    }
    
  2. Create a bin folder in the project directory and add file runScript1.js with the code:

    #! /usr/bin/env node
    var shell = require("shelljs");
    shell.exec("node step1script.js");
    
  3. Run npm install shelljs in terminal

  4. Run npm link in terminal

  5. From terminal you can now run script1 which will run node script1.js

Reference: http://blog.npmjs.org/post/118810260230/building-a-simple-command-line-tool-with-npm

How do I install PyCrypto on Windows?

If you don't already have a C/C++ development environment installed that is compatible with the Visual Studio binaries distributed by Python.org, then you should stick to installing only pure Python packages or packages for which a Windows binary is available.

Fortunately, there are PyCrypto binaries available for Windows: http://www.voidspace.org.uk/python/modules.shtml#pycrypto

UPDATE:
As @Udi suggests in the comment below, the following command also installs pycrypto and can be used in virtualenv as well:

easy_install http://www.voidspace.org.uk/python/pycrypto-2.6.1/pycrypto-2.6.1.win32-py2.7.exe

Notice to choose the relevant link for your setup from this list

If you're looking for builds for Python 3.5, see PyCrypto on python 3.5

Response Content type as CSV

I have found that the problem with IE is that it sniffs the return data and makes up its own mind about what content-type it thinks it has been sent. There are a number of side effect that this causes, such as always openning a saveAs dialog for text files because you are using compression of data trasnferes. The solution is (in php code)......

header('X-Content-Type-Options: nosniff');

How to run Gulp tasks sequentially one after the other

run-sequence is the most clear way (at least until Gulp 4.0 is released)

With run-sequence, your task will look like this:

var sequence = require('run-sequence');
/* ... */
gulp.task('develop', function (done) {
    sequence('clean', 'coffee', done);
});

But if you (for some reason) prefer not using it, gulp.start method will help:

gulp.task('develop', ['clean'], function (done) {
    gulp.on('task_stop', function (event) {
        if (event.task === 'coffee') {
            done();
        }
    });
    gulp.start('coffee');
});

Note: If you only start task without listening to result, develop task will finish earlier than coffee, and that may be confusing.

You may also remove event listener when not needed

gulp.task('develop', ['clean'], function (done) {
    function onFinish(event) {
        if (event.task === 'coffee') {
            gulp.removeListener('task_stop', onFinish);
            done();
        }
    }
    gulp.on('task_stop', onFinish);
    gulp.start('coffee');
});

Consider there is also task_err event you may want to listen to. task_stop is triggered on successful finish, while task_err appears when there is some error.

You may also wonder why there is no official documentation for gulp.start(). This answer from gulp member explains the things:

gulp.start is undocumented on purpose because it can lead to complicated build files and we don't want people using it

(source: https://github.com/gulpjs/gulp/issues/426#issuecomment-41208007)

How to check the Angular version?

In the terminal type in either ng -v or ng --version.

Sorting a Data Table

Try this:

Dim dataView As New DataView(table)
dataView.Sort = " AutoID DESC, Name DESC"
Dim dataTable AS DataTable = dataView.ToTable()

Angular/RxJs When should I unsubscribe from `Subscription`

For handling subscription I use a "Unsubscriber" class.

Here is the Unsubscriber Class.

export class Unsubscriber implements OnDestroy {
  private subscriptions: Subscription[] = [];

  addSubscription(subscription: Subscription | Subscription[]) {
    if (Array.isArray(subscription)) {
      this.subscriptions.push(...subscription);
    } else {
      this.subscriptions.push(subscription);
    }
  }

  unsubscribe() {
    this.subscriptions
      .filter(subscription => subscription)
      .forEach(subscription => {
        subscription.unsubscribe();
      });
  }

  ngOnDestroy() {
    this.unsubscribe();
  }
}

And You can use this class in any component / Service / Effect etc.

Example:

class SampleComponent extends Unsubscriber {
    constructor () {
        super();
    }

    this.addSubscription(subscription);
}

How to convert .crt to .pem

I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.

openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text

Android and setting width and height programmatically in dp units

simplest way(and even works from api 1) that tested is:

getResources().getDimensionPixelSize(R.dimen.example_dimen);

From documentations:

Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension(int), except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.

Yes it rounding the value but it's not very bad(just in odd values on hdpi and ldpi devices need to add a little value when ldpi is not very common) I tested in a xxhdpi device that converts 4dp to 16(pixels) and that is true.

PHP foreach with Nested Array?

Both syntaxes are correct. But the result would be Array. You probably want to do something like this:

foreach ($tmpArray[1] as $value) {
  echo $value[0];
  foreach($value[1] as $val){
    echo $val;
  }
}

This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).

How to dynamically change a web page's title?

Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.

Creating a range of dates in Python

import datetime    
def date_generator():
    cur = base = datetime.date.today()
    end  = base + datetime.timedelta(days=100)
    delta = datetime.timedelta(days=1)
    while(end>base):
        base = base+delta
        print base

date_generator()

Convert Python program to C/C++ code?

Yes. Look at Cython. It does just that: Converts Python to C for speedups.

PHP json_decode() returns NULL with valid JSON?

This worked for me

json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );

Multiple Updates in MySQL

UPDATE `your_table` SET 

`something` = IF(`id`="1","new_value1",`something`), `smth2` = IF(`id`="1", "nv1",`smth2`),
`something` = IF(`id`="2","new_value2",`something`), `smth2` = IF(`id`="2", "nv2",`smth2`),
`something` = IF(`id`="4","new_value3",`something`), `smth2` = IF(`id`="4", "nv3",`smth2`),
`something` = IF(`id`="6","new_value4",`something`), `smth2` = IF(`id`="6", "nv4",`smth2`),
`something` = IF(`id`="3","new_value5",`something`), `smth2` = IF(`id`="3", "nv5",`smth2`),
`something` = IF(`id`="5","new_value6",`something`), `smth2` = IF(`id`="5", "nv6",`smth2`) 

// You just building it in php like

$q = 'UPDATE `your_table` SET ';

foreach($data as $dat){

  $q .= '

       `something` = IF(`id`="'.$dat->id.'","'.$dat->value.'",`something`), 
       `smth2` = IF(`id`="'.$dat->id.'", "'.$dat->value2.'",`smth2`),';

}

$q = substr($q,0,-1);

So you can update hole table with one query

How to use MD5 in javascript to transmit a password

If someone is sniffing your plain-text HTTP traffic (or cache/cookies) for passwords just turning the password into a hash won't help - The hash password can be "replayed" just as well as plain-text. The client would need to hash the password with something somewhat random (like the date and time) See the section on "AUTH CRAM-MD5" here: http://www.fehcom.de/qmail/smtpauth.html

Is there a link to the "latest" jQuery library on Google APIs?

No. There isn't..

But, for development there is such a link on the jQuery code site.