Programs & Examples On #Mvs

MVS is the name for the IBM OS/VS operating system released in the late 1970s, and the name was used through MVS/ESA 5.2. The name was replaced by OS/390 in the mid-1990s, which itself was replaced by z/OS in the early 2000s.

How to resolve Value cannot be null. Parameter name: source in linq?

Value cannot be null. Parameter name: source

Above error comes in situation when you are querying the collection which is null.

For demonstration below code will result in such an exception.

Console.WriteLine("Hello World");
IEnumerable<int> list = null;
list.Where(d => d ==4).FirstOrDefault();

Here is the output of the above code.

Hello World Run-time exception (line 11): Value cannot be null. Parameter name: source

Stack Trace:

[System.ArgumentNullException: Value cannot be null. Parameter name: source] at Program.Main(): line 11

In your case ListMetadataKor is null. Here is the fiddle if you want to play around.

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

what does this mean ? image/png;base64?

That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

How to pause in C?

you can put

getchar();

before the return from the main function. That will wait for a character input before exiting the program.

Alternatively you could run your program from a command line and the output would be visible.

Do you know the Maven profile for mvnrepository.com?

Please use this profile

  <profiles>
    <profile>
        <repositories>
            <repository>
                <id>mvnrepository</id>
                <name>mvnrepository</name>
                <url>http://www.mvnrepository.com</url>
            </repository>
        </repositories>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>mvnrepository</activeProfile>
  </activeProfiles>

Creating the checkbox dynamically using JavaScript?

You're trying to put a text node inside an input element.

Input elements are empty and can't have children.

...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";

var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));

container.appendChild(checkbox);
container.appendChild(label);

Convert or extract TTC font to TTF - how to?

Assuming that Windows doesn't really know how to deal with TTC files (which I honestly find strange), you can "split" the combined fonts in an easy way if you use fontforge.

The steps are:

  1. Download the file.
  2. Unzip it (e.g., unzip "STHeiti Medium.ttc.zip").
  3. Load Fontforge.
  4. Open it with Fontforge (e.g., File > Open).
  5. Fontforge will tell you that there are two fonts "packed" in this particular TTC file (at least as of 2014-01-29) and ask you to choose one.
  6. After the font is loaded (it may take a while, as this font is very large), you can ask Fontforge to generate the TTF file via the menu File > Generate Fonts....

Repeat the steps of loading 4--6 for the other font and you will have your TTFs readily usable for you.

Note that I emphasized generating instead of saving above: saving the font will create a file in Fontforge's specific SFD format, which is probably useless to you, unless you want to develop fonts with Fontforge.

If you want to have a more programmatic/automatic way of manipulating fonts, then you might be interested in my answer to a similar (but not exactly the same) question.

Addenda

Further comments: One reason why some people may be interested in performing the splitting mentioned above (or using a font converter after all) is to convert the fonts to web formats (like WOFF). That's great, but be careful to see if the license of the fonts that you are splitting/converting allows such wide redistribution.

Of course, for Free ("as in Freedom") fonts, you don't need to worry (and one of the most prominent licenses of such fonts is the OFL).

Drop rows with all zeros in pandas data frame

It turns out this can be nicely expressed in a vectorized fashion:

> df = pd.DataFrame({'a':[0,0,1,1], 'b':[0,1,0,1]})
> df = df[(df.T != 0).any()]
> df
   a  b
1  0  1
2  1  0
3  1  1

a tag as a submit button?

in my opinion the easiest way would be somthing like this:

<?php>
echo '<a href="link.php?submit='.$value.'">Submit</a>';
</?>

within the "link.php" you can request the value like this:

$_REQUEST['submit']

Specify system property to Maven project

Is there a way ( I mean how do I ) set a system property in a maven project? I want to access a property from my test [...]

You can set system properties in the Maven Surefire Plugin configuration (this makes sense since tests are forked by default). From Using System Properties:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <systemPropertyVariables>
            <propertyName>propertyValue</propertyName>
            <buildDirectory>${project.build.directory}</buildDirectory>
            [...]
          </systemPropertyVariables>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

and my webapp ( running locally )

Not sure what you mean here but I'll assume the webapp container is started by Maven. You can pass system properties on the command line using:

mvn -DargLine="-DpropertyName=propertyValue"

Update: Ok, got it now. For Jetty, you should also be able to set system properties in the Maven Jetty Plugin configuration. From Setting System Properties:

<project>
  ...
  <plugins>
    ...
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <configuration>
         ...
         <systemProperties>
            <systemProperty>
              <name>propertyName</name>
              <value>propertyValue</value>
            </systemProperty>
            ...
         </systemProperties>
        </configuration>
      </plugin>
  </plugins>
</project>

Changing ImageView source

Supplemental visual answer

ImageView: setImageResource() (standard method, aspect ratio is kept)

enter image description here

View: setBackgroundResource() (image is stretched)

enter image description here

Both

enter image description here

My fuller answer is here.

How to enable GZIP compression in IIS 7.5

Sometimes no matter what you do or follow whole internet posts. Try on the MIMETYPES of applicationhost.config of the server.

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/httpcompression/#configuration-sample

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

Using Default Arguments in a Function

You can't do this directly, but a little code fiddling makes it possible to emulate.

function foo($blah, $x = false, $y = false) {
  if (!$x) $x = "some value";
  if (!$y) $y = "some other value";

  // code
}

TokenMismatchException in VerifyCsrfToken.php Line 67

Try php artisan cache:clear or manually delete storage cache from server.

Regex match text between tags

var root = document.createElement("div");

root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var texts = [].map.call( root.querySelectorAll("b"), function(v){
    return v.textContent || v.innerText || "";
});

//["Bob", "20", "programming"]

Maximum request length exceeded.

If you are using IIS for hosting your application, then the default upload file size is 4MB. To increase it, please use this below section in your web.config -

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Note:

  • maxRequestLength is measured in kilobytes
  • maxAllowedContentLength is measured in bytes

which is why the values differ in this config example. (Both are equivalent to 1 GB.)

How to fill the whole canvas with specific color?

You know what, there is an entire library for canvas graphics. It is called p5.js You can add it with just a single line in your head element and an additional sketch.js file.

Do this to your html and body tags first:

<html style="margin:0 ; padding:0">
<body style="margin:0 ; padding:0">

Add this to your head:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script type="text/javascript" src="sketch.js"></script>

The sketch.js file

function setup() {
    createCanvas(windowWidth, windowHeight);
    background(r, g, b);
}

If my interface must return Task what is the best way to have a no-operation implementation?

When you must return specified type:

Task.FromResult<MyClass>(null);

Calculate median in c#

Looks like other answers are using sorting. That's not optimal from performance point of view because it takes O(n logn) time. It is possible to calculate median in O(n) time instead. The generalized version of this problem is known as "n-order statistics" which means finding an element K in a set such that we have n elements smaller or equal to K and rest are larger or equal K. So 0th order statistic would be minimal element in the set (Note: Some literature use index from 1 to N instead of 0 to N-1). Median is simply (Count-1)/2-order statistic.

Below is the code adopted from Introduction to Algorithms by Cormen et al, 3rd Edition.

/// <summary>
/// Partitions the given list around a pivot element such that all elements on left of pivot are <= pivot
/// and the ones at thr right are > pivot. This method can be used for sorting, N-order statistics such as
/// as median finding algorithms.
/// Pivot is selected ranodmly if random number generator is supplied else its selected as last element in the list.
/// Reference: Introduction to Algorithms 3rd Edition, Corman et al, pp 171
/// </summary>
private static int Partition<T>(this IList<T> list, int start, int end, Random rnd = null) where T : IComparable<T>
{
    if (rnd != null)
        list.Swap(end, rnd.Next(start, end+1));

    var pivot = list[end];
    var lastLow = start - 1;
    for (var i = start; i < end; i++)
    {
        if (list[i].CompareTo(pivot) <= 0)
            list.Swap(i, ++lastLow);
    }
    list.Swap(end, ++lastLow);
    return lastLow;
}

/// <summary>
/// Returns Nth smallest element from the list. Here n starts from 0 so that n=0 returns minimum, n=1 returns 2nd smallest element etc.
/// Note: specified list would be mutated in the process.
/// Reference: Introduction to Algorithms 3rd Edition, Corman et al, pp 216
/// </summary>
public static T NthOrderStatistic<T>(this IList<T> list, int n, Random rnd = null) where T : IComparable<T>
{
    return NthOrderStatistic(list, n, 0, list.Count - 1, rnd);
}
private static T NthOrderStatistic<T>(this IList<T> list, int n, int start, int end, Random rnd) where T : IComparable<T>
{
    while (true)
    {
        var pivotIndex = list.Partition(start, end, rnd);
        if (pivotIndex == n)
            return list[pivotIndex];

        if (n < pivotIndex)
            end = pivotIndex - 1;
        else
            start = pivotIndex + 1;
    }
}

public static void Swap<T>(this IList<T> list, int i, int j)
{
    if (i==j)   //This check is not required but Partition function may make many calls so its for perf reason
        return;
    var temp = list[i];
    list[i] = list[j];
    list[j] = temp;
}

/// <summary>
/// Note: specified list would be mutated in the process.
/// </summary>
public static T Median<T>(this IList<T> list) where T : IComparable<T>
{
    return list.NthOrderStatistic((list.Count - 1)/2);
}

public static double Median<T>(this IEnumerable<T> sequence, Func<T, double> getValue)
{
    var list = sequence.Select(getValue).ToList();
    var mid = (list.Count - 1) / 2;
    return list.NthOrderStatistic(mid);
}

Few notes:

  1. This code replaces tail recursive code from the original version in book in to iterative loop.
  2. It also eliminates unnecessary extra check from original version when start==end.
  3. I've provided two version of Median, one that accepts IEnumerable and then creates a list. If you use the version that accepts IList then keep in mind it modifies the order in list.
  4. Above methods calculates median or any i-order statistics in O(n) expected time. If you want O(n) worse case time then there is technique to use median-of-median. While this would improve worse case performance, it degrades average case because constant in O(n) is now larger. However if you would be calculating median mostly on very large data then its worth to look at.
  5. The NthOrderStatistics method allows to pass random number generator which would be then used to choose random pivot during partition. This is generally not necessary unless you know your data has certain patterns so that last element won't be random enough or if somehow your code is exposed outside for targeted exploitation.
  6. Definition of median is clear if you have odd number of elements. It's just the element with index (Count-1)/2 in sorted array. But when you even number of element (Count-1)/2 is not an integer anymore and you have two medians: Lower median Math.Floor((Count-1)/2) and Math.Ceiling((Count-1)/2). Some textbooks use lower median as "standard" while others propose to use average of two. This question becomes particularly critical for set of 2 elements. Above code returns lower median. If you wanted instead average of lower and upper then you need to call above code twice. In that case make sure to measure performance for your data to decide if you should use above code VS just straight sorting.
  7. For .net 4.5+ you can add MethodImplOptions.AggressiveInlining attribute on Swap<T> method for slightly improved performance.

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

This answer is in three parts, see below for the official release (v3 and v4)

I couldn't even find the col-lg-push-x or pull classes in the original files for RC1 i downloaded, so check your bootstrap.css file. hopefully this is something they will sort out in RC2.

anyways, the col-push-* and pull classes did exist and this will suit your needs. Here is a demo

<div class="row">
    <div class="col-sm-5 col-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

EDIT: BELOW IS THE ANSWER FOR THE OFFICIAL RELEASE v3.0

Also see This blog post on the subject

  • col-vp-push-x = push the column to the right by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

  • col-vp-pull-x = pull the column to the left by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

    vp = xs, sm, md, or lg

    x = 1 thru 12

I think what messes most people up, is that you need to change the order of the columns in your HTML markup (in the example below, B comes before A), and that it only does the pushing or pulling on view-ports that are greater than or equal to what was specified. i.e. col-sm-push-5 will only push 5 columns on sm view-ports or greater. This is because Bootstrap is a "mobile first" framework, so your HTML should reflect the mobile version of your site. The Pushing and Pulling are then done on the larger screens.

  • (Desktop) Larger view-ports get pushed and pulled.
  • (Mobile) Smaller view-ports render in normal order.

DEMO

<div class="row">
    <div class="col-sm-5 col-sm-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-sm-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

View-port >= sm

|A|B|C|

View-port < sm

|B|
|A|
|C|

EDIT: BELOW IS THE ANSWER FOR v4.0

With v4 comes flexbox and other changes to the grid system and the push\pull classes have been removed in favor of using flexbox ordering.

  • Use .order-* classes to control visual order (where * = 1 thru 12)
  • This can also be grid tier specific .order-md-*
  • Also .order-first (-1) and .order-last (13) avalable

_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col order-2">1st yet 2nd</div>_x000D_
  <div class="col order-1">2nd yet 1st</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

merge one local branch into another local branch

First, checkout to your Branch3:

git checkout Branch3

Then merge the Branch1:

git merge Branch1

And if you want the updated commits of Branch1 on Branch2, you are probaly looking for git rebase

git checkout Branch2
git rebase Branch1

This will update your Branch2 with the latest updates of Branch1.

How do I change screen orientation in the Android emulator?

In my notebook, Dell Latitude E4310, the Ctrl+F12 keys do the job.

Where is SQL Server Management Studio 2012?

Install SQLEXPRADV_x64_ENU for x64 bit version from here and choose to install all components. This installs SQL Server Management Studio. You can also install Reporting Services with this installation.

/Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)/

Download Link: http://www.microsoft.com/en-us/download/details.aspx?id=29062

Retrieving Android API version programmatically

try this:

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
     // only for gingerbread and newer versions
 }

Initializing a static std::map<int, int> in C++

I would wrap the map inside a static object, and put the map initialisation code in the constructor of this object, this way you are sure the map is created before the initialisation code is executed.

Global Variable in app.js accessible in routes?

Here are explain well, in short:

http://www.hacksparrow.com/global-variables-in-node-js.html

So you are working with a set of Node modules, maybe a framework like Express.js, and suddenly feel the need to make some variables global. How do you make variables global in Node.js?

The most common advice to this one is to either "declare the variable without the var keyword" or "add the variable to the global object" or "add the variable to the GLOBAL object". Which one do you use?

First off, let's analyze the global object. Open a terminal, start a Node REPL (prompt).

> global.name
undefined
> global.name = 'El Capitan'
> global.name
'El Capitan'
> GLOBAL.name
'El Capitan'
> delete global.name
true
> GLOBAL.name
undefined
> name = 'El Capitan'
'El Capitan'
> global.name
'El Capitan'
> GLOBAL.name
'El Capitan'
> var name = 'Sparrow'
undefined
> global.name
'Sparrow'

How to update gradle in android studio?

For me I copied my fonts folder from the assets to the res folder and caused the problem because Android Studio didn't accept capitalized names. I switched to project view mode and deleted it then added it as font resource file by right clicking res folder.

How to drop all tables from a database with one SQL query?

Use the following script to drop all constraints:

DECLARE @sql NVARCHAR(max)=''

SELECT @sql += ' ALTER TABLE ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) +    ' NOCHECK CONSTRAINT all; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

Then run the following to drop all tables:

select @sql='';

SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

This worked for me in Azure SQL Database where 'sp_msforeachtable' was not available!

ArrayList or List declaration in Java

It is easy to change the implementation to List to Set:

Collection<String> stringList = new ArrayList<String>();
//Client side
stringList = new LinkedList<String>();

stringList = new HashSet<String>();
//stringList = new HashSet<>(); java 1.7 and 1.8

What's the strangest corner case you've seen in C# or .NET?

The following doesn't work:

if (something)
    doit();
else
    var v = 1 + 2;

But this works:

if (something)
    doit();
else {
    var v = 1 + 2;
}

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

Explanation

The error message told us, that the build-time dependency (in this case it is cc1) was not found, so all we need — install the appropriate package to the system (using package manager // from sources // another way)

What is cc1:

cc1 is the internal command which takes preprocessed C-language files and converts them to assembly. It's the actual part that compiles C. For C++, there's cc1plus, and other internal commands for different languages.

taken from this answer by Alan Shutko.

Solution for: Ubuntu / Linux Mint

sudo apt-get update
sudo apt-get install --reinstall build-essential

Solution for: Docker-alpine environment

If you are in docker-alpine environment install the build-base package by adding this to your Dockerfile:

RUN apk add build-base

Better package name provided by Pablo Castellano. More details here.

If you need more packages for building purposes, consider adding of the alpine-sdk package:

RUN apk add alpine-sdk

Taken from github

Solution for: CentOS/Fedora

This answer contains instructions for CentOS and Fedora Linux

Solution for: Amazon Linux

sudo yum install gcc72-c++

Taken from this comment by CoderChris

You could also try to install missed dependencies by this (though, it is said to not to solve the issue):

sudo yum install gcc-c++.noarch

Taken from this answer

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

If you (or a helpful admin) runs Set-ExecutionPolicy as administrator, the policy will be set for all users. (I would suggest "remoteSigned" rather than "unrestricted" as a safety measure.)

NB.: On a 64-bit OS you need to run Set-ExecutionPolicy for 32-bit and 64-bit PowerShell separately.

SyntaxError: cannot assign to operator

What do you think this is supposed to be: ((t[1])/length) * t[1] += string

Python can't parse this, it's a syntax error.

How can I check for IsPostBack in JavaScript?

Create a global variable in and apply the value

<script>
       var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
</script>

Then you can reference it from elsewhere

How do you get centered content using Twitter Bootstrap?

I tried two ways, and it worked fine to center the div. Both the ways will align the divs on all screens.

Way 1: Using Push:

<div class = "col-lg-4 col-md-4 col-sm-4 col-xs-4 col-lg-push-4 col-md-push-4 col-sm-push-4 col-xs-push-4" style="border-style:solid;border-width:1px">
    <h2>Grievance form</h2> <!-- To center this text, use style="text-align: center" -->
  </div>

Way 2: Using Offset:

<div class = "col-lg-4 col-md-4 col-sm-4 col-xs-4 col-lg-offset-4 col-md-offest-4 col-sm-offest-4 col-xs-offest-4" style="border-style:solid;border-width:1px">
    <h2>Grievance form</h2> <!--to center this text, use style="text-align: center"-->
</div>

Result:

Enter image description here

Explanation

Bootstrap will designate to the left, the first column of the specified screen-occupancy. If we use offset or push it will shift the 'this' column by 'those' many columns. Though I faced some issues in responsiveness of offset, push was awesome.

How can I parse a string with a comma thousand separator to a number?

With this function you will be able to format values in multiple formats like 1.234,56 and 1,234.56, and even with errors like 1.234.56 and 1,234,56

/**
 * @param {string} value: value to convert
 * @param {bool} coerce: force float return or NaN
 */
function parseFloatFromString(value, coerce) {
    value = String(value).trim();

    if ('' === value) {
        return value;
    }

    // check if the string can be converted to float as-is
    var parsed = parseFloat(value);
    if (String(parsed) === value) {
        return fixDecimals(parsed, 2);
    }

    // replace arabic numbers by latin
    value = value
    // arabic
    .replace(/[\u0660-\u0669]/g, function(d) {
        return d.charCodeAt(0) - 1632;
    })

    // persian
    .replace(/[\u06F0-\u06F9]/g, function(d) {
        return d.charCodeAt(0) - 1776;
    });

    // remove all non-digit characters
    var split = value.split(/[^\dE-]+/);

    if (1 === split.length) {
        // there's no decimal part
        return fixDecimals(parseFloat(value), 2);
    }

    for (var i = 0; i < split.length; i++) {
        if ('' === split[i]) {
            return coerce ? fixDecimals(parseFloat(0), 2) : NaN;
        }
    }

    // use the last part as decimal
    var decimal = split.pop();

    // reconstruct the number using dot as decimal separator
    return fixDecimals(parseFloat(split.join('') +  '.' + decimal), 2);
}

function fixDecimals(num, precision) {
    return (Math.floor(num * 100) / 100).toFixed(precision);
}
parseFloatFromString('1.234,56')
"1234.56"
parseFloatFromString('1,234.56')
"1234.56"
parseFloatFromString('1.234.56')
"1234.56"
parseFloatFromString('1,234,56')
"1234.56"

Disabling user input for UITextfield in swift

If you want to do it while keeping the user interaction on. In my case I am using (or rather misusing) isFocused

self.myField.inputView = UIView()

This way it will focus but keyboard won't show up.

How to grey out a button?

You could Also make it appear as disabled by setting the alpha (making it semi-transparent). This is especially useful if your button background is an image, and you don't want to create states for it.

button.setAlpha(.5f);
button.setClickable(false);

update: I wrote the above solution pre Kotlin and when I was a rookie. It's more of a "quick'n'dirty" solution, but I don't recommend it in a professional environment.

Today, if I wanted a generic solution that works on any button/view without having to create a state list, I would create a Kotlin extension.

fun View.disable() {
    getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
    setClickable(false)
}

In Java you can do something is similar with a static util function and you would just have to pass in the view as variable. It's not as clean but it works.

Center fixed div with dynamic width (CSS)

<div id="container">
    <div id="some_kind_of_popup">
        center me
    </div>
</div>

You'd need to wrap it in a container. here's the css

#container{
    position: fixed;
    top: 100px;
    width: 100%;
    text-align: center;
}
#some_kind_of_popup{
    display:inline-block;
    width: 90%;
    max-width: 900px;  
    min-height: 300px;  
}

C# : "A first chance exception of type 'System.InvalidOperationException'"

Consider using System.Windows.Forms.Timer instead of System.Threading.Timer for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.

In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.

How to tell if browser/tab is active

Using jQuery:

$(function() {
    window.isActive = true;
    $(window).focus(function() { this.isActive = true; });
    $(window).blur(function() { this.isActive = false; });
    showIsActive();
});

function showIsActive()
{
    console.log(window.isActive)
    window.setTimeout("showIsActive()", 2000);
}

function doWork()
{
    if (window.isActive) { /* do CPU-intensive stuff */}
}

How to generate random number in Bash?

You can also use shuf (available in coreutils).

shuf -i 1-100000 -n 1

Is there a developers api for craigslist.org

Craigslist does have a "bulk posting interface" which allows for multiple posts to happen at once through HTTPS POST. See:

http://www.craigslist.org/about/bulk_posting_interface

how to open a jar file in Eclipse

there is an Eclipse app called Import Jar As Project. I think it is quite simple and useful. https://marketplace.eclipse.org/content/import-jar-project?mpc=true&mpc_state=

Angular - POST uploaded file

Looking onto this issue Github - Request/Upload progress handling via @angular/http, angular2 http does not support file upload yet.

For very basic file upload I created such service function as a workaround (using ???????'s answer):

  uploadFile(file:File):Promise<MyEntity> {
    return new Promise((resolve, reject) => {

        let xhr:XMLHttpRequest = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(<MyEntity>JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        };

        xhr.open('POST', this.getServiceUrl(), true);

        let formData = new FormData();
        formData.append("file", file, file.name);
        xhr.send(formData);
    });
}

How do I record audio on iPhone with AVAudioRecorder?

START

NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);

NSError *error = nil;
NSString *filename = [NSString stringWithFormat:@"%@.caf",FILENAME];
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:filename];
NSURL *soundFileURL = [NSURL fileURLWithPath:path];


NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
                                [NSNumber numberWithInt:AVAudioQualityMedium],AVEncoderAudioQualityKey,
                                [NSNumber numberWithInt:AVAudioQualityMedium], AVSampleRateConverterAudioQualityKey,
                                [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                [NSNumber numberWithFloat:22050.0],AVSampleRateKey,
                                nil];

AVAudioRecorder *audioRecorder = [[AVAudioRecorder alloc]
                 initWithURL:soundFileURL
                 settings:recordSettings
                 error:&error];


if (!error && [audioRecorder prepareToRecord])
{
    [audioRecorder record];
}

STOP

[audioRecorder stop];
[audioRecorder release];
audioRecorder = nil;

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

http://help.github.com/forking/

iterating over and removing from a map

As of Java 8 you could do this as follows:

map.entrySet().removeIf(e -> <boolean expression>);

Oracle Docs: entrySet()

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa

How to select a single field for all documents in a MongoDB collection?

In mongodb 3.4 we can use below logic, i am not sure about previous versions

select roll from student ==> db.student.find(!{}, {roll:1})

the above logic helps to define some columns (if they are less)

How to send email attachments?

Below is combination of what I've found from SoccerPlayer's post Here and the following link that made it easier for me to attach an xlsx file. Found Here

file = 'File.xlsx'
username=''
password=''
send_from = ''
send_to = 'recipient1 , recipient2'
Cc = 'recipient'
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Cc'] = Cc
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = ''
server = smtplib.SMTP('smtp.gmail.com')
port = '587'
fp = open(file, 'rb')
part = MIMEBase('application','vnd.ms-excel')
part.set_payload(fp.read())
fp.close()
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename='Name File Here')
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(',') + msg['Cc'].split(','), msg.as_string())
smtp.quit()

jquery: $(window).scrollTop() but no $(window).scrollBottom()

This will scroll to the very top:

$(window).animate({scrollTop: 0});

This will scroll to the very bottom:

$(window).animate({scrollTop: $(document).height() + $(window).height()});

.. change window to your desired container id or class if necessary (in quotes).

How to _really_ programmatically change primary and accent color in Android Lollipop?

I used the Dahnark's code but I also need to change the ToolBar background:

if (dark_ui) {
    this.setTheme(R.style.Theme_Dark);

    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.Theme_Dark_primary));
        getWindow().setStatusBarColor(getResources().getColor(R.color.Theme_Dark_primary_dark));
    }
} else {
    this.setTheme(R.style.Theme_Light);
}

setContentView(R.layout.activity_main);

toolbar = (Toolbar) findViewById(R.id.app_bar);

if(dark_ui) {
    toolbar.setBackgroundColor(getResources().getColor(R.color.Theme_Dark_primary));
}

How do I use boolean variables in Perl?

Beautiful explanation given by bobf for Boolean values : True or False? A Quick Reference Guide

Truth tests for different values

                       Result of the expression when $var is:

Expression          | 1      | '0.0'  | a string | 0     | empty str | undef
--------------------+--------+--------+----------+-------+-----------+-------
if( $var )          | true   | true   | true     | false | false     | false
if( defined $var )  | true   | true   | true     | true  | true      | false
if( $var eq '' )    | false  | false  | false    | false | true      | true
if( $var == 0 )     | false  | true   | true     | true  | true      | true

AngularJS Error: $injector:unpr Unknown Provider

also one of the popular reasons maybe you miss to include the service file in your page

<script src="myservice.js"></script>

How to serve up images in Angular2?

In angular only one page is requested from server, that is index.html. And index.html and assets folder are on same directory. while putting image in any component give src value like assets\image.png. This will work fine because browser will make request to server for that image and webpack will be able serve that image.

equivalent of vbCrLf in c#

I think that "\r\n" should work fine

AngularJS sorting by property

As you can see in the code of angular-JS ( https://github.com/angular/angular.js/blob/master/src/ng/filter/orderBy.js ) ng-repeat does not work with objects. Here is a hack with sortFunction.

http://jsfiddle.net/sunnycpp/qaK56/33/

<div ng-app='myApp'>
    <div ng-controller="controller">
    <ul>
        <li ng-repeat="test in testData | orderBy:sortMe()">
            Order = {{test.value.order}} -> Key={{test.key}} Name=:{{test.value.name}}
        </li>
    </ul>
    </div>
</div>

myApp.controller('controller', ['$scope', function ($scope) {

    var testData = {
        a:{name:"CData", order: 2},
        b:{name:"AData", order: 3},
        c:{name:"BData", order: 1}
    };
    $scope.testData = _.map(testData, function(vValue, vKey) {
        return { key:vKey, value:vValue };
    }) ;
    $scope.sortMe = function() {
        return function(object) {
            return object.value.order;
        }
    }
}]);

Creating an index on a table variable

If Table variable has large data, then instead of table variable(@table) create temp table (#table).table variable doesn't allow to create index after insert.

 CREATE TABLE #Table(C1 int,       
  C2 NVarchar(100) , C3 varchar(100)
  UNIQUE CLUSTERED (c1) 
 ); 
  1. Create table with unique clustered index

  2. Insert data into Temp "#Table" table

  3. Create non clustered indexes.

     CREATE NONCLUSTERED INDEX IX1  ON #Table (C2,C3);
    

Preloading @font-face fonts?

Via Google's webfontloader

var fontDownloadCount = 0;
WebFont.load({
    custom: {
        families: ['fontfamily1', 'fontfamily2']
    },
    fontinactive: function() {
        fontDownloadCount++;
        if (fontDownloadCount == 2) {
            // all fonts have been loaded and now you can do what you want
        }
    }
});

Place cursor at the end of text in EditText

editText.setSelection is the magic here. Basically selection gives you place cursor at any position you want.

EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length());

This places cursor to end of EditText. Basically editText.getText().length() gives you text length. Then you use setSelection with length.

editText.setSelection(0);

It is for setting cursor at start position (0).

Creating files and directories via Python

import os

path = chap_name

if not os.path.exists(path):
    os.makedirs(path)

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
    temp_file.write(buff)

Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has '/' in it:

img_alt = os.path.basename(img_alt)

Create 3D array using Python

numpy.arrays are designed just for this case:

 numpy.zeros((i,j,k))

will give you an array of dimensions ijk, filled with zeroes.

depending what you need it for, numpy may be the right library for your needs.

C# How can I check if a URL exists/is valid?

This solution seems easy to follow:

public static bool isValidURL(string url) {
    WebRequest webRequest = WebRequest.Create(url);
    WebResponse webResponse;
    try
    {
        webResponse = webRequest.GetResponse();
    }
    catch //If exception thrown then couldn't get response from address
    {
        return false ;
    }
    return true ;
}

How to render an ASP.NET MVC view as a string?

If you want to forgo MVC entirely, thereby avoiding all the HttpContext mess...

using RazorEngine;
using RazorEngine.Templating; // For extension methods.

string razorText = System.IO.File.ReadAllText(razorTemplateFileLocation);
string emailBody = Engine.Razor.RunCompile(razorText, "templateKey", typeof(Model), model);

This uses the awesome open source Razor Engine here: https://github.com/Antaris/RazorEngine

How to control border height?

not bad .. but try this one ... (should works for all but ist just -webkit included)

<br>
<input type="text" style="
  background: transparent;
border-bottom: 1px solid #B5D5FF;
border-left: 1px solid;
border-right: 1px solid;
border-left-color: #B5D5FF;
border-image: -webkit-linear-gradient(top, #fff 50%, #B5D5FF 0%) 1 repeat;
">

//Feel free to edit and add all other browser..

Creating for loop until list.length

Yes you can, with range [docs]:

for i in range(1, len(l)):
    # i is an integer, you can access the list element with l[i]

but if you are accessing the list elements anyway, it's more natural to iterate over them directly:

for element in l:
   # element refers to the element in the list, i.e. it is the same as l[i]

If you want to skip the the first element, you can slice the list [tutorial]:

for element in l[1:]:
    # ...

can you do another for loop inside this for loop

Sure you can.

Formatting struct timespec

I wanted to ask the same question. Here is my current solution to obtain a string like this: 2013-02-07 09:24:40.749355372 I am not sure if there is a more straight forward solution than this, but at least the string format is freely configurable with this approach.

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

#define NANO 1000000000L

// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
    int ret;
    struct tm t;

    tzset();
    if (localtime_r(&(ts->tv_sec), &t) == NULL)
        return 1;

    ret = strftime(buf, len, "%F %T", &t);
    if (ret == 0)
        return 2;
    len -= ret - 1;

    ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
    if (ret >= len)
        return 3;

    return 0;
}

int main(int argc, char **argv) {
    clockid_t clk_id = CLOCK_REALTIME;
    const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
    char timestr[TIME_FMT];

    struct timespec ts, res;
    clock_getres(clk_id, &res);
    clock_gettime(clk_id, &ts);

    if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
        printf("timespec2str failed!\n");
        return EXIT_FAILURE;
    } else {
        unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
        printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
        return EXIT_SUCCESS;
    }
}

output:

gcc mwe.c -lrt 
$ ./a.out 
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501

How to use a servlet filter in Java to change an incoming servlet request url?

You could use the ready to use Url Rewrite Filter with a rule like this one:

<rule>
  <from>^/Check_License/Dir_My_App/Dir_ABC/My_Obj_([0-9]+)$</from>
  <to>/Check_License?Contact_Id=My_Obj_$1</to>
</rule>

Check the Examples for more... examples.

Running Python in PowerShell?

Since, you are able to run Python in PowerShell. You can just do python <scriptName>.py to run the script. So, for a script named test.py containing

name = raw_input("Enter your name: ")
print "Hello, " + name

The PowerShell session would be

PS C:\Python27> python test.py
Enter your name: Monty Python
Hello, Monty Python
PS C:\Python27>

How do I delete all messages from a single queue using the CLI?

In case you are using RabbitMQ with Docker your steps should be:

  1. Connect to container: docker exec -it your_container_id bash
  2. rabbitmqctl purge_queue Queue-1 (where Queue-1 is queue name)

Consider defining a bean of type 'service' in your configuration [Spring boot]

@SpringBootApplication @ComponentScan(basePackages = {"io.testapi"})

In the main class below springbootapplication annotation i have written componentscan and it worked for me.

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

If you are already extending from ActionBarActivity and you are trying to get the action bar from a fragment:

ActionBar mActionBar = (ActionBarActivity)getActivity()).getSupportActionBar();

ssh-copy-id no identities found error

Run following command

# ssh-add

If it gives following error: Could not open a connection to your authentication agent

To remove this error, Run following command:

# eval `ssh-agent`

How do I expire a PHP session after 30 minutes?

Please use following block of code in your include file which loaded in every pages.

$expiry = 1800 ;//session expiry required after 30 mins
    if (isset($_SESSION['LAST']) && (time() - $_SESSION['LAST'] > $expiry)) {
        session_unset();
        session_destroy();
    }
    $_SESSION['LAST'] = time();

How can I show/hide a specific alert with twitter bootstrap?

I had this problem today, was in a lot of time crunch, so below idea worked:

  • setTimeout with 1 sec -- call a function that shows the div
  • setTimeout with 10 sec -- call a function that hides the div

Fade is not there, but that bootstrap feeling will be there.

Hope that helps.

T-SQL split string based on delimiter

SELECT CASE 
        WHEN CHARINDEX('/', myColumn, 0) = 0
            THEN myColumn
        ELSE LEFT(myColumn, CHARINDEX('/', myColumn, 0)-1)
        END AS FirstName
    ,CASE 
        WHEN CHARINDEX('/', myColumn, 0) = 0
            THEN ''
        ELSE RIGHT(myColumn, CHARINDEX('/', REVERSE(myColumn), 0)-1)
        END AS LastName
FROM MyTable

Assigning variables with dynamic names in Java

If you want to access the variables some sort of dynamic you may use reflection. However Reflection works not for local variables. It is only applyable for class attributes.

A rough quick and dirty example is this:

public class T {
    public Integer n1;
    public Integer n2;
    public Integer n3;

    public void accessAttributes() throws IllegalArgumentException, SecurityException, IllegalAccessException,
            NoSuchFieldException {

        for (int i = 1; i < 4; i++) {
            T.class.getField("n" + i).set(this, 5);
        }
    }
}

You need to improve this code in various ways it is only an example. This is also not considered to be good code.

Wait .5 seconds before continuing code VB.net

Imports VB = Microsoft.VisualBasic

Public Sub wait(ByVal seconds As Single)
    Static start As Single
    start = VB.Timer()
    Do While VB.Timer() < start + seconds
        System.Windows.Forms.Application.DoEvents()
    Loop
End Sub

%20+ high cpu usage + no lag

Private Sub wait(ByVal seconds As Integer)
    For i As Integer = 0 To seconds * 100
        System.Threading.Thread.Sleep(10)
        Application.DoEvents()
    Next
End Sub

%0.1 cpu usage + high lag

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How can I change a file's encoding with vim?

From the doc:

:write ++enc=utf-8 russian.txt

So you should be able to change the encoding as part of the write command.

Get PostGIS version

Since some of the functions depend on other libraries like GEOS and proj4 you might want to get their versions too. Then use:

SELECT PostGIS_full_version();

PHP how to get the base domain/url?

/* Get sub domain or main domain url
 * $url is $_SERVER['SERVER_NAME']
 * $index int remove subdomain if acceess from sub domain my current url is https://support.abcd.com ("support" = 7 (char))
 * $subDomain string 
 * $issecure string https or http
 * return url
 * call like echo getUrl($_SERVER['SERVER_NAME'],7,"payment",true,false);
 * out put https://payment.abcd.com
 * second call echo getUrl($_SERVER['SERVER_NAME'],7,null,true,true);
*/
function getUrl($url,$index,$subDomain=null,$issecure=false,$www=true) {
  //$url=$_SERVER['SERVER_NAME']
  $protocol=($issecure==true) ?  "https://" : "http://";
  $url= substr($url,$index);
  $www =($www==true) ? "www": "";
  $url= empty($subDomain) ? $protocol.$url : 
  $protocol.$www.$subDomain.$url;
  return $url;
}

How to declare a Fixed length Array in TypeScript

The javascript array has a constructor that accepts the length of the array:

let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]

However, this is just the initial size, there's no restriction on changing that:

arr.push(5);
console.log(arr); // [undefined × 3, 5]

Typescript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

How do I compare a value to a backslash?

Try like this:

if message.value[0] == "/" or message.value[0] == "\\":
  do_stuff

How to run vbs as administrator from vbs?

Add this to the beginning of your file:

Set WshShell = WScript.CreateObject("WScript.Shell")
If WScript.Arguments.Length = 0 Then
  Set ObjShell = CreateObject("Shell.Application")
  ObjShell.ShellExecute "wscript.exe" _
    , """" & WScript.ScriptFullName & """ RunAsAdministrator", , "runas", 1
  WScript.Quit
End if

"SMTP Error: Could not authenticate" in PHPMailer

I had the same issue which was fixed following the instructions below

Test enabling “Access for less secure apps” (which just means the client/app doesn’t use OAuth 2.0 - https://oauth.net/2/) for the account you are trying to access. It's found in the account settings on the Security tab, Account permissions (not available to accounts with 2-step verification enabled): https://support.google.com/accounts/answer/6010255?hl=en

original link for the answer: https://support.google.com/mail/thread/5621336?msgid=6292199

What are 'get' and 'set' in Swift?

A simple question should be followed by a short, simple and clear answer.

  • When we are getting a value of the property it fires its get{} part.

  • When we are setting a value to the property it fires its set{} part.

PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{} part.

Example:

var A:Int = 0
var B:Int = 0

var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
     B = newValue
     }
}

//When we are getting a value of C it fires get{} part of C property
A = C 
A            //Now A = 1

//When we are setting a value to C it fires set{} part of C property
C = 2
B            //Now B = 2

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Finish all activities at a time

i am starter in java/android, may be this simple solution help for you

FIRST, create static class

public class ActivityManager {

    static Activity  _step1;
    static Activity _step2;
    static Activity _step3;

    public static void setActivity1(Activity activity)
    {
        _step1 = activity;
    }

    public static void setActivity2(Activity activity)
    {
        _step2 = activity;
    }

    public static void setActivity3(Activity activity)
    {
        _step3 = activity;
    }

    public static void finishAll()
    {
        _step1.finish();
        _step2.finish();
        _step3.finish();
    }

}

THEN when you run new activity save link to your manager(in step 1):

ActivityManager.setActivity1(this);
AddValuesToSharedPreferences();
Intent intent = new Intent(Step1.this, Step2.class);
startActivity(intent);

AND THEN in your last step finish all:

 public void OkExit(View v) throws IOException {
        ActivityManager.finishAll();
    }

CSS text-align: center; is not centering things

To make a inline-block element align center horizontally in its parent, add text-align:center to its parent.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...

HTML img scaling

Only set the width or height, and it will scale the other automatically. And yes you can use a percentage.

The first part can be done, but requires JavaScript, so might not work for all users.

How to re import an updated package while in Python Interpreter?

dragonfly's answer worked for me (python 3.4.3).

import sys
del sys.modules['module_name']

Here is a lower level solution :

exec(open("MyClass.py").read(), globals())

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.

How do I change the ID of a HTML element with JavaScript?

You can modify the id without having to use getElementById

Example:

<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>

You can see it here: http://jsbin.com/elikaj/1/

Tested with Mozilla Firefox 22 and Google Chrome 60.0

The request was aborted: Could not create SSL/TLS secure channel

I ran into the same issue recently. My environment is running under .NET 4.6.1 with VB.NET. That is how I fixed it:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf util.ValidateServerCertificate)

and the util.ValidateServerCertificate function is:

Public Function ValidateServerCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
    Return True
End Function

Change image source with JavaScript

Hi i tried to integrate with your code.

Can you have a look at this?

Thanks M.S

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<!--TODO: need to integrate this code into the project to change images added 05/21/2016:-->_x000D_
_x000D_
<script type="text/javascript">_x000D_
    function changeImage(a) {_x000D_
        document.getElementById("img").src=a;_x000D_
    }_x000D_
</script>_x000D_
_x000D_
_x000D_
 _x000D_
<title> Fluid Selection </title>_x000D_
<!-- css -->_x000D_
 <link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">_x000D_
 <link rel="stylesheet" href="css/main.css">_x000D_
<!-- end css -->_x000D_
<!-- Java script files -->_x000D_
<!-- Date.js date os javascript helper -->_x000D_
    <script src="js/date.js"> </script>_x000D_
_x000D_
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
 <script src="js/jquery-2.1.1.min.js"></script>_x000D_
_x000D_
<!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
 <script src="bootstrap-3/js/bootstrap.min.js"> </script>_x000D_
 <script src="js/library.js"> </script>_x000D_
 <script src="js/sfds.js"> </script>_x000D_
 <script src="js/main.js"> </script>_x000D_
_x000D_
<!-- End Java script files -->_x000D_
_x000D_
<!--added on 05/28/2016-->_x000D_
_x000D_
<style>_x000D_
/* The Modal (background) */_x000D_
.modal {_x000D_
    display: none; /* Hidden by default */_x000D_
    position: fixed; /* Stay in place */_x000D_
    z-index:40001; /* High z-index to ensure it appears above all content */ _x000D_
    padding-top: 100px; /* Location of the box */_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    width: 100%; /* Full width */_x000D_
    height: 100%; /* Full height */_x000D_
    overflow: auto; /* Enable scroll if needed */_x000D_
   _x000D_
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */_x000D_
}_x000D_
_x000D_
/* Modal Content */_x000D_
.modal-content {_x000D_
    position: relative;_x000D_
    background-color: #fefefe;_x000D_
    margin: auto;_x000D_
    padding: 0;_x000D_
    border: 1px solid #888;_x000D_
    width: 40%;_x000D_
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);_x000D_
    -webkit-animation-name: animatetop;_x000D_
    -webkit-animation-duration: 0.4s;_x000D_
    animation-name: animatetop;_x000D_
    animation-duration: 0.4s_x000D_
 opacity:.5; /* Sets opacity so it's partly transparent */ -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; _x000D_
 /* IE     _x000D_
 transparency */ filter:alpha(opacity=50); /* More IE transparency */ z-index:40001; } _x000D_
}_x000D_
_x000D_
/* Add Animation */_x000D_
@-webkit-keyframes animatetop {_x000D_
    from {top:-300px; opacity:0} _x000D_
    to {top:0; opacity:1}_x000D_
}_x000D_
_x000D_
@keyframes animatetop {_x000D_
    from {top:-300px; opacity:0}_x000D_
    to {top:0; opacity:1}_x000D_
}_x000D_
_x000D_
/* The Close Button */_x000D_
.close {_x000D_
    _x000D_
}_x000D_
_x000D_
.close:hover,_x000D_
.close:focus {_x000D_
    color: #000;_x000D_
    text-decoration: none;_x000D_
    cursor:pointer;_x000D_
}_x000D_
_x000D_
/* The Close Button */_x000D_
.close2 {_x000D_
    _x000D_
}_x000D_
_x000D_
_x000D_
.close2:focus {_x000D_
    color: #000;_x000D_
    text-decoration: none;_x000D_
    cursor:pointer;_x000D_
}_x000D_
_x000D_
.modal-header {_x000D_
 color: #000;_x000D_
    padding: 2px 16px;_x000D_
 }_x000D_
_x000D_
.modal-body {padding: 2px 16px;}_x000D_
 _x000D_
 _x000D_
}_x000D_
_x000D_
.modal-footer {_x000D_
    padding: 2px 16px;_x000D_
    background-color: #000099;_x000D_
    color: white;_x000D_
}_x000D_
_x000D_
_x000D_
</style>_x000D_
_x000D_
<script>_x000D_
 $(document).ready(function() {_x000D_
 _x000D_
 _x000D_
  $("#water").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setFluidType(0);_x000D_
    $this.find('h3').text('Select the H20 Fluid Type');_x000D_
    }else{_x000D_
     SFDS.setFluidType(1);_x000D_
     $this.addClass('clicked');_x000D_
     $this.find('h3').text('H20 Selected');_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  $("#saline").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setFluidType(0);_x000D_
    $this.find('h3').text('Select the NaCL Fluid Type');_x000D_
    }else{_x000D_
     SFDS.setFluidType(1);_x000D_
     $this.addClass('clicked');_x000D_
     $this.find('h3').text('NaCL Selected');_x000D_
     _x000D_
  _x000D_
  _x000D_
   }_x000D_
  });_x000D_
  _x000D_
 });_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<div class="container-fluid">_x000D_
 <header>_x000D_
  <div class="row">_x000D_
   <div class="col-xs-6">_x000D_
    <div id="date"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
   <div class="col-xs-6">_x000D_
    <div id="time" class="text-right"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </header>_x000D_
_x000D_
 <div class="row">_x000D_
  <div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">_x000D_
   <div id="fluid" class="main_button center-block">_x000D_
    <div class="large_circle_button, main_img"> _x000D_
     <h2>Select<br>Fluid</h2>_x000D_
     <img class="center-block large_button_image" src="images/dropwater.png" alt=""/> _x000D_
    </div>_x000D_
    <h1></h1>_x000D_
   </div>_x000D_
  </div>_x000D_
  <div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">_x000D_
   <div class="row">_x000D_
    <div class="col-xs-12">_x000D_
     <div id="water" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h3>Sterile<br>Water</h3>_x000D_
      </div>_x000D_
      <div id="thumb_img" class="image_wrapper">_x000D_
       <img src="images/dropsterilewater.png" alt="Sterile Water" class="sterile_water_image" onclick='changeImage("images/dropsterilewater.png");'>_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
     </div>_x000D_
    </div>_x000D_
    <div class="col-xs-12">_x000D_
     <div id="saline" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h3>Sterile<br>0.9% NaCL</h3>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/cansterilesaline.png" alt= "Sterile Saline" class="sterile_salt_image" onclick='changeImage("images/imagecansterilesaline.png");'>_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
    <div class="col-xs-12">_x000D_
     <div class="small_rectangle_button">_x000D_
      _x000D_
      <!-- Trigger/Open The Modal -->_x000D_
      <div id="myBtn" class="label_wrapper">_x000D_
       <h3>Change<br>Cartridge</h3>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/changecartridge.png" alt="" class="change_cartrige_image" />_x000D_
      </div>_x000D_
     </div>_x000D_
    </div>_x000D_
    _x000D_
     <!-- The Modal -->_x000D_
     <div id="myModal" class="modal">_x000D_
_x000D_
       <!-- Modal content -->_x000D_
       <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <span class="close"><img src="images/x-icon.png"></span>_x000D_
        <h2>Change Cartridge Instructions</h2>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <h4>Lorem ipsum dolor sit amet, dicant nonumes volutpat cu eum, in nulla molestie vim, nec probo option iracundia ut. Tale inermis scripserit ne cum, his no errem minimum commune, usu accumsan omnesque in. Eu has nihil dolor debitis, ad nobis impedit per. Dicat mnesarchum quo at, debet abhorreant consectetuer sea te, postea adversarium et eos. At alii dicit his, liber tantas suscipit sea in, id pri erat probatus. Vel nostro periculis dissentiet te, ut ubique noster vix. Id honestatis disputationi vel, ne vix assum constituam.</h4>                                                   _x000D_
                           <a href="#"><img src="images/video-icon.png" alt="click here for video"> </a>_x000D_
                           <a href="#close2" title="Close" class="close2"><img src="images/cancel-icon.png" alt="Cancel"></a>_x000D_
_x000D_
                          _x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <h4></h4>_x000D_
      </div>_x000D_
       </div>_x000D_
_x000D_
     </div>_x000D_
     _x000D_
     <!--for comparison-->_x000D_
_x000D_
_x000D_
     _x000D_
_x000D_
     _x000D_
     <script>_x000D_
     // Get the modal_x000D_
     var modal = document.getElementById('myModal');_x000D_
_x000D_
     // Get the button that opens the modal_x000D_
     var btn = document.getElementById("myBtn");_x000D_
_x000D_
     // Get the <span> element that closes the modal_x000D_
     var span = document.getElementsByClassName("close")[0];_x000D_
     _x000D_
_x000D_
     // When the user clicks the button, open the modal _x000D_
     btn.onclick = function() {_x000D_
      modal.style.display = "block";_x000D_
     }_x000D_
_x000D_
     // When the user clicks on <span> (x), close the modal_x000D_
     span.onclick = function() {_x000D_
      modal.style.display = "none";_x000D_
     }_x000D_
_x000D_
     // When the user clicks anywhere outside of the modal, close it_x000D_
     window.onclick = function(event) {_x000D_
      if (event.target == modal) {_x000D_
       modal.style.display = "none";_x000D_
      }_x000D_
      _x000D_
      _x000D_
     }_x000D_
     </script>_x000D_
                    _x000D_
_x000D_
    _x000D_
    _x000D_
    _x000D_
    _x000D_
    _x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</div>_x000D_
<footer class="footer navbar-fixed-bottom">_x000D_
 <div class="container-fluid">_x000D_
  <div class="row cols-bottom">_x000D_
   <div class="col-sm-3">_x000D_
    <a href="main.html">_x000D_
    <div class="small_circle_button">     _x000D_
     <img src="images/buttonback.png" alt="back to home" class="settings"/> <!--  width="49" height="48" -->_x000D_
    </div>_x000D_
   </div></a><div class=" col-sm-6">_x000D_
    <div id="stop_button" >_x000D_
     <img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->_x000D_
    </div>_x000D_
     _x000D_
   </div><div class="col-sm-3">_x000D_
    <div id="parker" class="pull-right">_x000D_
     <img src="images/parkerlogo.png" alt="parkerlogo" /> <!-- width="131" height="65" -->_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</footer>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to get multiple selected values from select box in JSP?

It would seem overkill but Spring Forms handles this elegantly. That is of course if you are already using Spring MVC and you want to take advantage of the Spring Forms feature.

// jsp form
    <form:select path="friendlyNumber" items="${friendlyNumberItems}" />

    // the command class
    public class NumberCmd {
      private String[] friendlyNumber;
    }

    // in your Spring MVC controller submit method
    @RequestMapping(method=RequestMethod.POST)
    public String manageOrders(@ModelAttribute("nbrCmd") NumberCmd nbrCmd){

       String[] selectedNumbers = nbrCmd.getFriendlyNumber();

    }

How can I get the Google cache age of any URL or web page?

This one good also to view cachepage http://www.cachepage.net

  1. Cache page view via google: webcache.googleusercontent.com/search?q=cache: Your url

  2. Cache page view via archive.org: web.archive.org/web/*/Your url

What are the benefits of learning Vim?

If you're a programmer who edits a lot of text, then it's important to learn an A Serious Text Editor. Which Serious Text Editor you learn is not terribly important and is largely dependent on the types of environments you expect to be editing in.

The reason is that these editors are highly optimized to perform the kinds of tasks that you will be doing a lot. For example, consider adding the same bit of text to the end of every line. This is trivial in A Serious Text Editor, but ridiculously cumbersome otherwise.

Usually vim's killer features are considered: A) that it's available on pretty much every Unix you'll ever encounter and B) your fingers very rarely have to leave the home row, which means you'll be able to edit text very, very quickly. It's also usually very fast and lightweight even when editing huge files.

There are plenty of alternatives, however. Emacs is the most common example, of course, and it's much more than just an advanced text editor if you really dig into it. I'm personally a very happy TextMate user now after years of using vim/gvim.

The trick to switching to any of these is to force yourself to use them the way they were intended. For example, in vim, if you're manually performing every step in a multi-step process or if you're using the arrow keys or the mouse then there's probably a better way to do it. Stop what you're doing and look it up.

If you do nothing else, learn the basic navigation controls for both vim and Emacs since they pop up all over the place. For example, you can use Emacs-style controls in any text input field in Mac OS, in most Unix shells, in Eclipse, etc. You can use vim-style controls in the less(1) command, on Slashdot, on gmail, etc.

Have fun!

Why is a div with "display: table-cell;" not affected by margin?

Cause

From the MDN documentation:

[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table

In other words, the margin property is not applicable to display:table-cell elements.

Solution

Consider using the border-spacing property instead.

Note it should be applied to a parent element with a display:table layout and border-collapse:separate.

For example:

HTML

<div class="table">
    <div class="row">
        <div class="cell">123</div>
        <div class="cell">456</div>
        <div class="cell">879</div>
    </div>
</div>

CSS

.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}

See jsFiddle demo


Different margin horizontally and vertically

As mentioned by Diego Quirós, the border-spacing property also accepts two values to set a different margin for the horizontal and vertical axes.

For example

.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */

How to move div vertically down using CSS

A standard width space for a standard 16px font is 4px.

Source: http://jkorpela.fi/styles/spaces.html

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

SOAP PHP fault parsing WSDL: failed to load external entity?

If anyone has the same problem, one possible solution is to set the bindto stream context configuration parameter (assuming you're connecting from 11.22.33.44 to 55.66.77.88):

$context = [
    'socket' => [
        'bindto' => '55.66.77.88'
    ]
];

$options = [
    'soapVersion' => SOAP_1_1,
    'stream_context' => stream_context_create($context)
];

$client = new Client('11.22.33.44', $options);

Why is an OPTIONS request sent and can I disable it?

Please refer this answer on the actual need for pre-flighted OPTIONS request: CORS - What is the motivation behind introducing preflight requests?

To disable the OPTIONS request, below conditions must be satisfied for ajax request:

  1. Request does not set custom HTTP headers like 'application/xml' or 'application/json' etc
  2. The request method has to be one of GET, HEAD or POST. If POST, content type should be one of application/x-www-form-urlencoded, multipart/form-data, or text/plain

Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

Spring MVC @PathVariable with dot (.) is getting truncated

Update for Spring 4: since 4.0.1 you can use PathMatchConfigurer (via your WebMvcConfigurer), e.g.

@Configuration
protected static class AllResources extends WebMvcConfigurerAdapter {

    @Override
    public void configurePathMatch(PathMatchConfigurer matcher) {
        matcher.setUseRegisteredSuffixPatternMatch(true);
    }

}


@Configuration
public class WebConfig implements WebMvcConfigurer {

   @Override
   public void configurePathMatch(PathMatchConfigurer configurer) {
       configurer.setUseSuffixPatternMatch(false);
   }
}

In xml, it would be (https://jira.spring.io/browse/SPR-10163):

<mvc:annotation-driven>
    [...]
    <mvc:path-matching registered-suffixes-only="true"/>
</mvc:annotation-driven>

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

DevTools failed to load SourceMap: Could not load content for chrome-extension

include.prepload.js file will have a line something like below. probably as the last line.

//# sourceMappingURL=include.prepload.js.map

Delete it and the error will go away.

error, string or binary data would be truncated when trying to insert

on sql server you can use SET ANSI_WARNINGS OFF like this:

        using (SqlConnection conn = new SqlConnection("Data Source=XRAYGOAT\\SQLEXPRESS;Initial Catalog='Healthy Care';Integrated Security=True"))
        {
            conn.Open();

            using (var trans = conn.BeginTransaction())
            {
                try
                {
                    using cmd = new SqlCommand("", conn, trans))
                    { 

                    cmd.CommandText = "SET ANSI_WARNINGS OFF";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "YOUR INSERT HERE";
                    cmd.ExecuteNonQuery();

                    cmd.Parameters.Clear();

                    cmd.CommandText = "SET ANSI_WARNINGS ON";
                    cmd.ExecuteNonQuery();

                    trans.Commit();
                    }
                }
                catch (Exception)
                {

                    trans.Rollback();
                }

            }

            conn.Close();

        }

SQL Case Expression Syntax?

Here you can find a complete guide for MySQL case statements in SQL.

CASE
     WHEN some_condition THEN return_some_value
     ELSE return_some_other_value
END

How to Load Ajax in Wordpress

I'm not allowed to comment, so regarding Shane's answer, keep in mind that

wp_localize_scripts()

must be hooked to wp or admin enqueue scripts. So a good example would be as follows:

function local() {

    wp_localize_script( 'js-file-handle', 'ajax', array(
        'url' => admin_url( 'admin-ajax.php' )
    ) );

}

add_action('admin_enqueue_scripts', 'local');
add_action('wp_enqueue_scripts', 'local');`

Convert Java Date to UTC String

Why not just use java.text.SimpleDateFormat ?

Date someDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = df.format(someDate);

Or see: http://www.tutorialspoint.com/java/java_date_time.htm

Error: package or namespace load failed for ggplot2 and for data.table

These steps work for me:

  1. Download the Rcpp manually from WebSite (https://cran.r-project.org/web/packages/Rcpp/index.html)
  2. unzip the folder/files to "Rcpp" folder
  3. Locate the "library" folder under R install directory Ex: C:\R\R-3.3.1\library
  4. Copy the "Rcpp" folder to Library folder.

Good to go!!!

library(Rcpp)
library(ggplot2) 

correct PHP headers for pdf file download

Example 2 on w3schools shows what you are trying to achieve.

<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>

Also remember that,

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)

How should I multiple insert multiple records?

You should execute the command on every loop instead of building a huge command Text(btw,StringBuilder is made for this) The underlying Connection will not close and re-open for each loop, let the connection pool manager handle this. Have a look at this link for further informations: Tuning Up ADO.NET Connection Pooling in ASP.NET Applications

If you want to ensure that every command is executed successfully you can use a Transaction and Rollback if needed,

What are the differences between a clustered and a non-clustered index?

Clustered Index

  • Only one per table
  • Faster to read than non clustered as data is physically stored in index order

Non Clustered Index

  • Can be used many times per table
  • Quicker for insert and update operations than a clustered index

Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.

Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp.

SQL Server will normally only use an index if its selectivity is above 95%.

How to convert between bytes and strings in Python 3?

TRY THIS:

StringVariable=ByteVariable.decode('UTF-8','ignore')

TO TEST TYPE:

print(type(StringVariable))

Here 'StringVariable' represented as a string. 'ByteVariable' represent as Byte. Its not relevent to question Variables..

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

How to reverse apply a stash?

This is in addition to the above answers but adds search for the git stash based on the message as the stash number can change when new stashes are saved. I have written a couple of bash functions:

apply(){
  if [ "$1" ]; then
    git stash apply `git stash list | grep -oPm1 "(.*)(?=:.*:.*$1.*)"`
  fi
}
remove(){
  if [ "$1" ]; then
    git stash show -p `git stash list | grep -oPm1 "(.*)(?=:.*:.*$1.*)"` | git apply -R
    git status
  fi
}
  1. Create stash with name (message) $ git stash save "my stash"
  2. To appply named $ apply "my stash"
  3. To remove named stash $ remove "my stash"

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

Your query ($myQuery) is failing and therefore not producing a query resource, but instead producing FALSE.

To reveal what your dynamically generated query looks like and reveal the errors, try this:

$result2 = mysql_query($myQuery) or die($myQuery."<br/><br/>".mysql_error());

The error message will guide you to the solution, which from your comment below is related to using ORDER BY on a field that doesn't exist in the table you're SELECTing from.

setting y-axis limit in matplotlib

This should work. Your code works for me, like for Tamás and Manoj Govindan. It looks like you could try to update Matplotlib. If you can't update Matplotlib (for instance if you have insufficient administrative rights), maybe using a different backend with matplotlib.use() could help.

Add to Array jQuery

push is a native javascript method. You could use it like this:

var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]

Java SSLException: hostname in certificate didn't match

Thanks Vineet Reynolds. The link you provided held a lot of user comments - one of which I tried in desperation and it helped. I added this method :

// Do not do this in production!!!
HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
    public boolean verify(String string,SSLSession ssls) {
        return true;
    }
});

This seems fine for me now, though I know this solution is temporary. I am working with the network people to identify why my hosts file is being ignored.

Android: how to handle button click

Most used way is, anonymous declaration

    Button send = (Button) findViewById(R.id.buttonSend);
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // handle click
        }
    });

Also you can create View.OnClickListener object and set it to button later, but you still need to override onClick method for example

View.OnClickListener listener = new View.OnClickListener(){
     @Override
        public void onClick(View v) {
            // handle click
        }
}   
Button send = (Button) findViewById(R.id.buttonSend);
send.setOnClickListener(listener);

When your activity implements OnClickListener interface you must override onClick(View v) method on activity level. Then you can assing this activity as listener to button, because it already implements interface and overrides the onClick() method

public class MyActivity extends Activity implements View.OnClickListener{


    @Override
    public void onClick(View v) {
        // handle click
    }


    @Override
    public void onCreate(Bundle b) {
        Button send = (Button) findViewById(R.id.buttonSend);
        send.setOnClickListener(this);
    }

}

(imho) 4-th approach used when multiple buttons have same handler, and you can declare one method in activity class and assign this method to multiple buttons in xml layout, also you can create one method for one button, but in this case I prefer to declare handlers inside activity class.

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

To add server using sp_addlinkedserver

I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.

An extended answer for remote IP db connections:

Step 1: Link servers

EXEC sp_addlinkedserver @server='SRV_NAME',
   @srvproduct=N'',
   @provider=N'SQLNCLI',   
   @datasrc=N'aaa.bbb.ccc.ddd';

EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'

...where SRV_NAME is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd is the ip address of the remote server hosting your SQLserver DB.

Step 2: Run your queries For instance:

SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table

...and that's it!

Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin

Select rows with same id but different value in another column

This ought to do it:

SELECT *
FROM YourTable
WHERE ARIDNR IN (
    SELECT ARIDNR
    FROM YourTable
    GROUP BY ARIDNR
    HAVING COUNT(*) > 1
)

The idea is to use the inner query to identify the records which have a ARIDNR value that occurs 1+ times in the data, then get all columns from the same table based on that set of values.

Adding ID's to google map markers

Why not use an cache that stores each marker object and references an ID?

var markerCache= {};
var idGen= 0;

function codeAddress(addr, contentStr){
    // create marker
    // store
    markerCache[idGen++]= marker;
}

Edit: of course this relies on a numeric index system that doesn't offer a length property like an array. You could of course prototype the Object object and create a length, etc for just such a thing. OTOH, generating a unique ID value (MD5, etc) of each address might be the way to go.

How to link an image and target a new window

<a href="http://www.google.com" target="_blank"> //gives blank window
<img width="220" height="250" border="0" align="center"  src=""/> // show image into new window
</a>

See the code

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

You can compare files from the explorer either from the working files section or the folder section. You can also trigger the global compare action from the command palette.

How to install pkg config in windows?

I did this by installing Cygwin64 from this link https://www.cygwin.com/ Then - View Full, Search gcc and scroll down to find pkg-config. Click on icon to select latest version. This worked for me well.

Export a list into a CSV or TXT file in R

You can write your For loop to individually store dataframes from a list:

allocation = list()

for(i in 1:length(allocation)){
    write.csv(data.frame(allocation[[i]]), file = paste0(path, names(allocation)[i], '.csv'))
}

Pass Javascript Array -> PHP

Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:

function obj2url(prefix, obj) {
        var args=new Array();
        if(typeof(obj) == 'object'){
            for(var i in obj)
                args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
        }
        else
            args[args.length]=prefix+'='+encodeURIComponent(obj);
        return args.join('&');
    }

prefix is a parameter name.

EDIT:

var a = {
    one: two,
    three: four
};

alert('/script.php?'+obj2url('a', a)); 

Will produce

/script.php?a[one]=two&a[three]=four

which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.

Passing parameters in Javascript onClick event

Try this:

<div id="div"></div>

<script language="javascript" type="text/javascript">
   var div = document.getElementById('div');

   for (var i = 0; i < 10; i++) {
       var f = function() {
           var link = document.createElement('a');
           var j = i; // this j is scoped to our anonymous function
                      // while i is scoped outside the anonymous function,
                      //  getting incremented by the for loop
           link.setAttribute('href', '#');
           link.innerHTML = j + '';
           link.onclick=  function() { onClickLink(j+'');};
           div.appendChild(link);
           div.appendChild(document.createElement('br')); // lower case BR, please!
       }(); // call the function immediately
   }

   function onClickLink(text) {
       alert('Link ' + text + ' clicked');
       return false;
   }
</script>

How can I access getSupportFragmentManager() in a fragment?

((AppCompatActivity) getActivity()).getSupportFragmentManager()

Jackson - Deserialize using generic class

You need to create a TypeReference object for each generic type you use and use that for deserialization. For example -

mapper.readValue(jsonString, new TypeReference<Data<String>>() {});

How to loop through files matching wildcard in batch file

Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.

According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:

for %%f in (*.in) do call process.cmd %%~nf

Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:

echo The file is %0
copy %0.in %0.out
ren %0.out monkeys_are_cool.txt

There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.

EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...

Clear and refresh jQuery Chosen dropdown list

In my case, I need to update selected value at each change because when I submit form, it always gets wrong values and I used multiple chosen drop downs. Rather than updating single entries, change selector to update all drop downs. This might help someone

 $(".chosen-select").chosen().change(function () {
    var item = $(this).val();
    $('.chosen-select').trigger('chosen:updated');
});

How do I add all new files to SVN

This will add all unknown (except ignored) files under the specified directory tree:

svn add --force path/to/dir

This will add all unknown (except ignored) files in the current directory and below:

svn add --force .

How does #include <bits/stdc++.h> work in C++?

That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.

Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.

Loop through an array php

You can use also this without creating additional variables nor copying the data in the memory like foreach() does.

while (false !== (list($item, $values) = each($array)))
{
    ...
}

How can I get my Twitter Bootstrap buttons to right align?

From Bootstrap V3.3.1 the following CSS style will solve this issue

.modal-open{
    padding-right: 0 !important;
}

Note: I tried all the suggestions in posts above and all addresses older versions and do not provide a fix to newset bootstrap versions.

A variable modified inside a while loop is not remembered

Hmmm... I would almost swear that this worked for the original Bourne shell, but don't have access to a running copy just now to check.

There is, however, a very trivial workaround to the problem.

Change the first line of the script from:

#!/bin/bash

to

#!/bin/ksh

Et voila! A read at the end of a pipeline works just fine, assuming you have the Korn shell installed.

pip installing in global site-packages instead of virtualenv

Funny you brought this up, I just had the exact same problem. I solved it eventually, but I'm still unsure as to what caused it.

Try checking your bin/pip and bin/activate scripts. In bin/pip, look at the shebang. Is it correct? If not, correct it. Then on line ~42 in your bin/activate, check to see if your virtualenv path is right. It'll look something like this

VIRTUAL_ENV="/Users/me/path/to/virtual/environment"

If it's wrong, correct it, deactivate, then . bin/activate, and if our mutual problem had the same cause, it should work. If it still doesn't, you're on the right track, anyway. I went through the same problem solving routine as you did, which piping over and over, following the stack trace, etc.

Make absolutely sure that

/Users/kristof/VirtualEnvs/testpy3/bin/pip3

is what you want, and not referring to another similarly-named test project (I had that problem, and have no idea how it started. My suspicion is running multiple virtualenvs at the same time).

If none of this works, a temporary solution may be to, as Joe Holloway said,

Just run the virtualenv's pip with its full path (i.e. don't rely on searching the executable path) and you don't even need to activate the environment. It will do the right thing.

Perhaps not ideal, but it ought to work in a pinch.

Link to my original question:

VirtualEnv/Pip trying to install packages globally

Visual Studio Code open tab in new window

On Windows and Linux, press Ctrl+K, then release the keys and press O (the letter O, not Zero).

On macOS, press command+K, then O (without holding command).

This will open the active file tab in a new window/instance.

Passing arguments to "make run"

You can explicitly extract each n-th argument in the command line. To do this, you can use variable MAKECMDGOALS, it holds the list of command line arguments given to 'make', which it interprets as a list of targets. If you want to extract n-th argument, you can use that variable combined with the "word" function, for instance, if you want the second argument, you can store it in a variable as follows:

second_argument := $(word 2, $(MAKECMDGOALS) )

Freely convert between List<T> and IEnumerable<T>

Aside: Note that the standard LINQ operators (as per the earlier example) don't change the existing list - list.OrderBy(...).ToList() will create a new list based on the re-ordered sequence. It is pretty easy, however, to create an extension method that allows you to use lambdas with List<T>.Sort:

static void Sort<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
}

static void SortDescending<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(y), selector(x)));
}

Then you can use:

list.Sort(x=>x.SomeProp); // etc

This updates the existing list in the same way that List<T>.Sort usually does.

Check if a string is html or not

There is an NPM package is-html that can attempt to solve this https://github.com/sindresorhus/is-html

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

How to cin Space in c++?

I thought I'd share the answer that worked for me. The previous line ended in a newline, so most of these answers by themselves didn't work. This did:

string title;
do {
  getline(cin, title);
} while (title.length() < 2);

That was assuming the input is always at least 2 characters long, which worked for my situation. You could also try simply comparing it to the string "\n".

How to get the CUDA version?

Open a terminal and run these commands:

cd /usr/local/cuda/samples/1_Utilities/deviceQuery
sudo make
./deviceQuery

You can get the information of CUDA Driver version, CUDA Runtime Version, and also detailed information for GPU(s). An image example of the output from my end is as below.

You can find the image here.

How to create a backup of a single table in a postgres database?

pg_dump -h localhost -p 5432 -U postgres -d mydb -t my_table > backup.sql

You can take the backup of a single table but I would suggest to take the backup of whole database and then restore whichever table you need. It is always good to have backup of whole database.

9 ways to use pg_dump

Is there an easy way to convert Android Application to IPad, IPhone

In the box is working on being able to convert android projects to iOS

https://code.google.com/p/in-the-box/

How to determine previous page URL in Angular?

Create a injectable service:

import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';

 /** A router wrapper, adding extra functions. */
@Injectable()
export class RouterExtService {

  private previousUrl: string = undefined;
  private currentUrl: string = undefined;

  constructor(private router : Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {        
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl(){
    return this.previousUrl;
  }    
}

Then use it everywhere you need. To store the current variable as soon as possible, it's necessary to use the service in the AppModule.

// AppModule
export class AppModule {
  constructor(private routerExtService: RouterExtService){}

  //...

}

// Using in SomeComponent
export class SomeComponent implements OnInit {

  constructor(private routerExtService: RouterExtService, private location: Location) { } 

  public back(): void {
    this.location.back();
  }

  //Strange name, but it makes sense. Behind the scenes, we are pushing to history the previous url
  public goToPrevious(): void {
    let previous = this.routerExtService.getPreviousUrl();

    if(previous)
      this.routerExtService.router.navigateByUrl(previous);
  }

  //...

}

Outputting data from unit test in Python

Another option - start a debugger where the test fails.

Try running your tests with Testoob (it will run your unittest suite without changes), and you can use the '--debug' command line switch to open a debugger when a test fails.

Here's a terminal session on windows:

C:\work> testoob tests.py --debug
F
Debugging for failure in test: test_foo (tests.MyTests.test_foo)
> c:\python25\lib\unittest.py(334)failUnlessEqual()
-> (msg or '%r != %r' % (first, second))
(Pdb) up
> c:\work\tests.py(6)test_foo()
-> self.assertEqual(x, y)
(Pdb) l
  1     from unittest import TestCase
  2     class MyTests(TestCase):
  3       def test_foo(self):
  4         x = 1
  5         y = 2
  6  ->     self.assertEqual(x, y)
[EOF]
(Pdb)

What is .Net Framework 4 extended?

It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:

The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

How to remove focus from single editText

Just find another view and give it focus instead.

var refresher = FindViewById<MvxSwipeRefreshLayout>(Resource.Id.refresher);

refresher.RequestFocus();

Using Java to pull data from a webpage?

Since Java 11 the most convenient way it to use java.net.http.HttpClient from the standard library.

Example:

HttpRequest request = HttpRequest.newBuilder(new URI(
    "https://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage"))
  .timeout(Duration.of(10, SECONDS))
  .GET()
  .build();

HttpResponse<String> response = HttpClient.newHttpClient()
  .send(request, BodyHandlers.ofString());

if (response.statusCode() != 200) {
  throw new RuntimeException(
    "Invalid response: " + response.statusCode() + ", request: " + response);
}

System.out.println(response.body());

Show div when radio button selected

var switchData = $('#show-me');
switchData.hide();
$('input[type="radio"]').change(function(){ var inputData = $(this).attr("value");if(inputData == 'b') { switchData.show();}else{switchData.hide();}});

JSFIDDLE

How to get Chrome to allow mixed content?

Another solution which is permanent in nature between sessions without requiring you to run a specific command when opening chrome is as follows:

  1. Open a Chrome window
  2. In the URL bar enter Chrome://net-internals
  3. Click on "Domain Security Policy" in the side-bar
  4. Add the domain name which you want to always be able to access in http form into the "Add HSTS/PKP domain" section

How to get height of Keyboard?

Shorter version here:

func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height
        }
}

How to get the first item from an associative PHP array?

Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.

For Example:

if(is_array($array))
{
  reset($array);
  $first = key($array);
}

How to place the "table" at the middle of the webpage?

The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.

That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!

<style>
  html, body {
    height: 100%;
  }
  #tableContainer-1 {
    height: 100%;
    width: 100%;
    display: table;
  }
  #tableContainer-2 {
    vertical-align: middle;
    display: table-cell;
    height: 100%;
  }
  #myTable {
    margin: 0 auto;
  }
</style>
<div id="tableContainer-1">
  <div id="tableContainer-2">
    <table id="myTable" border>
      <tr><td>Name</td><td>J W BUSH</td></tr>
      <tr><td>Proficiency</td><td>PHP</td></tr>
      <tr><td>Company</td><td>BLAH BLAH</td></tr>
    </table>
  </div>
</div>

How to fix "unable to open stdio.h in Turbo C" error?

On most systems, you'd have to be trying fairly hard not to find '<stdio.h>', to the point where the first reaction is "is <stdio.h> installed". So, I'd be looking to see if the file exists in a plausible location. If not, then your installation of Turbo C is broken; reinstall. If you can find it, then you will have to establish why the compiler is not searching for it in the right place - what are the compiler options you've specified and where is the compiler searching for its headers (and why isn't it searching where the header is).

DataSet panel (Report Data) in SSRS designer is gone

If you are using BIDS with SQL 2008 R2 you can only get the "Report Data" menu by clicking inside the actual report layout itself.

  1. Click inside the actual report layout.

  2. Now select "View" from the main menu bar.

  3. Now select "Report Data" which is the last item.

Having both a Created and Last Updated timestamp columns in MySQL 4.0

There is a trick to have both timestamps, but with a little limitation.

You can use only one of the definitions in one table. Create both timestamp columns like so:

create table test_table( 
  id integer not null auto_increment primary key, 
  stamp_created timestamp default '0000-00-00 00:00:00', 
  stamp_updated timestamp default now() on update now() 
); 

Note that it is necessary to enter null into both columns during insert:

mysql> insert into test_table(stamp_created, stamp_updated) values(null, null); 
Query OK, 1 row affected (0.06 sec)

mysql> select * from test_table; 
+----+---------------------+---------------------+ 
| id | stamp_created       | stamp_updated       |
+----+---------------------+---------------------+
|  2 | 2009-04-30 09:44:35 | 2009-04-30 09:44:35 |
+----+---------------------+---------------------+
2 rows in set (0.00 sec)  

mysql> update test_table set id = 3 where id = 2; 
Query OK, 1 row affected (0.05 sec) Rows matched: 1  Changed: 1  Warnings: 0  

mysql> select * from test_table;
+----+---------------------+---------------------+
| id | stamp_created       | stamp_updated       | 
+----+---------------------+---------------------+ 
|  3 | 2009-04-30 09:44:35 | 2009-04-30 09:46:59 | 
+----+---------------------+---------------------+ 
2 rows in set (0.00 sec)  

How do I create a new column from the output of pandas groupby().sum()?

How do I create a new column with Groupby().Sum()?

There are two ways - one straightforward and the other slightly more interesting.


Everybody's Favorite: GroupBy.transform() with 'sum'

@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby rather than Series.groupby. This results in simpler syntax.

# The setup.
df[['Date', 'Data3']]

         Date  Data3
0  2015-05-08      5
1  2015-05-07      8
2  2015-05-06      6
3  2015-05-05      1
4  2015-05-08     50
5  2015-05-07    100
6  2015-05-06     60
7  2015-05-05    120

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64 

It's a tad faster,

df2 = pd.concat([df] * 12345)

%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')

10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Unconventional, but Worth your Consideration: GroupBy.sum() + Series.map()

I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform if you instead use a direct function of GroupBy and broadcast it using map:

df.Date.map(df.groupby('Date')['Data3'].sum())

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Date, dtype: int64

Compare with

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64

My tests show that map is a bit faster if you can afford to use the direct GroupBy function (such as mean, min, max, first, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.

(Left: v0.23, Right: v0.24)

Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform as a first choice. Thought this was worth sharing anyway.

Benchmarking code, for reference:

import perfplot

perfplot.show(
    setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
    kernels=[
        lambda df: df.groupby('A')['B'].transform('sum'),
        lambda df:  df.A.map(df.groupby('A')['B'].sum()),
    ],
    labels=['GroupBy.transform', 'GroupBy.sum + map'],
    n_range=[2**k for k in range(5, 20)],
    xlabel='N',
    logy=True,
    logx=True
)

How to generate a random int in C?

For Linux C applications:

This is my reworked code from an answer above that follows my C code practices and returns a random buffer of any size (with proper return codes, etc.). Make sure to call urandom_open() once at the beginning of your program.

int gUrandomFd = -1;

int urandom_open(void)
{
    if (gUrandomFd == -1) {
        gUrandomFd = open("/dev/urandom", O_RDONLY);
    }

    if (gUrandomFd == -1) {
        fprintf(stderr, "Error opening /dev/urandom: errno [%d], strerrer [%s]\n",
                  errno, strerror(errno));
        return -1;
    } else {
        return 0;
    }
}


void urandom_close(void)
{
    close(gUrandomFd);
    gUrandomFd = -1;
}


//
// This link essentially validates the merits of /dev/urandom:
// http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
//
int getRandomBuffer(uint8_t *buf, int size)
{
    int ret = 0; // Return value

    if (gUrandomFd == -1) {
        fprintf(stderr, "Urandom (/dev/urandom) file not open\n");
        return -1;
    }

    ret = read(gUrandomFd, buf, size);

    if (ret != size) {
        fprintf(stderr, "Only read [%d] bytes, expected [%d]\n",
                 ret, size);
        return -1;
    } else {
        return 0;
    }
}

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

This plagued me for over an hour.

If you're using the dataSrc option and column defs option, make sure they are in the correct locations. I had nested column defs in the ajax settings and lost way too much time figuring that out.

This is good:

good

This is not good:

enter image description here

Subtle difference, but real enough to cause hair loss.

Convert datetime to Unix timestamp and convert it back in python

This class will cover your needs, you can pass the variable into ConvertUnixToDatetime & call which function you want it to operate based off.

from datetime import datetime
import time

class ConvertUnixToDatetime:
    def __init__(self, date):
        self.date = date

    # Convert unix to date object
    def convert_unix(self):
        unix = self.date

        # Check if unix is a string or int & proceeds with correct conversion
        if type(unix).__name__ == 'str':
            unix = int(unix[0:10])
        else:
            unix = int(str(unix)[0:10])

        date = datetime.utcfromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S')

        return date

    # Convert date to unix object
    def convert_date(self):
        date = self.date

        # Check if datetime object or raise ValueError
        if type(date).__name__ == 'datetime':
            unixtime = int(time.mktime(date.timetuple()))
        else:
            raise ValueError('You are trying to pass a None Datetime object')
        return type(unixtime).__name__, unixtime


if __name__ == '__main__':

    # Test Date
    date_test = ConvertUnixToDatetime(datetime.today())
    date_test = date_test.convert_date()
    print(date_test)

    # Test Unix
    unix_test = ConvertUnixToDatetime(date_test[1])
    print(unix_test.convert_unix())

Custom HTTP Authorization Header

The format defined in RFC2617 is credentials = auth-scheme #auth-param. So, in agreeing with fumanchu, I think the corrected authorization scheme would look like

Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg="

Where FIRE-TOKEN is the scheme and the two key-value pairs are the auth parameters. Though I believe the quotes are optional (from Apendix B of p7-auth-19)...

auth-param = token BWS "=" BWS ( token / quoted-string )

I believe this fits the latest standards, is already in use (see below), and provides a key-value format for simple extension (if you need additional parameters).

Some examples of this auth-param syntax can be seen here...

http://tools.ietf.org/html/draft-ietf-httpbis-p7-auth-19#section-4.4

https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin

https://developers.google.com/accounts/docs/AuthSub#WorkingAuthSub

Setting Windows PowerShell environment variables

Most answers aren't addressing UAC. This covers UAC issues.

First install PowerShell Community Extensions: choco install pscx via http://chocolatey.org/ (you may have to restart your shell environment).

Then enable pscx

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser #allows scripts to run from the interwebs, such as pcsx

Then use Invoke-Elevated

Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

Context is stored at the application level scope where as request is stored at page level i.e to say

Web Container brings up the applications one by one and run them inside its JVM. It stores a singleton object in its jvm where it registers anyobject that is put inside it.This singleton is shared across all applications running inside it as it is stored inside the JVM of the container itself.

However for requests, the container creates a request object that is filled with data from request and is passed along from one thread to the other (each thread is a new request that is coming to the server), also request is passed to the threads of same application.

AngularJS: ng-model not binding to ng-checked for checkboxes

You can use ng-value-true to tell angular that your ng-model is a string.

I could only get ng-true-value working if I added the extra quotes like so (as shown in the official Angular docs - https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D)

ng-true-value="'1'"

Check existence of directory and create if doesn't exist

In terms of general architecture I would recommend the following structure with regard to directory creation. This will cover most potential issues and any other issues with directory creation will be detected by the dir.create call.

mainDir <- "~"
subDir <- "outputDirectory"

if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
    cat("subDir exists in mainDir and is a directory")
} else if (file.exists(paste(mainDir, subDir, sep = "/", collapse = "/"))) {
    cat("subDir exists in mainDir but is a file")
    # you will probably want to handle this separately
} else {
    cat("subDir does not exist in mainDir - creating")
    dir.create(file.path(mainDir, subDir))
}

if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
    # By this point, the directory either existed or has been successfully created
    setwd(file.path(mainDir, subDir))
} else {
    cat("subDir does not exist")
    # Handle this error as appropriate
}

Also be aware that if ~/foo doesn't exist then a call to dir.create('~/foo/bar') will fail unless you specify recursive = TRUE.

How to compare two Dates without the time portion?

public static Date getZeroTimeDate(Date fecha) {
    Date res = fecha;
    Calendar calendar = Calendar.getInstance();

    calendar.setTime( fecha );
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    res = calendar.getTime();

    return res;
}

Date currentDate = getZeroTimeDate(new Date());// get current date   

this is the simplest way to solve this problem.

Command line .cmd/.bat script, how to get directory of running script

for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d

pushd %curdir%

Source

How to get current route in react-router 2.0.0-rc5

If you use the history,then Router put everything into the location from the history,such as:

this.props.location.pathname;
this.props.location.query;

get it?

Kill a postgresql session/connection

I had this issue and the problem was that Navicat was connected to my local Postgres db. Once I disconnected Navicat the problem disappeared.

EDIT:

Also, as an absolute last resort you can back up your data then run this command:

sudo kill -15 `ps -u postgres -o pid`

... which will kill everything that the postgres user is accessing. Avoid doing this on a production machine but you shouldn't have a problem with a development environment. It is vital that you ensure every postgres process has really terminated before attempting to restart PostgreSQL after this.

EDIT 2:

Due to this unix.SE post I've changed from kill -9 to kill -15.

How do I verify that a string only contains letters, numbers, underscores and dashes?

[Edit] There's another solution not mentioned yet, and it seems to outperform the others given so far in most cases.

Use string.translate to replace all valid characters in the string, and see if we have any invalid ones left over. This is pretty fast as it uses the underlying C function to do the work, with very little python bytecode involved.

Obviously performance isn't everything - going for the most readable solutions is probably the best approach when not in a performance critical codepath, but just to see how the solutions stack up, here's a performance comparison of all the methods proposed so far. check_trans is the one using the string.translate method.

Test code:

import string, re, timeit

pat = re.compile('[\w-]*$')
pat_inv = re.compile ('[^\w-]')
allowed_chars=string.ascii_letters + string.digits + '_-'
allowed_set = set(allowed_chars)
trans_table = string.maketrans('','')

def check_set_diff(s):
    return not set(s) - allowed_set

def check_set_all(s):
    return all(x in allowed_set for x in s)

def check_set_subset(s):
    return set(s).issubset(allowed_set)

def check_re_match(s):
    return pat.match(s)

def check_re_inverse(s): # Search for non-matching character.
    return not pat_inv.search(s)

def check_trans(s):
    return not s.translate(trans_table,allowed_chars)

test_long_almost_valid='a_very_long_string_that_is_mostly_valid_except_for_last_char'*99 + '!'
test_long_valid='a_very_long_string_that_is_completely_valid_' * 99
test_short_valid='short_valid_string'
test_short_invalid='/$%$%&'
test_long_invalid='/$%$%&' * 99
test_empty=''

def main():
    funcs = sorted(f for f in globals() if f.startswith('check_'))
    tests = sorted(f for f in globals() if f.startswith('test_'))
    for test in tests:
        print "Test %-15s (length = %d):" % (test, len(globals()[test]))
        for func in funcs:
            print "  %-20s : %.3f" % (func, 
                   timeit.Timer('%s(%s)' % (func, test), 'from __main__ import pat,allowed_set,%s' % ','.join(funcs+tests)).timeit(10000))
        print

if __name__=='__main__': main()

The results on my system are:

Test test_empty      (length = 0):
  check_re_inverse     : 0.042
  check_re_match       : 0.030
  check_set_all        : 0.027
  check_set_diff       : 0.029
  check_set_subset     : 0.029
  check_trans          : 0.014

Test test_long_almost_valid (length = 5941):
  check_re_inverse     : 2.690
  check_re_match       : 3.037
  check_set_all        : 18.860
  check_set_diff       : 2.905
  check_set_subset     : 2.903
  check_trans          : 0.182

Test test_long_invalid (length = 594):
  check_re_inverse     : 0.017
  check_re_match       : 0.015
  check_set_all        : 0.044
  check_set_diff       : 0.311
  check_set_subset     : 0.308
  check_trans          : 0.034

Test test_long_valid (length = 4356):
  check_re_inverse     : 1.890
  check_re_match       : 1.010
  check_set_all        : 14.411
  check_set_diff       : 2.101
  check_set_subset     : 2.333
  check_trans          : 0.140

Test test_short_invalid (length = 6):
  check_re_inverse     : 0.017
  check_re_match       : 0.019
  check_set_all        : 0.044
  check_set_diff       : 0.032
  check_set_subset     : 0.037
  check_trans          : 0.015

Test test_short_valid (length = 18):
  check_re_inverse     : 0.125
  check_re_match       : 0.066
  check_set_all        : 0.104
  check_set_diff       : 0.051
  check_set_subset     : 0.046
  check_trans          : 0.017

The translate approach seems best in most cases, dramatically so with long valid strings, but is beaten out by regexes in test_long_invalid (Presumably because the regex can bail out immediately, but translate always has to scan the whole string). The set approaches are usually worst, beating regexes only for the empty string case.

Using all(x in allowed_set for x in s) performs well if it bails out early, but can be bad if it has to iterate through every character. isSubSet and set difference are comparable, and are consistently proportional to the length of the string regardless of the data.

There's a similar difference between the regex methods matching all valid characters and searching for invalid characters. Matching performs a little better when checking for a long, but fully valid string, but worse for invalid characters near the end of the string.

How schedule build in Jenkins?

That appears to be a cron expression. Note that your example builds only on the first to seventh of every month, at 16:00. You likely have some sort of other error, or Jenkins uses non-standard CRON expressions.

INSERT SELECT statement in Oracle 11G

You don't need the 'values' clause when using a 'select' as your source.

insert into table1 (col1, col2) 
select t1.col1, t2.col2 from oldtable1 t1, oldtable2 t2;

How does one represent the empty char?

You can use c[i]= '\0' or simply c[i] = (char) 0.

The null/empty char is simply a value of zero, but can also be represented as a character with an escaped zero.

Conveniently map between enum and int / String

enum ? int

yourEnum.ordinal()

int ? enum

EnumType.values()[someInt]

String ? enum

EnumType.valueOf(yourString)

enum ? String

yourEnum.name()

A side-note:
As you correctly point out, the ordinal() may be "unstable" from version to version. This is the exact reason why I always store constants as strings in my databases. (Actually, when using MySql, I store them as MySql enums!)

How to get a responsive button in bootstrap 3

In Bootstrap, the .btn class has a white-space: nowrap; property, making it so that the button text won't wrap. So, after setting that to normal, and giving the button a width, the text should wrap to the next line if the text would exceed the set width.

#new-board-btn {
    white-space: normal;
}

http://jsfiddle.net/ADewB/

How to read fetch(PDO::FETCH_ASSOC);

PDO:FETCH_ASSOC puts the results in an array where values are mapped to their field names.

You can access the name field like this: $user['name'].

I recommend using PDO::FETCH_OBJ. It fetches fields in an object and you can access like this: $user->name

Access event to call preventdefault from custom function originating from onclick attribute of tag

Add a unique class to the links and a javascript that prevents default on links with this class:

<a href="#" class="prevent-default" 
   onclick="$('.comment .hidden').toggle();">Show comments</a>

<script>
  $(document).ready(function(){

    $("a.prevent-default").click(function(event) {
         event.preventDefault(); 
          });
  });
</script>

Getting Current date, time , day in laravel

It's very simple:

Carbon::now()->toDateString()

This will give you a perfectly formatted date string such as 2020-10-29.

In Laravel 5.5 and above you can use now() as a global helper instead of Carbon::now(), like this:

now()->toDateString()

How do I remove the horizontal scrollbar in a div?

If you don't have anything overflowing horizontally, you can also just use

overflow: auto;

and it will only show scrollbars when needed.

See The CSS Overflow Property

How do you specify a byte literal in Java?

You can use a byte literal in Java... sort of.

    byte f = 0;
    f = 0xa;

0xa (int literal) gets automatically cast to byte. It's not a real byte literal (see JLS & comments below), but if it quacks like a duck, I call it a duck.

What you can't do is this:

void foo(byte a) {
   ...
}

 foo( 0xa ); // will not compile

You have to cast as follows:

 foo( (byte) 0xa ); 

But keep in mind that these will all compile, and they are using "byte literals":

void foo(byte a) {
   ...
}

    byte f = 0;

    foo( f = 0xa ); //compiles

    foo( f = 'a' ); //compiles

    foo( f = 1 );  //compiles

Of course this compiles too

    foo( (byte) 1 );  //compiles

CSS: Set Div height to 100% - Pixels

Alternatively, you can just use position:absolute:

#content
{
    position:absolute;
    top: 111px;
    bottom: 0px;
}

However, IE6 doesn't like top and bottom declarations. But web developers don't like IE6.

Rename a file in C#

Take a look at System.IO.File.Move, "move" the file to a new name.

System.IO.File.Move("oldfilename", "newfilename");

The type WebMvcConfigurerAdapter is deprecated

Since Spring 5 you just need to implement the interface WebMvcConfigurer:

public class MvcConfig implements WebMvcConfigurer {

This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter class

See here:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.html

Why split the <script> tag when writing it with document.write()?

Here's another variation I've used when wanting to generate a script tag inline (so it executes immediately) without needing any form of escapes:

<script>
    var script = document.createElement('script');
    script.src = '/path/to/script.js';
    document.write(script.outerHTML);
</script>

(Note: contrary to most examples on the net, I'm not setting type="text/javascript" on neither the enclosing tag, nor the generated one: there is no browser not having that as the default, and so it is redundant, but will not hurt either, if you disagree).

A KeyValuePair in Java

Hashtable<String, Object>

It is better than java.util.Properties which is by fact an extension of Hashtable<Object, Object>.

Postgres "psql not recognized as an internal or external command"

I had your issue and got it working again (on windows 7).

My setup had actually worked at first. I installed postgres and then set up the system PATH variables with C:\Program Files\PostgreSQL\9.6\bin; C:\Program Files\PostgreSQL\9.6\lib. The psql keyword in the command line gave no errors.

I deleted the PATH variables above one at a time to test if they were both really needed. Psql continued to work after I deleted the lib path, but stopped working after I deleted the bin path. When I returned bin, it still didn't work, and the same with lib. I closed and reopened the command line between tries, and checked the path. The problem lingered even though the path was identical to how it had been when working. I re-pasted it.

I uninstalled and reinstalled postgres. The problem lingered. It finally worked after I deleted the spaces between the "; C:..." in the paths and re-saved.

Not sure if it was really the spaces that were the culprit. Maybe the environment variables just needed to be altered and refreshed after the install.

I'm also still not sure if both lib and bin paths are needed since there seems to be some kind of lingering memory for old path configurations. I don't want to test it again though.