Programs & Examples On #Monoids

A monoid is a set that is closed under an associative binary operation and has an identity element I ∈ Such that for all a ∈ S, Ia = aI = a. Note that unlike a group, its elements need not have inverses. It can also be thought of as a semigroup with an identity element.

A monad is just a monoid in the category of endofunctors, what's the problem?

I came to this post by way of better understanding the inference of the infamous quote from Mac Lane's Category Theory For the Working Mathematician.

In describing what something is, it's often equally useful to describe what it's not.

The fact that Mac Lane uses the description to describe a Monad, one might imply that it describes something unique to monads. Bear with me. To develop a broader understanding of the statement, I believe it needs to be made clear that he is not describing something that is unique to monads; the statement equally describes Applicative and Arrows among others. For the same reason we can have two monoids on Int (Sum and Product), we can have several monoids on X in the category of endofunctors. But there is even more to the similarities.

Both Monad and Applicative meet the criteria:

  • endo => any arrow, or morphism that starts and ends in the same place
  • functor => any arrow, or morphism between two Categories

    (e.g., in day to day Tree a -> List b, but in Category Tree -> List)

  • monoid => single object; i.e., a single type, but in this context, only in regards to the external layer; so, we can't have Tree -> List, only List -> List.

The statement uses "Category of..." This defines the scope of the statement. As an example, the Functor Category describes the scope of f * -> g *, i.e., Any functor -> Any functor, e.g., Tree * -> List * or Tree * -> Tree *.

What a Categorical statement does not specify describes where anything and everything is permitted.

In this case, inside the functors, * -> * aka a -> b is not specified which means Anything -> Anything including Anything else. As my imagination jumps to Int -> String, it also includes Integer -> Maybe Int, or even Maybe Double -> Either String Int where a :: Maybe Double; b :: Either String Int.

So the statement comes together as follows:

  • functor scope :: f a -> g b (i.e., any parameterized type to any parameterized type)
  • endo + functor :: f a -> f b (i.e., any one parameterized type to the same parameterized type) ... said differently,
  • a monoid in the category of endofunctor

So, where is the power of this construct? To appreciate the full dynamics, I needed to see that the typical drawings of a monoid (single object with what looks like an identity arrow, :: single object -> single object), fails to illustrate that I'm permitted to use an arrow parameterized with any number of monoid values, from the one type object permitted in Monoid. The endo, ~ identity arrow definition of equivalence ignores the functor's type value and both the type and value of the most inner, "payload" layer. Thus, equivalence returns true in any situation where the functorial types match (e.g., Nothing -> Just * -> Nothing is equivalent to Just * -> Just * -> Just * because they are both Maybe -> Maybe -> Maybe).

Sidebar: ~ outside is conceptual, but is the left most symbol in f a. It also describes what "Haskell" reads-in first (big picture); so Type is "outside" in relation to a Type Value. The relationship between layers (a chain of references) in programming is not easy to relate in Category. The Category of Set is used to describe Types (Int, Strings, Maybe Int etc.) which includes the Category of Functor (parameterized Types). The reference chain: Functor Type, Functor values (elements of that Functor's set, e.g., Nothing, Just), and in turn, everything else each functor value points to. In Category the relationship is described differently, e.g., return :: a -> m a is considered a natural transformation from one Functor to another Functor, different from anything mentioned thus far.

Back to the main thread, all in all, for any defined tensor product and a neutral value, the statement ends up describing an amazingly powerful computational construct born from its paradoxical structure:

  • on the outside it appears as a single object (e.g., :: List); static
  • but inside, permits a lot of dynamics
    • any number of values of the same type (e.g., Empty | ~NonEmpty) as fodder to functions of any arity. The tensor product will reduce any number of inputs to a single value... for the external layer (~fold that says nothing about the payload)
    • infinite range of both the type and values for the inner most layer

In Haskell, clarifying the applicability of the statement is important. The power and versatility of this construct, has absolutely nothing to do with a monad per se. In other words, the construct does not rely on what makes a monad unique.

When trying to figure out whether to build code with a shared context to support computations that depend on each other, versus computations that can be run in parallel, this infamous statement, with as much as it describes, is not a contrast between the choice of Applicative, Arrows and Monads, but rather is a description of how much they are the same. For the decision at hand, the statement is moot.

This is often misunderstood. The statement goes on to describe join :: m (m a) -> m a as the tensor product for the monoidal endofunctor. However, it does not articulate how, in the context of this statement, (<*>) could also have also been chosen. It truly is a an example of six/half dozen. The logic for combining values are exactly alike; same input generates the same output from each (unlike the Sum and Product monoids for Int because they generate different results when combining Ints).

So, to recap: A monoid in the category of endofunctors describes:

   ~t :: m * -> m * -> m *
   and a neutral value for m *

(<*>) and (>>=) both provide simultaneous access to the two m values in order to compute the the single return value. The logic used to compute the return value is exactly the same. If it were not for the different shapes of the functions they parameterize (f :: a -> b versus k :: a -> m b) and the position of the parameter with the same return type of the computation (i.e., a -> b -> b versus b -> a -> b for each respectively), I suspect we could have parameterized the monoidal logic, the tensor product, for reuse in both definitions. As an exercise to make the point, try and implement ~t, and you end up with (<*>) and (>>=) depending on how you decide to define it forall a b.

If my last point is at minimum conceptually true, it then explains the precise, and only computational difference between Applicative and Monad: the functions they parameterize. In other words, the difference is external to the implementation of these type classes.

In conclusion, in my own experience, Mac Lane's infamous quote provided a great "goto" meme, a guidepost for me to reference while navigating my way through Category to better understand the idioms used in Haskell. It succeeds at capturing the scope of a powerful computing capacity made wonderfully accessible in Haskell.

However, there is irony in how I first misunderstood the statement's applicability outside of the monad, and what I hope conveyed here. Everything that it describes turns out to be what is similar between Applicative and Monads (and Arrows among others). What it doesn't say is precisely the small but useful distinction between them.

- E

JSON character encoding

If you're using StringEntity try this, using your choice of character encoding. It handles foreign characters as well.

oracle sql: update if exists else insert

Please refer to this question if you want to use UPSERT/MERGE command in Oracle. Otherwise, just resolve your issue on the client side by doing a count(1) first and then deciding whether to insert or update.

Difference between nVidia Quadro and Geforce cards?

The difference is in view-port wire-frame rendering and double-sided polygon rendering, which is very common in professional CAD/3D software but not in games.

The difference is almost 10x-13x faster in single-fixed rendering pipeline (now very obsolete but some CAD software using it) rendering double sided polygons and wireframes:

enter image description here

Thats how entry level Quadro beats high-end GeForce. At least in the single-fixed pipeline using legacy calls like glLightModel(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE). The trick is done with driver optimization (does not matter if its single-fixed pipeline Direct3D or OpenGL). And its true that on some GeForce cards some firmware/hardware hacking can unlock the features.

If double sided is implemented using shader code, the GeForce has to render the polygon twice giving the Quadro only 2x the speed difference (it's less in real-world). The wireframe rendering remains much much slower on GeForce even if implemented in a modern way.

Todays GeForce cards can render millions of polygons per second, drawing lines with faded polygons can result in 100x speed difference eliminating the Quadro benefit.

Quadro equivalent GTX cards have usually better clock speeds giving 2%-10% better performance in games.


So to sum up:

The Quadro rules the single-fixed legacy now obsolete rendering pipeline (which CAD uses), but by implementing modern rendering methods this can be significantly reduced (virtually no speed gain in Maya's Viewport 2.0, it uses GLSL effects - very similar to game engine).

Other reasons to get Quadro are double precision float computations for science, better warranty and display's support for professionals.

That's about it, price-vise the Quadros or FirePros are artificially overpriced.

How do I display a decimal value to 2 decimal places?

You can use system.globalization to format a number in any required format.

For example:

system.globalization.cultureinfo ci = new system.globalization.cultureinfo("en-ca");

If you have a decimal d = 1.2300000 and you need to trim it to 2 decimal places then it can be printed like this d.Tostring("F2",ci); where F2 is string formating to 2 decimal places and ci is the locale or cultureinfo.

for more info check this link
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

CSS - How to Style a Selected Radio Buttons Label?

_x000D_
_x000D_
.radio-toolbar input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.radio-toolbar label {_x000D_
  display: inline-block;_x000D_
  background-color: #ddd;_x000D_
  padding: 4px 11px;_x000D_
  font-family: Arial;_x000D_
  font-size: 16px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.radio-toolbar input[type="radio"]:checked+label {_x000D_
  background-color: #bbb;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
  <input type="radio" id="radio1" name="radios" value="all" checked>_x000D_
  <label for="radio1">All</label>_x000D_
_x000D_
  <input type="radio" id="radio2" name="radios" value="false">_x000D_
  <label for="radio2">Open</label>_x000D_
_x000D_
  <input type="radio" id="radio3" name="radios" value="true">_x000D_
  <label for="radio3">Archived</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

First of all, you probably want to add the name attribute on the radio buttons. Otherwise, they are not part of the same group, and multiple radio buttons can be checked.

Also, since I placed the labels as siblings (of the radio buttons), I had to use the id and for attributes to associate them together.

What does Html.HiddenFor do?

And to consume the hidden ID input back on your Edit action method:

[HttpPost]
public ActionResult Edit(FormCollection collection)
{
    ViewModel.ID = Convert.ToInt32(collection["ID"]);
}

How to reset db in Django? I get a command 'reset' not found error

For me this solved the problem.

heroku pg:reset DATABASE_URL

heroku run bash
>> Inside heroku bash
cd app_name && rm -rf migrations && cd ..
./manage.py makemigrations app_name
./manage.py migrate

How can I store the result of a system command in a Perl variable?

Use backticks for system commands, which helps to store their results into Perl variables.

my $pid = 5892;
my $not = ``top -H -p $pid -n 1 | grep myprocess | wc -l`; 
print "not = $not\n";

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

Return array from function

Your BlockID function uses the undefined variable images, which will lead to an error. Also, you should not use an Array here - JavaScripts key-value-maps are plain objects:

function BlockID() {
    return {
        "s": "Images/Block_01.png",
        "g": "Images/Block_02.png",
        "C": "Images/Block_03.png",
        "d": "Images/Block_04.png"
    };
}

How can I convert a comma-separated string to an array?

Pass your comma-separated string into this function and it will return an array, and if a comma-separated string is not found then it will return null.

function splitTheString(CommaSepStr) {
    var ResultArray = null;

    // Check if the string is null or so.
    if (CommaSepStr!= null) {

        var SplitChars = ',';

        // Check if the string has comma of not will go to else
        if (CommaSepStr.indexOf(SplitChars) >= 0) {
            ResultArray = CommaSepStr.split(SplitChars);

        }
        else {

            // The string has only one value, and we can also check
            // the length of the string or time and cross-check too.
            ResultArray = [CommaSepStr];
        }
    }
    return ResultArray;
}

How to unlock android phone through ADB

This command helps you to unlock phone using ADB

adb shell input keyevent 82 # unlock

data.map is not a function

data is not an array, it is an object with an array of products so iterate over data.products

var allProducts = data.products.map(function (item) {
    return new getData(item);
});

nodemon not working: -bash: nodemon: command not found

If you want to run it locally instead of globally, you can run it from your node_modules:

npx nodemon

File size exceeds configured limit (2560000), code insight features not available

For those who don't know where to find the file they're talking about. On my machine (OSX) it is in:

  • PyCharm CE: /Applications/PyCharm CE.app/Contents/bin/idea.properties
  • WebStorm: /Applications/WebStorm.app/Contents/bin/idea.properties

Error "The connection to adb is down, and a severe error has occurred."

Simply go in Task Manager (windows users) and kill the abd.exe (it is remaining active somehow). After that start Eclipse.

The error

"The connection to adb is down, and a severe error has occured"

happened after installing plugin for Android of Netbeans. After closing Netbeans the process abd.exe remained active. When you want to start again Eclipse ... you will get the error.

You have to manually kill the adb.exe and then start Eclipse.

It worked for me.

How to determine the screen width in terms of dp or dip at runtime in Android?

DisplayMetrics displayMetrics = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;

int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;

int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;


int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;

In Java, remove empty elements from a list of Strings

Another way to do this now that we have Java 8 lambda expressions.

arrayList.removeIf(item -> item == null || "".equals(item));

Getting the URL of the current page using Selenium WebDriver

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

Handling 'Sequence has no elements' Exception

You are using linq's First() method, which as per the documentation throws an InvalidOperationException if you are calling it on an empty collection.

If you expect the result of your query to be empty sometimes, you likely want to use FirstOrDefault(), which will return null if the collection is empty, instead of throwing an exception.

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

How do I get a file's directory using the File object?

String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length()); 

This would be my solution

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

jQuery onclick toggle class name

jQuery has a toggleClass function:

<button class="switch">Click me</button>

<div class="text-block collapsed pressed">some text</div>

<script>    
    $('.switch').on('click', function(e) {
      $('.text-block').toggleClass("collapsed pressed"); //you can list several class names 
      e.preventDefault();
    });
</script>

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"

What is the use of the @ symbol in PHP?

Suppose we haven't used the "@" operator then our code would look like this:

$fileHandle = fopen($fileName, $writeAttributes);

And what if the file we are trying to open is not found? It will show an error message.

To suppress the error message we are using the "@" operator like:

$fileHandle = @fopen($fileName, $writeAttributes);

CakePHP 3.0 installation: intl extension missing from system

For those who get Package not found error try sudo apt-get install php7-intl then run composer install in your project directory.

postgresql: INSERT INTO ... (SELECT * ...)

You can use dblink to create a view that is resolved in another database. This database may be on another server.

Integrating Dropzone.js into existing HTML form with other fields

You can modify the formData by catching the 'sending' event from your dropzone.

dropZone.on('sending', function(data, xhr, formData){
        formData.append('fieldname', 'value');
});

Logarithmic returns in pandas dataframe

Log returns are simply the natural log of 1 plus the arithmetic return. So how about this?

df['pct_change'] = df.price.pct_change()
df['log_return'] = np.log(1 + df.pct_change)

Even more concise, utilizing Ximix's suggestion:

df['log_return'] = np.log1p(df.price.pct_change())

Slide a layout up from bottom of screen

Ok, there are two possible approaches. The simplest - is to use a sliding menu library. It allows creating a bottom sliding menu, it can animate the top container to make bottom visible, it suports both dragging it with your finger, or animating it programmatically via button (StaticDrawer).

Harder way - if you want to use Animations, as was already suggested. With animations you must FIRST change your layouts. So try first to make your layout change to the final state without any animations whatsoever. Because it is very likely that you are not laying out your views properly in RelativeLayout, so even though you show your bottom view, it remains obscured by the top one. Once you achieved proper layout change - all you need to do is to is to remember translations before layout and apply translate animation AFTER layout.

Difference of keywords 'typename' and 'class' in templates?

This piece of snippet is from c++ primer book. Although I am sure this is wrong.

Each type parameter must be preceded by the keyword class or typename:

// error: must precede U with either typename or class
template <typename T, U> T calc(const T&, const U&);

These keywords have the same meaning and can be used interchangeably inside a template parameter list. A template parameter list can use both keywords:

// ok: no distinction between typename and class in a template parameter list
template <typename T, class U> calc (const T&, const U&);

It may seem more intuitive to use the keyword typename rather than class to designate a template type parameter. After all, we can use built-in (nonclass) types as a template type argument. Moreover, typename more clearly indicates that the name that follows is a type name. However, typename was added to C++ after templates were already in widespread use; some programmers continue to use class exclusively

Loop in react-native

This should work

_x000D_
_x000D_
render(){_x000D_
_x000D_
 var payments = [];_x000D_
_x000D_
 for(let i = 0; i < noGuest; i++){_x000D_
_x000D_
  payments.push(_x000D_
   <View key = {i}>_x000D_
    <View>_x000D_
     <TextInput />_x000D_
    </View>_x000D_
    <View>_x000D_
     <TextInput />_x000D_
    </View>_x000D_
    <View>_x000D_
     <TextInput />_x000D_
    </View>_x000D_
   </View>_x000D_
  )_x000D_
 }_x000D_
 _x000D_
 return (_x000D_
  <View>_x000D_
   <View>_x000D_
    <View><Text>No</Text></View>_x000D_
    <View><Text>Name</Text></View>_x000D_
    <View><Text>Preference</Text></View>_x000D_
   </View>_x000D_
_x000D_
   { payments }_x000D_
  </View>_x000D_
 )_x000D_
}
_x000D_
_x000D_
_x000D_

Show an image preview before upload

For background images, make sure to use url()

node.backgroundImage = 'url(' + e.target.result + ')';

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Is there a way to create interfaces in ES6 / Node 4?

In comments debiasej wrote the mentioned below article explains more about design patterns (based on interfaces, classes):

http://loredanacirstea.github.io/es6-design-patterns/

Design patterns book in javascript may also be useful for you:

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Design pattern = classes + interface or multiple inheritance

An example of the factory pattern in ES6 JS (to run: node example.js):

"use strict";

// Types.js - Constructors used behind the scenes

// A constructor for defining new cars
class Car {
  constructor(options){
    console.log("Creating Car...\n");
    // some defaults
    this.doors = options.doors || 4;
    this.state = options.state || "brand new";
    this.color = options.color || "silver";
  }
}

// A constructor for defining new trucks
class Truck {
  constructor(options){
    console.log("Creating Truck...\n");
    this.state = options.state || "used";
    this.wheelSize = options.wheelSize || "large";
    this.color = options.color || "blue";
  }
}


// FactoryExample.js

// Define a skeleton vehicle factory
class VehicleFactory {}

// Define the prototypes and utilities for this factory

// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;

// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {

  switch(options.vehicleType){
    case "car":
      this.vehicleClass = Car;
      break;
    case "truck":
      this.vehicleClass = Truck;
      break;
    //defaults to VehicleFactory.prototype.vehicleClass (Car)
  }

  return new this.vehicleClass( options );

};

// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
            vehicleType: "car",
            color: "yellow",
            doors: 6 } );

// Test to confirm our car was created using the vehicleClass/prototype Car

// Outputs: true
console.log( car instanceof Car );

// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );

var movingTruck = carFactory.createVehicle( {
                      vehicleType: "truck",
                      state: "like new",
                      color: "red",
                      wheelSize: "small" } );

// Test to confirm our truck was created with the vehicleClass/prototype Truck

// Outputs: true
console.log( movingTruck instanceof Truck );

// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

Using btoa with unescape and encodeURIComponent didn't work for me. Replacing all the special characters with XML/HTML entities and then converting to the base64 representation was the only way to solve this issue for me. Some code:

base64 = btoa(str.replace(/[\u00A0-\u2666]/g, function(c) {
    return '&#' + c.charCodeAt(0) + ';';
}));

What is the difference between onBlur and onChange attribute in HTML?

onblur fires when a field loses focus, while onchange fires when that field's value changes. These events will not always occur in the same order, however.

In Firefox, tabbing out of a changed field will fire onchange then onblur, and it will normally do the same in IE. However, if you press the enter key instead of tab, in Firefox it will fire onblur then onchange, while IE will usually fire in the original order. However, I've seen cases where IE will also fire blur first, so be careful. You can't assume that either the onblur or the onchange will happen before the other one.

Responsive background image in div full width

When you use background-size: cover the background image will automatically be stretched to cover the entire container. Aspect ratio is maintained however, so you will always lose part of the image, unless the aspect ratio of the image and the element it is applied to are identical.

I see two ways you could solve this:

  • Do not maintain the aspect ratio of the image by setting background-size: 100% 100% This will also make the image cover the entire container, but the ratio will not be maintained. Disadvantage is that this distorts your image, and therefore may look very weird, depending on the image. With the image you are using in the fiddle, I think you could get away with it though.

  • You could also calculate and set the height of the element with javascript, based on its width, so it gets the same ratio as the image. This calculation would have to be done on load and on resize. It should be easy enough with a few lines of code (feel free to ask if you want an example). Disadvantage of this method is that your width may become very small (on mobile devices), and therfore the calculated height also, which may cause the content of the container to overflow. This could be solved by changing the size of the content as well or something, but it adds some complexity to the solution/

plot different color for different categorical levels using matplotlib

I usually do it using Seaborn which is built on top of matplotlib

import seaborn as sns
iris = sns.load_dataset('iris')
sns.scatterplot(x='sepal_length', y='sepal_width',
              hue='species', data=iris); 

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

For me neither the MouseClick or Click event worked, because the events, simply, are not called when you right click. The quick way to do it is:

 private void button1_MouseUp(object sender, MouseEventArgs e)
 {
        if (e.Button == MouseButtons.Right)
        {
            //do something here
        }
        else//left or middle click
        {
            //do something here
        }
 }

You can modify that to do exactly what you want depended on the arguments' values.

WARNING: There is one catch with only using the mouse up event. if you mousedown on the control and then you move the cursor out of the control to release it, you still get the event fired. In order to avoid that, you should also make sure that the mouse up occurs within the control in the event handler. Checking whether the mouse cursor coordinates are within the control's rectangle before you check the buttons will do it properly.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

Using VS2013 .net 4.5

I had this same issue.

The "Most likely causes" section on the error message page provided the most help. For me. It said "This application defines configuration in the system.web/httpModules section." Then in the "Things you can try" section it said "Migrate the configuration to the system.webServer/modules section."

<system.web>
      <httpHandlers>
        <add type="DevExpress.Web.ASPxUploadProgressHttpHandler, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET,POST" path="ASPxUploadProgressHandlerPage.ashx" validate="false" />
        <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET" path="DX.ashx" validate="false" />
      </httpHandlers>
      <httpModules>
        <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
      </httpModules>
    </system.web>

into the system.webServer section.

<system.webServer> 
    <handlers>
      <add type="DevExpress.Web.ASPxUploadProgressHttpHandler, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET,POST" path="ASPxUploadProgressHandlerPage.ashx" name="ASPxUploadProgressHandler" preCondition="integratedMode" />
      <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET" path="DX.ashx" name="ASPxHttpHandlerModule" preCondition="integratedMode" />
    </handlers>
    <modules>
      <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
    </modules>
</system.webServer>

How do I format a number in Java?

As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).

Use Spring's Numberformatter instead, which is thread safe.

Why does Node.js' fs.readFile() return a buffer instead of string?

The data variable contains a Buffer object. Convert it into ASCII encoding using the following syntax:

data.toString('ascii', 0, data.length)

Asynchronously:

fs.readFile('test.txt', 'utf8', function (error, data) {
    if (error) throw error;
    console.log(data.toString());
});

Efficiently updating database using SQLAlchemy ORM

Here's an example of how to solve the same problem without having to map the fields manually:

from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime, text, create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.attributes import InstrumentedAttribute

engine = create_engine('postgres://postgres@localhost:5432/database')
session = sessionmaker()
session.configure(bind=engine)

Base = declarative_base()


class Media(Base):
  __tablename__ = 'media'
  id = Column(Integer, primary_key=True)
  title = Column(String, nullable=False)
  slug = Column(String, nullable=False)
  type = Column(String, nullable=False)

  def update(self):
    s = session()
    mapped_values = {}
    for item in Media.__dict__.iteritems():
      field_name = item[0]
      field_type = item[1]
      is_column = isinstance(field_type, InstrumentedAttribute)
      if is_column:
        mapped_values[field_name] = getattr(self, field_name)

    s.query(Media).filter(Media.id == self.id).update(mapped_values)
    s.commit()

So to update a Media instance, you can do something like this:

media = Media(id=123, title="Titular Line", slug="titular-line", type="movie")
media.update()

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

ShowAllData method of Worksheet class failed

This will work. Define this, then call it from when you need it. (Good for button logic if you are making a clear button):

Sub ResetFilters()
    On Error Resume Next
    ActiveSheet.ShowAllData
End Sub

How do I center a window onscreen in C#?

Use this:

this.CenterToScreen();  // This will take care of the current form

Bundler: Command not found

You can also create a symlink:

ln -s /opt/ruby-enterprise-1.8.7-2010.02/lib/ruby/gems/1.8/gems/bin/bundle /usr/bin/bundle

Convert to/from DateTime and Time in Ruby

While making such conversions one should take into consideration the behavior of timezones while converting from one object to the other. I found some good notes and examples in this stackoverflow post.

Python popen command. Wait until the command is finished

Force popen to not continue until all output is read by doing:

os.popen(command).read()

Multiple select in Visual Studio?

Multi cursor edit is natively supported in Visual Studio starting from version 2017 Update 8. The following is an extract of the documentation:

  • Ctrl + Alt + click : Add a secondary caret
  • Ctrl + Alt + double-click : Add a secondary word selection
  • Ctrl + Alt + click + drag : Add a secondary selection
  • Shift + Alt + . : Add the next matching text as a selection
  • Shift + Alt + ; : Add all matching text as selections
  • Shift + Alt + , : Remove last selected occurrence
  • Shift + Alt + / : Skip next matching occurrence
  • Alt + click : Add a box selection
  • Esc or click : Clear all selections

Some of those commands are also available in the Edit menu:

Multiple Carets Menu

Java: Find .txt files in specified folder

import org.apache.commons.io.FileUtils;   

List<File> htmFileList = new ArrayList<File>();

for (File file : (List<File>) FileUtils.listFiles(new File(srcDir), new String[]{"txt", "TXT"}, true)) {
    htmFileList.add(file);
}

This is my latest code to add all text files from a directory

How do I list all the columns in a table?

SQL Server

SELECT 
    c.name 
FROM
    sys.objects o
INNER JOIN
    sys.columns c
ON
    c.object_id = o.object_id
AND o.name = 'Table_Name'

or

SELECT 
    COLUMN_NAME 
FROM 
    INFORMATION_SCHEMA.COLUMNS
WHERE 
    TABLE_NAME  = 'Table_Name'

The second way is an ANSI standard and therefore should work on all ANSI compliant databases.

How to find all the tables in MySQL with specific column names in them?

In version that do not have information_schema (older versions, or some ndb's) you can dump the table structure and search the column manually.

mysqldump -h$host -u$user -p$pass --compact --no-data --all-databases > some_file.sql

Now search the column name in some_file.sql using your preferred text editor, or use some nifty awk scripts.


And a simple sed script to find the column, just replace COLUMN_NAME with your's:

sed -n '/^USE/{h};/^CREATE/{H;x;s/\nCREATE.*\n/\n/;x};/COLUMN_NAME/{x;p};' <some_file.sql
USE `DATABASE_NAME`;
CREATE TABLE `TABLE_NAME` (
  `COLUMN_NAME` varchar(10) NOT NULL,

You can pipe the dump directly in sed but that's trivial.

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

How do I close a tkinter window?

from tkinter import *

def quit(root):
    root.close()

root = Tk()
root.title("Quit Window")

def quit(root):
    root.close()

button = Button(root, text="Quit", command=quit.pack()

root.mainloop()

iPhone Debugging: How to resolve 'failed to get the task for process'?

The ad-hoc profile doesn't support debugging. You need to debug with a Development profile, and use the Ad-Hoc profile only for distributing non-debuggable copies.

Compiling C++11 with g++

Your Ubuntu definitely has a sufficiently recent version of g++. The flag to use is -std=c++0x.

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

yourimg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}

and make sure there is no parent tags with position: relative in it

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

In your state, home is initialized as an array homes: []

In your return, there is an attempt to render home (which is an array). <p>Stuff: {homes}</p>

Cannot be done this way --- If you want to render it, you need to render an array into each single item. For example: using map()

Ex: {home.map(item=>item)}

How to calculate moving average without keeping the count and data-total?

From a blog on running sample variance calculations, where the mean is also calculated using Welford's method:

enter image description here

Too bad we can't upload SVG images.

Is there a PowerShell "string does not contain" cmdlet or syntax?

If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:

Get-Content $FileName | foreach-object { `
   if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }

or better (IMO)

Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}

How to get start and end of day in Javascript?

var start = new Date();
start.setHours(0,0,0,0);

var end = new Date();
end.setHours(23,59,59,999);

alert( start.toUTCString() + ':' + end.toUTCString() );

If you need to get the UTC time from those, you can use UTC().

Apply jQuery datepicker to multiple instances

html:

<input type="text" class="datepick" id="date_1" />
<input type="text" class="datepick" id="date_2" />
<input type="text" class="datepick" id="date_3" />

script:

$('.datepick').each(function(){
    $(this).datepicker();
});

(pseudo coded up a bit to keep it simpler)

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

ScrollIntoView() causing the whole page to move

Just to add an answer as per my latest experience and working on VueJs. I found below piece of code ad best, which does not impact your application in anyways.

const el = this.$el.getElementsByClassName('your_element_class')[0];
if (el) {
   scrollIntoView(el,
                  {
                       block: 'nearest',
                       inline: 'start',
                       behavior: 'smooth',
                       boundary: document.getElementsByClassName('main_app_class')[0]
                    });
     }

main_app_class is the root class

your_element_class is the element/view where you can to scroll into

And for browser which does not support ScrollIntoView() just use below library its awesome https://www.npmjs.com/package/scroll-into-view-if-needed

Confirm deletion using Bootstrap 3 modal box

You need the modal in your HTML. When the delete button is clicked it popup the modal. It's also important to prevent the click of that button from submitting the form. When the confirmation is clicked the form will submit.

_x000D_
_x000D_
   _x000D_
_x000D_
 $('button[name="remove_levels"]').on('click', function(e) {_x000D_
      var $form = $(this).closest('form');_x000D_
      e.preventDefault();_x000D_
      $('#confirm').modal({_x000D_
          backdrop: 'static',_x000D_
          keyboard: false_x000D_
      })_x000D_
      .on('click', '#delete', function(e) {_x000D_
          $form.trigger('submit');_x000D_
        });_x000D_
      $("#cancel").on('click',function(e){_x000D_
       e.preventDefault();_x000D_
       $('#confirm').modal.model('hide');_x000D_
      });_x000D_
    });
_x000D_
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>_x000D_
<form action="#" method="POST">_x000D_
  <button class='btn btn-danger btn-xs' type="submit" name="remove_levels" value="delete"><span class="fa fa-times"></span> delete</button>_x000D_
</form>_x000D_
_x000D_
<div id="confirm" class="modal">_x000D_
  <div class="modal-body">_x000D_
    Are you sure?_x000D_
  </div>_x000D_
  <div class="modal-footer">_x000D_
    <button type="button" data-dismiss="modal" class="btn btn-primary" id="delete">Delete</button>_x000D_
    <button type="button" data-dismiss="modal" class="btn">Cancel</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaScript: changing the value of onclick with or without jQuery

You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()

$(document).ready(function(){
    var js = "alert('B:' + this.id); return false;";
    // create a function from the "js" string
    var newclick = new Function(js);

    // clears onclick then sets click using jQuery
    $("#anchor").attr('onclick', '').click(newclick);
});

That should cancel the onClick function - and keep your "javascript from a string" as well.

The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.

You also said:

Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().

No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors

return error message with actionResult

Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.

[HttpPost]
public ActionResult PostViaAjax()
{
    var body = Request.BinaryRead(Request.TotalBytes);

    var result = Content(JsonError(new Dictionary<string, string>()
    {
        {"err", "Some error!"}
    }), "application/json; charset=utf-8");
    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return result;
}

Getting value from appsettings.json in .net core

Program and Startup class

.NET Core 2.x

You don't need to new IConfiguration in the Startup constructor. Its implementation will be injected by the DI system.

// Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();            
}

// Startup.cs
public class Startup
{
    public IHostingEnvironment HostingEnvironment { get; private set; }
    public IConfiguration Configuration { get; private set; }

    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        this.HostingEnvironment = env;
        this.Configuration = configuration;
    }
}

.NET Core 1.x

You need to tell Startup to load the appsettings files.

// Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

        host.Run();
    }
}

//Startup.cs
public class Startup
{
    public IConfigurationRoot Configuration { get; private set; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        this.Configuration = builder.Build();
    }
    ...
}

Getting Values

There are many ways you can get the value you configure from the app settings:

Let's say your appsettings.json looks like this:

{
    "ConnectionStrings": {
        ...
    },
    "AppIdentitySettings": {
        "User": {
            "RequireUniqueEmail": true
        },
        "Password": {
            "RequiredLength": 6,
            "RequireLowercase": true,
            "RequireUppercase": true,
            "RequireDigit": true,
            "RequireNonAlphanumeric": true
        },
        "Lockout": {
            "AllowedForNewUsers": true,
            "DefaultLockoutTimeSpanInMins": 30,
            "MaxFailedAccessAttempts": 5
        }
    },
    "Recaptcha": { 
        ...
    },
    ...
}

Simple Way

You can inject the whole configuration into the constructor of your controller/class (via IConfiguration) and get the value you want with a specified key:

public class AccountController : Controller
{
    private readonly IConfiguration _config;

    public AccountController(IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    public IActionResult ResetPassword(int userId, string code)
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _config.GetValue<int>(
                "AppIdentitySettings:Password:RequiredLength"),
            RequireUppercase = _config.GetValue<bool>(
                "AppIdentitySettings:Password:RequireUppercase")
        };

        return View(vm);
    }
}

Options Pattern

The ConfigurationBuilder.GetValue<T> works great if you only need one or two values from the app settings. But if you want to get multiple values from the app settings, or you don't want to hard code those key strings in multiple places, it might be easier to use Options Pattern. The options pattern uses classes to represent the hierarchy/structure.

To use options pattern:

  1. Define classes to represent the structure
  2. Register the configuration instance which those classes bind against
  3. Inject IOptions<T> into the constructor of the controller/class you want to get values on

1. Define configuration classes to represent the structure

You can define classes with properties that need to exactly match the keys in your app settings. The name of the class does't have to match the name of the section in the app settings:

public class AppIdentitySettings
{
    public UserSettings User { get; set; }
    public PasswordSettings Password { get; set; }
    public LockoutSettings Lockout { get; set; }
}

public class UserSettings
{
    public bool RequireUniqueEmail { get; set; }
}

public class PasswordSettings
{
    public int RequiredLength { get; set; }
    public bool RequireLowercase { get; set; }
    public bool RequireUppercase { get; set; }
    public bool RequireDigit { get; set; }
    public bool RequireNonAlphanumeric { get; set; }
}

public class LockoutSettings
{
    public bool AllowedForNewUsers { get; set; }
    public int DefaultLockoutTimeSpanInMins { get; set; }
    public int MaxFailedAccessAttempts { get; set; }
}

2. Register the configuration instance

And then you need to register this configuration instance in ConfigureServices() in the start up:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
...

namespace DL.SO.UI.Web
{
    public class Startup
    {
        ...
        public void ConfigureServices(IServiceCollection services)
        {
            ...
            var identitySettingsSection = 
                _configuration.GetSection("AppIdentitySettings");
            services.Configure<AppIdentitySettings>(identitySettingsSection);
            ...
        }
        ...
    }
}

3. Inject IOptions

Lastly on the controller/class you want to get the values, you need to inject IOptions<AppIdentitySettings> through constructor:

public class AccountController : Controller
{
    private readonly AppIdentitySettings _appIdentitySettings;

    public AccountController(IOptions<AppIdentitySettings> appIdentitySettingsAccessor)
    {
        _appIdentitySettings = appIdentitySettingsAccessor.Value;
    }

    [AllowAnonymous]
    public IActionResult ResetPassword(int userId, string code)
    {
        var vm = new ResetPasswordViewModel
        {
            PasswordRequiredLength = _appIdentitySettings.Password.RequiredLength,
            RequireUppercase = _appIdentitySettings.Password.RequireUppercase
        };

        return View(vm);
    }
}

Firebug-like debugger for Google Chrome

There is a Firebug-like tool already built into Chrome. Just right click anywhere on a page and choose "Inspect element" from the menu. Chrome has a graphical tool for debugging (like in Firebug), so you can debug JavaScript. It also does CSS inspection well and can even change CSS rendering on the fly.

For more information, see https://developers.google.com/chrome-developer-tools/

How to get the cursor to change to the hand when hovering a <button> tag

Just add this style:

cursor: pointer;

The reason it's not happening by default is because most browsers reserve the pointer for links only (and maybe a couple other things I'm forgetting, but typically not <button>s).

More on the cursor property: https://developer.mozilla.org/en/CSS/cursor

I usually apply this to <button> and <label> by default.

NOTE: I just caught this:

the button tags have an id of #more

It's very important that each element has it's own unique id, you cannot have duplicates. Use the class attribute instead, and change your selector from #more to .more. This is actually quite a common mistake that is the cause of many problems and questions asked here. The earlier you learn how to use id, the better.

Is there a way to use max-width and height for a background image?

As thirtydot said, you can use the CSS3 background-size syntax:

For example:

-o-background-size:35% auto;
-webkit-background-size:35% auto;
-moz-background-size:35% auto;
background-size:35% auto;

However, as also stated by thirtydot, this does not work in IE6, 7 and 8.

See the following links for more information about background-size: http://www.w3.org/TR/css3-background/#the-background-size

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

Updated:

<build> 
  <plugins> 
    <plugin> 
    <artifactId>maven-dependency-plugin</artifactId> 
    <executions> 
      <execution> 
        <phase>install</phase> 
          <goals> 
            <goal>copy-dependencies</goal> 
          </goals> 
          <configuration> 
             <outputDirectory>${project.build.directory}/lib</outputDirectory> 
          </configuration> 
        </execution> 
      </executions> 
    </plugin> 
  </plugins> 
</build> 

get UTC timestamp in python with datetime

I feel like the main answer is still not so clear, and it's worth taking the time to understand time and timezones.

The most important thing to understand when dealing with time is that time is relative!

  • 2017-08-30 13:23:00: (a naive datetime), represents a local time somewhere in the world, but note that 2017-08-30 13:23:00 in London is NOT THE SAME TIME as 2017-08-30 13:23:00 in San Francisco.

Because the same time string can be interpreted as different points-in-time depending on where you are in the world, there is a need for an absolute notion of time.

A UTC timestamp is a number in seconds (or milliseconds) from Epoch (defined as 1 January 1970 00:00:00 at GMT timezone +00:00 offset).

Epoch is anchored on the GMT timezone and therefore is an absolute point in time. A UTC timestamp being an offset from an absolute time therefore defines an absolute point in time.

This makes it possible to order events in time.

Without timezone information, time is relative, and cannot be converted to an absolute notion of time without providing some indication of what timezone the naive datetime should be anchored to.

What are the types of time used in computer system?

  • naive datetime: usually for display, in local time (i.e. in the browser) where the OS can provide timezone information to the program.

  • UTC timestamps: A UTC timestamp is an absolute point in time, as mentioned above, but it is anchored in a given timezone, so a UTC timestamp can be converted to a datetime in any timezone, however it does not contain timezone information. What does that mean? That means that 1504119325 corresponds to 2017-08-30T18:55:24Z, or 2017-08-30T17:55:24-0100 or also 2017-08-30T10:55:24-0800. It doesn't tell you where the datetime recorded is from. It's usually used on the server side to record events (logs, etc...) or used to convert a timezone aware datetime to an absolute point in time and compute time differences.

  • ISO-8601 datetime string: The ISO-8601 is a standardized format to record datetime with timezone. (It's in fact several formats, read on here: https://en.wikipedia.org/wiki/ISO_8601) It is used to communicate timezone aware datetime information in a serializable manner between systems.

When to use which? or rather when do you need to care about timezones?

  • If you need in any way to care about time-of-day, you need timezone information. A calendar or alarm needs time-of-day to set a meeting at the correct time of the day for any user in the world. If this data is saved on a server, the server needs to know what timezone the datetime corresponds to.

  • To compute time differences between events coming from different places in the world, UTC timestamp is enough, but you lose the ability to analyze at what time of day events occured (ie. for web analytics, you may want to know when users come to your site in their local time: do you see more users in the morning or the evening? You can't figure that out without time of day information.

Timezone offset in a date string:

Another point that is important, is that timezone offset in a date string is not fixed. That means that because 2017-08-30T10:55:24-0800 says the offset -0800 or 8 hours back, doesn't mean that it will always be!

In the summer it may well be in daylight saving time, and it would be -0700

What that means is that timezone offset (+0100) is not the same as timezone name (Europe/France) or even timezone designation (CET)

America/Los_Angeles timezone is a place in the world, but it turns into PST (Pacific Standard Time) timezone offset notation in the winter, and PDT (Pacific Daylight Time) in the summer.

So, on top of getting the timezone offset from the datestring, you should also get the timezone name to be accurate.

Most packages will be able to convert numeric offsets from daylight saving time to standard time on their own, but that is not necessarily trivial with just offset. For example WAT timezone designation in West Africa, is UTC+0100 just like CET timezone in France, but France observes daylight saving time, while West Africa does not (because they're close to the equator)

So, in short, it's complicated. VERY complicated, and that's why you should not do this yourself, but trust a package that does it for you, and KEEP IT UP TO DATE!

What is the difference between instanceof and Class.isAssignableFrom(...)?

When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime.

TypeScript - Append HTML to container element in Angular 2

You could do something like this:

htmlComponent.ts

htmlVariable: string = "<b>Some html.</b>"; //this is html in TypeScript code that you need to display

htmlComponent.html

<div [innerHtml]="htmlVariable"></div> //this is how you display html code from TypeScript in your html

How to convert JSON to XML or XML to JSON?

Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. You cannot automatically conform to all interface possibilities, and there is limited built-in support in controlling the conversion- many JSON structures and values cannot automatically be converted both ways. Keep in mind I am using the default settings with Newtonsoft JSON library and MS XML library, so your mileage may vary:

XML -> JSON

  1. All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases.
  2. Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases.
  3. Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries.
  4. In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null

A new update changes how null can be handled (Thanks to Jon Story for pointing it out): https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

JSON -> XML

  1. You need a top level object that will convert to a root XML element or the parser will fail.
  2. Your object names cannot start with a number, as they cannot be converted to elements (XML is technically even more strict than this) but I can 'get away' with breaking some of the other element naming rules.

Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup. As StaxMan mentions, your situation may actually require that you convert between objects...this could entail appropriate interfaces and a bunch of case statements/etc to handle the caveats I mention above.

Changing the text on a label

I made a small tkinter application which is sets the label after button clicked

#!/usr/bin/env python
from Tkinter import *
from tkFileDialog import askopenfilename
from tkFileDialog import askdirectory


class Application:
    def __init__(self, master):
        frame = Frame(master,width=200,height=200)
        frame.pack()

        self.log_file_btn = Button(frame, text="Select Log File", command=self.selectLogFile,width=25).grid(row=0)
        self.image_folder_btn = Button(frame, text="Select Image Folder", command=self.selectImageFile,width=25).grid(row=1)
        self.quite_button = Button(frame, text="QUIT", fg="red", command=frame.quit,width=25).grid(row=5)

        self.logFilePath =StringVar()
        self.imageFilePath = StringVar()
        self.labelFolder = Label(frame,textvariable=self.logFilePath).grid(row=0,column=1)
        self.labelImageFile = Label(frame,textvariable = self.imageFilePath).grid(row = 1,column=1)

        def selectLogFile(self):
            filename = askopenfilename()
            self.logFilePath.set(filename)

        def selectImageFile(self):
            imageFolder = askdirectory()
            self.imageFilePath.set(imageFolder)

root = Tk()
root.title("Geo Tagging")
root.geometry("600x100")
app = Application(root)
root.mainloop()

Join two data frames, select all columns from one and some columns from the other

Without using alias.

df1.join(df2, df1.id == df2.id).select(df1["*"],df2["other"])

Parse string to date with moment.js

Maybe try the Intl polyfill for IE8 or the olyfill service ?

or

https://github.com/andyearnshaw/Intl.js/

Usage of \b and \r in C

The characters are exactly as documented - \b equates to a character code of 0x08 and \r equates to 0x0d. The thing that varies is how your OS reacts to those characters. Back when displays were trying to emulate an old teletype those actions were standardized, but they are less useful in modern environments and compatibility is not guaranteed.

'uint32_t' identifier not found error

I have the same error and it fixed it including in the file the following

#include <stdint.h>

at the beginning of your file.

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

In short:

  • getPath() gets the path string that the File object was constructed with, and it may be relative current directory.
  • getAbsolutePath() gets the path string after resolving it against the current directory if it's relative, resulting in a fully qualified path.
  • getCanonicalPath() gets the path string after resolving any relative path against current directory, and removes any relative pathing (. and ..), and any file system links to return a path which the file system considers the canonical means to reference the file system object to which it points.

Also, each of these has a File equivalent which returns the corresponding File object.

Note that IMO, Java got the implementation of an "absolute" path wrong; it really should remove any relative path elements in an absolute path. The canonical form would then remove any FS links or junctions in the path.

Interview question: Check if one string is a rotation of other string

Another python example (based on THE answer):

def isrotation(s1,s2):
     return len(s1)==len(s2) and s1 in 2*s2

Return a value if no rows are found in Microsoft tSQL

You can do something just like this.

IF EXISTS ( SELECT * FROM TableName WHERE Column=colval)
BEGIN
   select 
select name ,Id from TableName WHERE Column=colval
END
ELSE
  SELECT 'test' as name,0 as Id

Setting up redirect in web.config file

  1. Open web.config in the directory where the old pages reside
  2. Then add code for the old location path and new destination as follows:

    <configuration>
      <location path="services.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/services" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
      <location path="products.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/products" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
    </configuration>
    

You may add as many location paths as necessary.

Setting a divs background image to fit its size?

If you'd like to use CSS3, you can do it pretty simply using background-size, like so:

background-size: 100%;

It is supported by all major browsers (including IE9+). If you'd like to get it working in IE8 and before, check out the answers to this question.

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

There is a package called eclipse-cdt in the Ubuntu 12.10 repositories, this is what you want. If you haven't got g++ already, you need to install that as well, so all you need is:

sudo apt-get install eclipse eclipse-cdt g++

Whether you messed up your system with your previous installation attempts depends heavily on how you did it. If you did it the safe way for trying out new packages not from repositories (i.e., only installed in your home folder, no sudos blindly copied from installation manuals...) you're definitely fine. Otherwise, you may well have thousands of stray files all over your file system now. In that case, run all uninstall scripts you can find for the things you installed, then install using apt-get and hope for the best.

How to set a dropdownlist item as selected in ASP.NET?

You can set the SelectedValue to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error.

dropdownlist.ClearSelection();
dropdownlist.SelectedValue = value;

You can also use ListItemCollection.FindByText or ListItemCollection.FindByValue

dropdownlist.ClearSelection();  
dropdownlist.Items.FindByValue(value).Selected = true;

Use the FindByValue method to search the collection for a ListItem with a Value property that contains value specified by the value parameter. This method performs a case-sensitive and culture-insensitive comparison. This method does not do partial searches or wildcard searches. If an item is not found in the collection using this criteria, null is returned, MSDN.

If you expect that you may be looking for text/value that wont be present in DropDownList ListItem collection then you must check if you get the ListItem object or null from FindByText or FindByValue before you access Selected property. If you try to access Selected when null is returned then you will get NullReferenceException.

ListItem listItem = dropdownlist.Items.FindByValue(value);

if(listItem != null) 
{
   dropdownlist.ClearSelection();
   listItem.Selected = true;
}

How to start and stop android service from a adb shell?

am startservice <INTENT>   

or actually from the OS shell

adb shell am startservice <INTENT>

Why calling react setState method doesn't mutate the state immediately?

Simply putting - this.setState({data: value}) is asynchronous in nature that means it moves out of the Call Stack and only comes back to the Call Stack unless it is resolved.

Please read about Event Loop to have a clear picture about Asynchronous nature in JS and why it takes time to update -

https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4

Hence -

    this.setState({data:value});
    console.log(this.state.data); // will give undefined or unupdated value

as it takes time to update. To achieve the above process -

    this.setState({data:value},function () {
     console.log(this.state.data);
    });

No Title Bar Android Theme

Why are you changing android os inbuilt theme.

As per your activity Require You have to implements this way

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

as per @arianoo says you have to used this feature.

I think this is better way to hide titlebar theme.

Multiprocessing a for loop?

You can use multiprocessing.Pool:

from multiprocessing import Pool
class Engine(object):
    def __init__(self, parameters):
        self.parameters = parameters
    def __call__(self, filename):
        sci = fits.open(filename + '.fits')
        manipulated = manipulate_image(sci, self.parameters)
        return manipulated

try:
    pool = Pool(8) # on 8 processors
    engine = Engine(my_parameters)
    data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
    pool.close()
    pool.join()

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I'd guess foreign key constraint problem. Is country_id used as a foreign key in another table?

I'm not DB guru but I think I solved a problem like this (where there was a fk constraint) by removing the fk, doing my alter table stuff and then redoing the fk stuff.

I'll be interested to hear what the outcome is - sometime mysql is pretty cryptic.

CSS @font-face not working with Firefox, but working with Chrome and IE

I was having the same problem getting a font to display properly in Firefox. Here is what I found to work for me. Add a slash before the directory holding the font in the url attribute. Here is my before and after versions:

B E F O R E:
   @font-face
{   font-family: "GrilledCheese BTN";
    src: url(fonts/grilcb__.ttf);
}

A F T E R:
@font-face
{   font-family: "GrilledCheese BTN";
    src: url(/fonts/grilcb__.ttf);
}

notice the leading slash before 'fonts' in the url? This tells the browser to start at the root directory and then access the resource. At least for me - Problem Solved.

Java java.sql.SQLException: Invalid column index on preparing statement

As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....

The ? and the OR needs to be seperated by a space character. Do it wherever needed in the query string.

What methods of ‘clearfix’ can I use?

The new standard, as used by Inuit.css and Bourbon - two very widely used and well-maintained CSS/Sass frameworks:

.btcf:after {
    content:"";
    display:block;
    clear:both;
}

Notes

Keep in mind that clearfixes are essentially a hack for what flexbox layouts can now provide in a much smarter way. CSS floats were originally designed for inline content to flow around - like images in a long textual article - and not for grid layouts and the like. If your target browsers support flexbox, it's worth looking into.

This doesn't support IE7. You shouldn't be supporting IE7. Doing so continues to expose users to unfixed security exploits and makes life harder for all other web developers, as it reduces the pressure on users and organisations to switch to modern browsers.

This clearfix was announced and explained by Thierry Koblentz in July 2012. It sheds unnecessary weight from Nicolas Gallagher's 2011 micro-clearfix. In the process, it frees a pseudo-element for your own use. This has been updated to use display: block rather than display: table (again, credit to Thierry Koblentz).

Getting the 'external' IP address in Java

As @Donal Fellows wrote, you have to query the network interface instead of the machine. This code from the javadocs worked for me:

The following example program lists all the network interfaces and their addresses on a machine:

import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }
} 

The following is sample output from the example program:

Display name: TCP Loopback interface
Name: lo
InetAddress: /127.0.0.1

Display name: Wireless Network Connection
Name: eth0
InetAddress: /192.0.2.0

From docs.oracle.com

Sorting A ListView By Column

i used this trick

private void lv_TavComEmpty_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            ListView lv = (ListView)sender;

            //propriety SortOrder make me some problem on graphic layout
            //i use this tag to set last order
            if (lv.Tag == null || (int)lv.Tag > 0)
            //if (lv.Sorting == SortOrder.Ascending)
            {
                ListViewItem[] tmp = lv.Items.Cast<ListViewItem>().OrderBy(t => t.SubItems[e.Column].Text).ToArray();
                lv.Items.Clear();
                lv.Items.AddRange(tmp);

                lv.Tag = -1;
                //lv.Sorting = SortOrder.Descending;
            }
            else
            {
                ListViewItem[] tmp = lv.Items.Cast<ListViewItem>().OrderByDescending(t => t.SubItems[e.Column].Text).ToArray();
                lv.Items.Clear();
                lv.Items.AddRange(tmp);

                lv.Tag = +1;
                //lv.Sorting = SortOrder.Ascending;
            }
        }

javascript compare strings without being case sensitive

You can also use string.match().

var string1 = "aBc";
var match = string1.match(/AbC/i);

if(match) {
}

How can I loop through all rows of a table? (MySQL)

    Use this:

    $stmt = $user->runQuery("SELECT * FROM tbl WHERE ID=:id");
    $stmt->bindparam(":id",$id);
    $stmt->execute();

        $stmt->bindColumn("a_b",$xx);
        $stmt->bindColumn("c_d",$yy);


    while($rows = $stmt->fetch(PDO::FETCH_BOUND))
    {
        //---insert into new tble
    }   

About catching ANY exception

You can do this to handle general exceptions

try:
    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message

How do I use FileSystemObject in VBA?

These guys have excellent examples of how to use the filesystem object http://www.w3schools.com/asp/asp_ref_filesystem.asp

<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%> 

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

I had the same issue when upgrading from Tomcat 7 to 8: a continuous large flood of log warnings about cache.

1. Short Answer

Add this within the Context xml element of your $CATALINA_BASE/conf/context.xml:

<!-- The default value is 10240 kbytes, even when not added to context.xml.
So increase it high enough, until the problem disappears, for example set it to 
a value 5 times as high: 51200. -->
<Resources cacheMaxSize="51200" />

So the default is 10240 (10 mbyte), so set a size higher than this. Than tune for optimum settings where the warnings disappear. Note that the warnings may come back under higher traffic situations.

1.1 The cause (short explanation)

The problem is caused by Tomcat being unable to reach its target cache size due to cache entries that are less than the TTL of those entries. So Tomcat didn't have enough cache entries that it could expire, because they were too fresh, so it couldn't free enough cache and thus outputs warnings.

The problem didn't appear in Tomcat 7 because Tomcat 7 simply didn't output warnings in this situation. (Causing you and me to use poor cache settings without being notified.)

The problem appears when receiving a relative large amount of HTTP requests for resources (usually static) in a relative short time period compared to the size and TTL of the cache. If the cache is reaching its maximum (10mb by default) with more than 95% of its size with fresh cache entries (fresh means less than less than 5 seconds in cache), than you will get a warning message for each webResource that Tomcat tries to load in the cache.

1.2 Optional info

Use JMX if you need to tune cacheMaxSize on a running server without rebooting it.

The quickest fix would be to completely disable cache: <Resources cachingAllowed="false" />, but that's suboptimal, so increase cacheMaxSize as I just described.

2. Long Answer

2.1 Background information

A WebSource is a file or directory in a web application. For performance reasons, Tomcat can cache WebSources. The maximum of the static resource cache (all resources in total) is by default 10240 kbyte (10 mbyte). A webResource is loaded into the cache when the webResource is requested (for example when loading a static image), it's then called a cache entry. Every cache entry has a TTL (time to live), which is the time that the cache entry is allowed to stay in the cache. When the TTL expires, the cache entry is eligible to be removed from the cache. The default value of the cacheTTL is 5000 milliseconds (5 seconds).

There is more to tell about caching, but that is irrelevant for the problem.

2.2 The cause

The following code from the Cache class shows the caching policy in detail:

152  // Content will not be cached but we still need metadata size
153 long delta = cacheEntry.getSize();
154 size.addAndGet(delta);
156 if (size.get() > maxSize) {
157 // Process resources unordered for speed. Trades cache
158 // efficiency (younger entries may be evicted before older
159 // ones) for speed since this is on the critical path for
160 // request processing
161 long targetSize =
162 maxSize * (100 - TARGET_FREE_PERCENT_GET) / 100;
163 long newSize = evict(
164 targetSize, resourceCache.values().iterator());
165 if (newSize > maxSize) {
166 // Unable to create sufficient space for this resource
167 // Remove it from the cache
168 removeCacheEntry(path);
169 log.warn(sm.getString("cache.addFail", path));
170 }
171 }

When loading a webResource, the code calculates the new size of the cache. If the calculated size is larger than the default maximum size, than one or more cached entries have to be removed, otherwise the new size will exceed the maximum. So the code will calculate a "targetSize", which is the size the cache wants to stay under (as an optimum), which is by default 95% of the maximum. In order to reach this targetSize, entries have to be removed/evicted from the cache. This is done using the following code:

215  private long evict(long targetSize, Iterator<CachedResource> iter) {
217 long now = System.currentTimeMillis();
219 long newSize = size.get();
221 while (newSize > targetSize && iter.hasNext()) {
222 CachedResource resource = iter.next();
224 // Don't expire anything that has been checked within the TTL
225 if (resource.getNextCheck() > now) {
226 continue;
227 }
229 // Remove the entry from the cache
230 removeCacheEntry(resource.getWebappPath());
232 newSize = size.get();
233 }
235 return newSize;
236 }

So a cache entry is removed when its TTL is expired and the targetSize hasn't been reached yet.

After the attempt to free cache by evicting cache entries, the code will do:

165  if (newSize > maxSize) {
166 // Unable to create sufficient space for this resource
167 // Remove it from the cache
168 removeCacheEntry(path);
169 log.warn(sm.getString("cache.addFail", path));
170 }

So if after the attempt to free cache, the size still exceeds the maximum, it will show the warning message about being unable to free:

cache.addFail=Unable to add the resource at [{0}] to the cache for web application [{1}] because there was insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache

2.3 The problem

So as the warning message says, the problem is

insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache

If your web application loads a lot of uncached webResources (about maximum of cache, by default 10mb) within a short time (5 seconds), then you'll get the warning.

The confusing part is that Tomcat 7 didn't show the warning. This is simply caused by this Tomcat 7 code:

1606  // Add new entry to cache
1607 synchronized (cache) {
1608 // Check cache size, and remove elements if too big
1609 if ((cache.lookup(name) == null) && cache.allocate(entry.size)) {
1610 cache.load(entry);
1611 }
1612 }

combined with:

231  while (toFree > 0) {
232 if (attempts == maxAllocateIterations) {
233 // Give up, no changes are made to the current cache
234 return false;
235 }

So Tomcat 7 simply doesn't output any warning at all when it's unable to free cache, whereas Tomcat 8 will output a warning.

So if you are using Tomcat 8 with the same default caching configuration as Tomcat 7, and you got warnings in Tomcat 8, than your (and mine) caching settings of Tomcat 7 were performing poorly without warning.

2.4 Solutions

There are multiple solutions:

  1. Increase cache (recommended)
  2. Lower the TTL (not recommended)
  3. Suppress cache log warnings (not recommended)
  4. Disable cache

2.4.1. Increase cache (recommended)

As described here: http://tomcat.apache.org/tomcat-8.0-doc/config/resources.html

By adding <Resources cacheMaxSize="XXXXX" /> within the Context element in $CATALINA_BASE/conf/context.xml, where "XXXXX" stands for an increased cache size, specified in kbytes. The default is 10240 (10 mbyte), so set a size higher than this.

You'll have to tune for optimum settings. Note that the problem may come back when you suddenly have an increase in traffic/resource requests.

To avoid having to restart the server every time you want to try a new cache size, you can change it without restarting by using JMX.

To enable JMX, add this to $CATALINA_BASE/conf/server.xml within the Server element: <Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener" rmiRegistryPortPlatform="6767" rmiServerPortPlatform="6768" /> and download catalina-jmx-remote.jar from https://tomcat.apache.org/download-80.cgi and put it in $CATALINA_HOME/lib. Then use jConsole (shipped by default with the Java JDK) to connect over JMX to the server and look through the settings for settings to increase the cache size while the server is running. Changes in these settings should take affect immediately.

2.4.2. Lower the TTL (not recommended)

Lower the cacheTtl value by something lower than 5000 milliseconds and tune for optimal settings.

For example: <Resources cacheTtl="2000" />

This comes effectively down to having and filling a cache in ram without using it.

2.4.3. Suppress cache log warnings (not recommended)

Configure logging to disable the logger for org.apache.catalina.webresources.Cache.

For more info about logging in Tomcat: http://tomcat.apache.org/tomcat-8.0-doc/logging.html

2.4.4. Disable cache

You can disable the cache by setting cachingAllowed to false. <Resources cachingAllowed="false" />

Although I can remember that in a beta version of Tomcat 8, I was using JMX to disable the cache. (Not sure why exactly, but there may be a problem with disabling the cache via server.xml.)

How to convert column with string type to int form in pyspark data frame?

You could use cast(as int) after replacing NaN with 0,

data_df = df.withColumn("Plays", df.call_time.cast('float'))

Android studio: emulator is running but not showing up in Run App "choose a running device"

Wipe the data of your Android virtual Device and then start the emulator. Works for me.

Is it ok to run docker from inside docker?

Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".

And also it would require to run the docker in privileged mode, so the commands would be:

sudo chmod 757 /var/run/docker.sock

docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...

Highlighting Text Color using Html.fromHtml() in Android?

 String name = modelOrderList.get(position).getName();   //get name from List
    String text = "<font color='#000000'>" + name + "</font>"; //set Black color of name
    /* check API version, according to version call method of Html class  */
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
        Log.d(TAG, "onBindViewHolder: if");
        holder.textViewName.setText(context.getString(R.string._5687982) + " ");
        holder.textViewName.append(Html.fromHtml(text));
    } else {
        Log.d(TAG, "onBindViewHolder: else");
        holder.textViewName.setText("123456" + " ");   //set text 
        holder.textViewName.append(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY));   //append text into textView
    }

How to get parameters from a URL string?

you can use below code to get email address after ? in the URL

_x000D_
_x000D_
<?php_x000D_
if (isset($_GET['email'])) {_x000D_
    echo $_GET['email'];_x000D_
}
_x000D_
_x000D_
_x000D_

jQuery - setting the selected value of a select control via its text description

Just on a side note. My selected value was not being set. And i had search all over the net. Actually i had to select a value after a call back from a web service, because i was getting data from it.

$("#SelectMonth option[value=" + DataFromWebService + "]").attr('selected', 'selected'); 
$("#SelectMonth").selectmenu('refresh', true);

So the refresh of the selector was was the only thing that i was missing.

How to split a dataframe string column into two columns?

TL;DR version:

For the simple case of:

  • I have a text column with a delimiter and I want two columns

The simplest solution is:

df[['A', 'B']] = df['AB'].str.split(' ', 1, expand=True)

You must use expand=True if your strings have a non-uniform number of splits and you want None to replace the missing values.

Notice how, in either case, the .tolist() method is not necessary. Neither is zip().

In detail:

Andy Hayden's solution is most excellent in demonstrating the power of the str.extract() method.

But for a simple split over a known separator (like, splitting by dashes, or splitting by whitespace), the .str.split() method is enough1. It operates on a column (Series) of strings, and returns a column (Series) of lists:

>>> import pandas as pd
>>> df = pd.DataFrame({'AB': ['A1-B1', 'A2-B2']})
>>> df

      AB
0  A1-B1
1  A2-B2
>>> df['AB_split'] = df['AB'].str.split('-')
>>> df

      AB  AB_split
0  A1-B1  [A1, B1]
1  A2-B2  [A2, B2]

1: If you're unsure what the first two parameters of .str.split() do, I recommend the docs for the plain Python version of the method.

But how do you go from:

  • a column containing two-element lists

to:

  • two columns, each containing the respective element of the lists?

Well, we need to take a closer look at the .str attribute of a column.

It's a magical object that is used to collect methods that treat each element in a column as a string, and then apply the respective method in each element as efficient as possible:

>>> upper_lower_df = pd.DataFrame({"U": ["A", "B", "C"]})
>>> upper_lower_df

   U
0  A
1  B
2  C
>>> upper_lower_df["L"] = upper_lower_df["U"].str.lower()
>>> upper_lower_df

   U  L
0  A  a
1  B  b
2  C  c

But it also has an "indexing" interface for getting each element of a string by its index:

>>> df['AB'].str[0]

0    A
1    A
Name: AB, dtype: object

>>> df['AB'].str[1]

0    1
1    2
Name: AB, dtype: object

Of course, this indexing interface of .str doesn't really care if each element it's indexing is actually a string, as long as it can be indexed, so:

>>> df['AB'].str.split('-', 1).str[0]

0    A1
1    A2
Name: AB, dtype: object

>>> df['AB'].str.split('-', 1).str[1]

0    B1
1    B2
Name: AB, dtype: object

Then, it's a simple matter of taking advantage of the Python tuple unpacking of iterables to do

>>> df['A'], df['B'] = df['AB'].str.split('-', 1).str
>>> df

      AB  AB_split   A   B
0  A1-B1  [A1, B1]  A1  B1
1  A2-B2  [A2, B2]  A2  B2

Of course, getting a DataFrame out of splitting a column of strings is so useful that the .str.split() method can do it for you with the expand=True parameter:

>>> df['AB'].str.split('-', 1, expand=True)

    0   1
0  A1  B1
1  A2  B2

So, another way of accomplishing what we wanted is to do:

>>> df = df[['AB']]
>>> df

      AB
0  A1-B1
1  A2-B2

>>> df.join(df['AB'].str.split('-', 1, expand=True).rename(columns={0:'A', 1:'B'}))

      AB   A   B
0  A1-B1  A1  B1
1  A2-B2  A2  B2

The expand=True version, although longer, has a distinct advantage over the tuple unpacking method. Tuple unpacking doesn't deal well with splits of different lengths:

>>> df = pd.DataFrame({'AB': ['A1-B1', 'A2-B2', 'A3-B3-C3']})
>>> df
         AB
0     A1-B1
1     A2-B2
2  A3-B3-C3
>>> df['A'], df['B'], df['C'] = df['AB'].str.split('-')
Traceback (most recent call last):
  [...]    
ValueError: Length of values does not match length of index
>>> 

But expand=True handles it nicely by placing None in the columns for which there aren't enough "splits":

>>> df.join(
...     df['AB'].str.split('-', expand=True).rename(
...         columns={0:'A', 1:'B', 2:'C'}
...     )
... )
         AB   A   B     C
0     A1-B1  A1  B1  None
1     A2-B2  A2  B2  None
2  A3-B3-C3  A3  B3    C3

How to remove focus from input field in jQuery?

For all textbox :

$(':text').blur()

How to have css3 animation to loop forever

add this styles

animation-iteration-count:infinite;

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid Reference: https://en.wikipedia.org/wiki/Typeid

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

What is the difference between docker-compose ports vs expose

I totally agree with the answers before. I just like to mention that the difference between expose and ports is part of the security concept in docker. It goes hand in hand with the networking of docker. For example:

Imagine an application with a web front-end and a database back-end. The outside world needs access to the web front-end (perhaps on port 80), but only the back-end itself needs access to the database host and port. Using a user-defined bridge, only the web port needs to be opened, and the database application doesn’t need any ports open, since the web front-end can reach it over the user-defined bridge.

This is a common use case when setting up a network architecture in docker. So for example in a default bridge network, not ports are accessible from the outer world. Therefor you can open an ingresspoint with "ports". With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.

Disable automatic sorting on the first column when using jQuery DataTables

this.dtOptions = {
    order: [],
    columnDefs: [ {
        'targets': [0], /* column index [0,1,2,3]*/
        'orderable': false, /* true or false */
    }],
    ........ rest all stuff .....
}

The above worked fine for me.

(I am using Angular version 7, angular-datatables version 6.0.0 and bootstrap version 4)

How to list containers in Docker

There are many ways to list all containers.

You can find using 3 Aliasesls, ps, list like this.

sudo docker container ls 
sudo docker container ps
sudo docker container list
sudo docker ps
sudo docker ps -a

You can also use give option[option].

Options -:

  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display numeric IDs
  -s, --size            Display total file sizes

You can use an option like this:

sudo docker ps //Showing only running containers
sudo docker ps -a //All container (running + stopped)
sudo docker pa -l // latest
sudo docker ps -n <int valuse 1,2,3 etc>// latest number of created containers
sudo docker ps -s // Display container with size
sudo docker ps -q // Only display numeric IDs for containers
docker docker ps -a | tail -n 1 //oldest container

In C#, why is String a reference type that behaves like a value type?

How can you tell string is a reference type? I'm not sure that it matters how it is implemented. Strings in C# are immutable precisely so that you don't have to worry about this issue.

How can I determine installed SQL Server instances and their versions?

The commands OSQL -L and SQLCMD -L will show you all instances on the network.

If you want to have a list of all instances on the server and doesn't feel like doing scripting or programming, do this:

  1. Start Windows Task Manager
  2. Tick the checkbox "Show processes from all users" or equivalent
  3. Sort the processes by "Image Name"
  4. Locate all sqlsrvr.exe images

The instances should be listed in the "User Name" column as MSSQL$INSTANCE_NAME.

And I went from thinking the poor server was running 63 instances to realizing it was running three (out of which one was behaving like a total bully with the CPU load...)

Select all text inside EditText when it gets focus

I know you've found a solution, but really the proper way to do what you're asking is to just use the android:hint attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.

text-align: right; not working for <label>

As stated in other answers, label is an inline element. However, you can apply display: inline-block to the label and then center with text-align.

#name_label {
    display: inline-block;
    width: 90%;
    text-align: right;
}

Why display: inline-block and not display: inline? For the same reason that you can't align label, it's inline.

Why display: inline-block and not display: block? You could use display: block, but it will be on another line. display: inline-block combines the properties of inline and block. It's inline, but you can also give it a width, height, and align it.

How to find the width of a div using vanilla JavaScript?

Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.

var elem = document.getElementById("myDiv");
if(elem) {
   var rect = elem.getBoundingClientRect();
   console.log(rect.width);  
}

Python - Using regex to find multiple matches and print them out

Instead of using re.search use re.findall it will return you all matches in a List. Or you could also use re.finditer (which i like most to use) it will return an Iterator Object and you can just use it to iterate over all found matches.

line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
    print match.group(1)

Is Fortran easier to optimize than C for heavy calculations?

Fortran has better I/O routines, e.g. the implied do facility gives flexibility that C's standard library can't match.

The Fortran compiler directly handles the more complex syntax involved, and as such syntax can't be easily reduced to argument passing form, C can't implement it efficiently.

javascript if number greater than number

You should convert them to number before compare.

Try:

if (+x > +y) {
  //...
}

or

if (Number(x) > Number(y)) {
  // ...
}

Note: parseFloat and pareseInt(for compare integer, and you need to specify the radix) will give you NaN for an empty string, compare with NaN will always be false, If you don't want to treat empty string be 0, then you could use them.

Flexbox: 4 items per row

Here is another apporach.

You can accomplish it in this way too:

.parent{
  display: flex;
  flex-wrap: wrap;
}

.child{
  width: 25%;
  box-sizing: border-box;
}

Sample: https://codepen.io/capynet/pen/WOPBBm

And a more complete sample: https://codepen.io/capynet/pen/JyYaba

ImportError: No module named pip

On some kind of linux like ubuntu, first, do apt-get update and then try installing the python-pip package. without apt-get update, you might get error such as

E: Unable to locate package python-pip

1.Update :

sudo apt-get update

2.Install the pip package

For python2

sudo apt-get install python-pip

or

For python3

sudo apt-get install python3-pip

And done!

How can I position my jQuery dialog to center?

Try this for older versions and somebody who don't want to use position:

$("#dialog-div-id").dialog({position: ['center', 'top'],....

position: fixed doesn't work on iPad and iPhone

This might not be applicable to all scenarios, but I found that the position: sticky (same thing with position: fixed) only works on old iPhones when the scrolling container is not the body, but inside something else.

Example pseudo html:

body                         <- scrollbar
   relative div
       sticky div

The sticky div will be sticky on desktop browsers, but with certain devices, tested with: Chromium: dev tools: device emultation: iPhone 6/7/8, and with Android 4 Firefox, it will not.

What will work, however, is

body
    div overflow=auto       <- scrollbar
        relative div
            sticky div

Is there a way to force npm to generate package-lock.json?

When working with local packages, the only way I found to reliably regenerate the package-lock.json file is to delete it, as well as in the linked modules and all corresponding node_modules folders and let it be regenerated with npm i

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.

I can't figure out exactly what's there, yet ...

edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.

A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.

If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

How to revert multiple git commits?

This is an expansion of one of the solutions provided in Jakub's answer

I was faced with a situation where the commits I needed to roll back were somewhat complex, with several of the commits being merge commits, and I needed to avoid rewriting history. I was not able to use a series of git revert commands because I eventually ran into conflicts between the reversion changes being added. I ended up using the following steps.

First, check out the contents of the target commit while leaving HEAD at the tip of the branch:

$ git checkout -f <target-commit> -- .

(The -- makes sure <target-commit> is interpreted as a commit rather than a file; the . refers to the current directory.)

Then, determine what files were added in the commits being rolled back, and thus need to be deleted:

$ git diff --name-status --cached <target-commit>

Files that were added should show up with an "A" at the beginning of the line, and there should be no other differences. Now, if any files need to be removed, stage these files for removal:

$ git rm <filespec>[ <filespec> ...]

Finally, commit the reversion:

$ git commit -m 'revert to <target-commit>'

If desired, make sure that we're back to the desired state:

$git diff <target-commit> <current-commit>

There should be no differences.

Set a border around a StackPanel.

You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.

If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)

Twitter Bootstrap Multilevel Dropdown Menu

[Twitter Bootstrap v3]

To create a n-level dropdown menu (touch device friendly) in Twitter Bootstrap v3,

CSS:

.dropdown-menu>li /* To prevent selection of text */
{   position:relative;
    -webkit-user-select: none; /* Chrome/Safari */        
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE10+ */
    /* Rules below not implemented in browsers yet */
    -o-user-select: none;
    user-select: none;
    cursor:pointer;
}
.dropdown-menu .sub-menu 
{
    left: 100%;
    position: absolute;
    top: 0;
    display:none;
    margin-top: -1px;
    border-top-left-radius:0;
    border-bottom-left-radius:0;
    border-left-color:#fff;
    box-shadow:none;
}
.right-caret:after,.left-caret:after
 {  content:"";
    border-bottom: 5px solid transparent;
    border-top: 5px solid transparent;
    display: inline-block;
    height: 0;
    vertical-align: middle;
    width: 0;
    margin-left:5px;
}
.right-caret:after
{   border-left: 5px solid #ffaf46;
}
.left-caret:after
{   border-right: 5px solid #ffaf46;
}

JQuery:

$(function(){
    $(".dropdown-menu > li > a.trigger").on("click",function(e){
        var current=$(this).next();
        var grandparent=$(this).parent().parent();
        if($(this).hasClass('left-caret')||$(this).hasClass('right-caret'))
            $(this).toggleClass('right-caret left-caret');
        grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
        grandparent.find(".sub-menu:visible").not(current).hide();
        current.toggle();
        e.stopPropagation();
    });
    $(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
        var root=$(this).closest('.dropdown');
        root.find('.left-caret').toggleClass('right-caret left-caret');
        root.find('.sub-menu:visible').hide();
    });
});

HTML:

<div class="dropdown" style="position:relative">
    <a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Click Here <span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li>
            <a class="trigger right-caret">Level 1</a>
            <ul class="dropdown-menu sub-menu">
                <li><a href="#">Level 2</a></li>
                <li>
                    <a class="trigger right-caret">Level 2</a>
                    <ul class="dropdown-menu sub-menu">
                        <li><a href="#">Level 3</a></li>
                        <li><a href="#">Level 3</a></li>
                        <li>
                            <a class="trigger right-caret">Level 3</a>
                            <ul class="dropdown-menu sub-menu">
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#">Level 2</a></li>
            </ul>
        </li>
        <li><a href="#">Level 1</a></li>
        <li><a href="#">Level 1</a></li>
    </ul>
</div>

How to check if an appSettings key exists?

if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
{
    // Key exists
}
else
{
    // Key doesn't exist
}

How do I import a .bak file into Microsoft SQL Server 2012?

Using the RESTORE DATABASE command most likely. bak is a common extension used for a database backup file. You'll find documentation for this command on MSDN.

How do I obtain a Query Execution Plan in SQL Server?

Here's one important thing to know in addition to everything said before.

Query plans are often too complex to be represented by the built-in XML column type which has a limitation of 127 levels of nested elements. That is one of the reasons why sys.dm_exec_query_plan may return NULL or even throw an error in earlier MS SQL versions, so generally it's safer to use sys.dm_exec_text_query_plan instead. The latter also has a useful bonus feature of selecting a plan for a particular statement rather than the whole batch. Here's how you use it to view plans for currently running statements:

SELECT p.query_plan
FROM sys.dm_exec_requests AS r
OUTER APPLY sys.dm_exec_text_query_plan(
                r.plan_handle,
                r.statement_start_offset,
                r.statement_end_offset) AS p

The text column in the resulting table is however not very handy compared to an XML column. To be able to click on the result to be opened in a separate tab as a diagram, without having to save its contents to a file, you can use a little trick (remember you cannot just use CAST(... AS XML)), although this will only work for a single row:

SELECT Tag = 1, Parent = NULL, [ShowPlanXML!1!!XMLTEXT] = query_plan
FROM sys.dm_exec_text_query_plan(
                -- set these variables or copy values
                -- from the results of the above query
                @plan_handle,
                @statement_start_offset,
                @statement_end_offset)
FOR XML EXPLICIT

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

What are the minimum margins most printers can handle?

Every printer is different but 0.25" (6.35 mm) is a safe bet.

How to load image files with webpack file-loader

Install file loader first:

$ npm install file-loader --save-dev

And add this rule in webpack.config.js

           {
                test: /\.(png|jpg|gif)$/,
                use: [{
                    loader: 'file-loader',
                    options: {}
                }]
            }

Select element based on multiple classes

You mean two classes? "Chain" the selectors (no spaces between them):

.class1.class2 {
    /* style here */
}

This selects all elements with class1 that also have class2.

In your case:

li.left.ui-class-selector {

}

Official documentation : CSS2 class selectors.


As akamike points out a problem with this method in Internet Explorer 6 you might want to read this: Use double classes in IE6 CSS?

AppCompat v7 r21 returning error in values.xml?

I have updated the build.gradle(Module: app): Old Code:

  compile 'com.android.support:appcompat-v7:23.0.1'

New Code:

 compile 'com.android.support:appcompat-v7:22.2.0'

Works for me in android studio.

Split string in JavaScript and detect line break

This is what I used to print text to a canvas. The input is not coming from a textarea, but from input and I'm only splitting by space. Definitely not perfect, but works for my case. It returns the lines in an array:

splitTextToLines: function (text) {
        var idealSplit = 7,
            maxSplit = 20,
            lineCounter = 0,
            lineIndex = 0,
            lines = [""],
            ch, i;

        for (i = 0; i < text.length; i++) {
            ch = text[i];
            if ((lineCounter >= idealSplit && ch === " ") || lineCounter >= maxSplit) {
                ch = "";
                lineCounter = -1;
                lineIndex++;
                lines.push("");
            }
            lines[lineIndex] += ch;
            lineCounter++;
        }

        return lines;
    }

Get list of JSON objects with Spring RestTemplate

I found work around from this post https://jira.spring.io/browse/SPR-8263.

Based on this post you can return a typed list like this:

ResponseEntity<? extends ArrayList<User>> responseEntity = restTemplate.getForEntity(restEndPointUrl, (Class<? extends ArrayList<User>>)ArrayList.class, userId);

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

javascript function wait until another function to finish

In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.

Here is an example I have just written to demonstrate how you could do it using deferreds/promises.

Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.

Hope this helps!

$(function(){
    function1().done(function(){
        // function1 is done, we can now call function2
        console.log('function1 is done!');

        function2().done(function(){
            //function2 is done
            console.log('function2 is done!');
        });
    });
});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}

function function2(){
    var dfrd1 = $.Deferred();
    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function2 is done!');
        dfrd1.resolve();
    }, 2000);
    return dfrd1.promise();
}

When should I use Lazy<T>?

Just to point onto the example posted by Mathew

public sealed class Singleton
{
    // Because Singleton's constructor is private, we must explicitly
    // give the Lazy<Singleton> a delegate for creating the Singleton.
    private static readonly Lazy<Singleton> instanceHolder =
        new Lazy<Singleton>(() => new Singleton());

    private Singleton()
    {
        ...
    }

    public static Singleton Instance
    {
        get { return instanceHolder.Value; }
    }
}

before the Lazy was born we would have done it this way:

private static object lockingObject = new object();
public static LazySample InstanceCreation()
{
    if(lazilyInitObject == null)
    {
         lock (lockingObject)
         {
              if(lazilyInitObject == null)
              {
                   lazilyInitObject = new LazySample ();
              }
         }
    }
    return lazilyInitObject ;
}

Need to get current timestamp in Java

Try this single line solution :

import java.util.Date;
String timestamp = 
    new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss a").format(new Date());

Java: How to get input from System.console()

I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.

It introduces an abstraction layer similar to the one proposed by McDowell. If System.console() returns null, the library switches to a Swing-based console.

In addition, Text-IO has a series of useful features:

  • supports reading values with various data types.
  • allows masking the input when reading sensitive data.
  • allows selecting a value from a list.
  • allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).

Usage example:

TextIO textIO = TextIoFactory.getTextIO();

String user = textIO.newStringInputReader()
        .withDefaultValue("admin")
        .read("Username");

String password = textIO.newStringInputReader()
        .withMinLength(6)
        .withInputMasking(true)
        .read("Password");

int age = textIO.newIntInputReader()
        .withMinVal(13)
        .read("Age");

Month month = textIO.newEnumInputReader(Month.class)
        .read("What month were you born in?");

textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
        "was born in " + month + " and has the password " + password + ".");

In this image you can see the above code running in a Swing-based console.

Simple working Example of json.net in VB.net

In Place of using this

MsgBox(json.SelectToken("Venue").SelectToken("ID"))

You can also use

MsgBox(json.SelectToken("Venue.ID"))

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

After placing the jar file in desired location, you need to add the jar file by right click on

Project --> properties --> Java Build Path --> Libraries --> Add Jar.

This certificate has an invalid issuer Apple Push Services

You need to search the World from the top right search bar and delete the expired certificate. Make sure you selected Login and All items.

Enter image description here

How to remove all the occurrences of a char in c++ string

#include <string>
#include <algorithm>
std::string str = "YourString";
char chars[] = {'Y', 'S'};
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());

Will remove capital Y and S from str, leaving "ourtring".

Note that remove is an algorithm and needs the header <algorithm> included.

Reverting single file in SVN to a particular revision

If you just want the old file in your working copy:

svn up -r 147 myfile.py

If you want to rollback, see this "How to return to an older version of our code in subversion?".

How to post data using HttpClient?

Use UploadStringAsync method:

WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
    if (e.Error != null)
    {
        //handle your error here
    }
    else
    {
        //post was successful, so do what you need to do here
    }
};

webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);     

Find a value in DataTable

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

Return first N key:value pairs from dict

just add an answer using zip,

{k: d[k] for k, _ in zip(d, range(n))}

Find where python is installed (if it isn't default dir)

  1. First search for PYTHON IDLE from search bar
  2. Open the IDLE and use below commands.

    import sys print(sys.path)

  3. It will give you the path where the python.exe is installed. For eg: C:\Users\\...\python.exe

  4. Add the same path to system environment variable.

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

return collection.All(i => i == collection.First())) 
    ? collection.First() : otherValue;.

Or if you're worried about executing First() for each element (which could be a valid performance concern):

var first = collection.First();
return collection.All(i => i == first) ? first : otherValue;

Quick way to list all files in Amazon S3 bucket?

AWS CLI

Documentation for aws s3 ls

AWS have recently release their Command Line Tools. This works much like boto and can be installed using sudo easy_install awscli or sudo pip install awscli

Once you have installed, you can then simply run

aws s3 ls

Which will show you all of your available buckets

CreationTime Bucket
       ------------ ------
2013-07-11 17:08:50 mybucket
2013-07-24 14:55:44 mybucket2

You can then query a specific bucket for files.

Command:

aws s3 ls s3://mybucket

Output:

Bucket: mybucket
Prefix:

      LastWriteTime     Length Name
      -------------     ------ ----
                           PRE somePrefix/
2013-07-25 17:06:27         88 test.txt

This will show you all of your files.

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

For those using VPS / virtual hosting.

I was using a VPS, getting errors with MySQL not being able to write to /tmp, and everything looked correct. I had enough free space, enough free inodes, correct permissions. Turned out the problem was outside my VPS, it was the machine hosting the VPS that was full. I only had "virtual space" in my file system, but the machine in the background which hosted the VPS had no "physical space" left. I had to contact the VPS company any they fixed it.

If you think this might be your problem, you could test writing a larger file to /tmp (1GB):

dd if=/dev/zero of=/tmp/file.txt count=1024 bs=1048576 

I got a No space left on device error message, which was a giveaway that it was a disk/volume in the background that was full.

How do I find an element that contains specific text in Selenium WebDriver (Python)?

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(), 'YourTextHere')]")));
assertNotNull(driver.findElement(By.xpath("//*[contains(text(), 'YourTextHere')]")));
String yourButtonName = driver.findElement(By.xpath("//*[contains(text(), 'YourTextHere')]")).getAttribute("innerText");
assertTrue(yourButtonName.equalsIgnoreCase("YourTextHere"));

How do I "decompile" Java class files?

If you want to see how the Java compiler does certain things, you don't want decompilation, you want disassembly. Decompilation involves transforming the bytecode into Java source, meaning that a lot of low level information is lost, and if you're wondering about compiler optimization, this is probably the very information you're interested in.

Anyway, I happen to have written an open source Java disassembler. Unlike Javap, this works even on highly pathological classes, so you can see what obfuscation tools are doing to your classes as well. It can also do decompilation, though I wouldn't recommend it.

toBe(true) vs toBeTruthy() vs toBeTrue()

In javascript there are trues and truthys. When something is true it is obviously true or false. When something is truthy it may or may not be a boolean, but the "cast" value of is a boolean.

Examples.

true == true; // (true) true
1 == true; // (true) truthy
"hello" == true;  // (true) truthy
[1, 2, 3] == true; // (true) truthy
[] == false; // (true) truthy
false == false; // (true) true
0 == false; // (true) truthy
"" == false; // (true) truthy
undefined == false; // (true) truthy
null == false; // (true) truthy

This can make things simpler if you want to check if a string is set or an array has any values.

var users = [];

if(users) {
  // this array is populated. do something with the array
}

var name = "";

if(!name) {
  // you forgot to enter your name!
}

And as stated. expect(something).toBe(true) and expect(something).toBeTrue() is the same. But expect(something).toBeTruthy() is not the same as either of those.

Use CSS to automatically add 'required field' asterisk to form inputs

_x000D_
_x000D_
.asterisc {_x000D_
  display: block;_x000D_
  color: red;_x000D_
  margin: -19px 185px;_x000D_
}
_x000D_
<input style="width:200px">_x000D_
<span class="asterisc">*</span>
_x000D_
_x000D_
_x000D_

JavaScript post request like a form submit

If you have Prototype installed, you can tighten up the code to generate and submit the hidden form like this:

 var form = new Element('form',
                        {method: 'post', action: 'http://example.com/'});
 form.insert(new Element('input',
                         {name: 'q', value: 'a', type: 'hidden'}));
 $(document.body).insert(form);
 form.submit();

Remove HTML tags from string including &nbsp in C#

I've been using this function for a while. Removes pretty much any messy html you can throw at it and leaves the text intact.

        private static readonly Regex _tags_ = new Regex(@"<[^>]+?>", RegexOptions.Multiline | RegexOptions.Compiled);

        //add characters that are should not be removed to this regex
        private static readonly Regex _notOkCharacter_ = new Regex(@"[^\w;&#@.:/\\?=|%!() -]", RegexOptions.Compiled);

        public static String UnHtml(String html)
        {
            html = HttpUtility.UrlDecode(html);
            html = HttpUtility.HtmlDecode(html);

            html = RemoveTag(html, "<!--", "-->");
            html = RemoveTag(html, "<script", "</script>");
            html = RemoveTag(html, "<style", "</style>");

            //replace matches of these regexes with space
            html = _tags_.Replace(html, " ");
            html = _notOkCharacter_.Replace(html, " ");
            html = SingleSpacedTrim(html);

            return html;
        }

        private static String RemoveTag(String html, String startTag, String endTag)
        {
            Boolean bAgain;
            do
            {
                bAgain = false;
                Int32 startTagPos = html.IndexOf(startTag, 0, StringComparison.CurrentCultureIgnoreCase);
                if (startTagPos < 0)
                    continue;
                Int32 endTagPos = html.IndexOf(endTag, startTagPos + 1, StringComparison.CurrentCultureIgnoreCase);
                if (endTagPos <= startTagPos)
                    continue;
                html = html.Remove(startTagPos, endTagPos - startTagPos + endTag.Length);
                bAgain = true;
            } while (bAgain);
            return html;
        }

        private static String SingleSpacedTrim(String inString)
        {
            StringBuilder sb = new StringBuilder();
            Boolean inBlanks = false;
            foreach (Char c in inString)
            {
                switch (c)
                {
                    case '\r':
                    case '\n':
                    case '\t':
                    case ' ':
                        if (!inBlanks)
                        {
                            inBlanks = true;
                            sb.Append(' ');
                        }   
                        continue;
                    default:
                        inBlanks = false;
                        sb.Append(c);
                        break;
                }
            }
            return sb.ToString().Trim();
        }

Changing precision of numeric column in Oracle

If the table is compressed this will work:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES move nocompress;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

alter table EVAPP_FEES compress;

First Heroku deploy failed `error code=H10`

I was deploying python Django framework when I got this error because I forget to put my app name web: gunicorn plaindjango.wsgi:application --log-file - instead of plaindjango

How to check if element has any children in Javascript?

As slashnick & bobince mention, hasChildNodes() will return true for whitespace (text nodes). However, I didn't want this behaviour, and this worked for me :)

element.getElementsByTagName('*').length > 0

Edit: for the same functionality, this is a better solution:

 element.children.length > 0

children[] is a subset of childNodes[], containing elements only.

Compatibility

How to get the IP address of the server on which my C# application is running on?

If you can't rely on getting your IP address from a DNS server (which has happened to me), you can use the following approach:

The System.Net.NetworkInformation namespace contains a NetworkInterface class, which has a static GetAllNetworkInterfaces method.

This method will return all "network interfaces" on your machine, and there are generally quite a few, even if you only have a wireless adapter and/or an ethernet adapter hardware installed on your machine. All of these network interfaces have valid IP addresses for your local machine, although you probably only want one.

If you're looking for one IP address, then you'll need to filter the list down until you can identify the right address. You will probably need to do some experimentation, but I had success with the following approach:

  • Filter out any NetworkInterfaces that are inactive by checking for OperationalStatus == OperationalStatus.Up. This will exclude your physical ethernet adapter, for instance, if you don't have a network cable plugged in.

For each NetworkInterface, you can get an IPInterfaceProperties object using the GetIPProperties method, and from an IPInterfaceProperties object you can access the UnicastAddresses property for a list of UnicastIPAddressInformation objects.

  • Filter out non-preferred unicast addresses by checking for DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
  • Filter out "virtual" addresses by checking for AddressPreferredLifetime != UInt32.MaxValue.

At this point I take the address of the first (if any) unicast address that matches all of these filters.

EDIT:

[revised code on May 16, 2018 to include the conditions mentioned in the text above for duplicate address detection state and preferred lifetime]

The sample below demonstrates filtering based on operational status, address family, excluding the loopback address (127.0.0.1), duplicate address detection state, and preferred lifetime.

static IEnumerable<IPAddress> GetLocalIpAddresses()
{
    // Get the list of network interfaces for the local computer.
    var adapters = NetworkInterface.GetAllNetworkInterfaces();

    // Return the list of local IPv4 addresses excluding the local
    // host, disconnected, and virtual addresses.
    return (from adapter in adapters
            let properties = adapter.GetIPProperties()
            from address in properties.UnicastAddresses
            where adapter.OperationalStatus == OperationalStatus.Up &&
                  address.Address.AddressFamily == AddressFamily.InterNetwork &&
                  !address.Equals(IPAddress.Loopback) &&
                  address.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred &&
                  address.AddressPreferredLifetime != UInt32.MaxValue
            select address.Address);
}

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

XPath to select multiple tags

Why not a/b/(c|d|e)? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work. abc.xml is the doc described by OP.

(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
    #<XdmNode <d>D1</d>>
    #<XdmNode <e>E1</e>>
    #<XdmNode <c>C2</c>>
    #<XdmNode <d>D2</d>>
    #<XdmNode <e>E1</e>>)

How Big can a Python List Get?

As the Python documentation says:

sys.maxsize

The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.

In my computer (Linux x86_64):

>>> import sys
>>> print sys.maxsize
9223372036854775807

How can I exit from a javascript function?

I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..

function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
  return Browser.msgBox("something");
  }
}

This way you not only exit the function, but show a message saying why it stopped. Hope it helps.

Something like 'contains any' for Java set?

Use retainAll() in the Set interface. This method provides an intersection of elements common in both sets. See the API docs for more information.

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Your second DELETE query was nearly correct. Just be sure to put the table name (or an alias) between DELETE and FROM to specify which table you are deleting from. This is simpler than using a nested SELECT statement like in the other answers.

Corrected Query (option 1: using full table name):

DELETE tableA
FROM tableA
INNER JOIN tableB u on (u.qlabel = tableA.entityrole AND u.fieldnum = tableA.fieldnum) 
WHERE (LENGTH(tableA.memotext) NOT IN (8,9,10)
OR tableA.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')

Corrected Query (option 2: using an alias):

DELETE q
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')

More examples here:
How to Delete using INNER JOIN with SQL Server?

Creating an empty file in C#

You can chain methods off the returned object, so you can immediately close the file you just opened in a single statement.

File.Open("filename", FileMode.Create).Close();

How to create custom spinner like border around the spinner with down triangle on the right side?

It's super easy you can just add this to your Adapter -> getDropDownView

getDropDownView:

convertView.setBackground(getContext().getResources().getDrawable(R.drawable.bg_spinner_dropdown));

bg_spinner_dropdown:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/white" />
    <corners
        android:bottomLeftRadius=enter code here"25dp"
        android:bottomRightRadius="25dp"
        android:topLeftRadius="25dp"
        android:topRightRadius="25dp" />
</shape>

How to embed images in html email

You have to encode your email as multipart mime and then you can attach emails as attachments basically. You reference them by cid in the email.

Alternatively you could not attach them to the email and use URLs directly but most mail programs will block this as spammers use the trick to detect the liveness of email addresses.

You don't say what language but here is one example.

Can't install any packages in Node.js using "npm install"

npm set registry http://85.10.209.91/

(this proxy fetches the original data from registry.npmjs.org and manipulates the tarball urls to fix the tarball file structure issue).

The other solutions seem to have outdated versions.

Is it possible to open a Windows Explorer window from PowerShell?

This is the only thing that fit my unique constraints of wanting the folder to open as a Quizo Tab in any existing Explorer window.

$objShell = New-Object -ComObject "Shell.Application"
$objShell.Explore("path")

How to generate a random integer number from within a range

While Ryan is correct, the solution can be much simpler based on what is known about the source of the randomness. To re-state the problem:

  • There is a source of randomness, outputting integer numbers in range [0, MAX) with uniform distribution.
  • The goal is to produce uniformly distributed random integer numbers in range [rmin, rmax] where 0 <= rmin < rmax < MAX.

In my experience, if the number of bins (or "boxes") is significantly smaller than the range of the original numbers, and the original source is cryptographically strong - there is no need to go through all that rigamarole, and simple modulo division would suffice (like output = rnd.next() % (rmax+1), if rmin == 0), and produce random numbers that are distributed uniformly "enough", and without any loss of speed. The key factor is the randomness source (i.e., kids, don't try this at home with rand()).

Here's an example/proof of how it works in practice. I wanted to generate random numbers from 1 to 22, having a cryptographically strong source that produced random bytes (based on Intel RDRAND). The results are:

Rnd distribution test (22 boxes, numbers of entries in each box):     
 1: 409443    4.55%
 2: 408736    4.54%
 3: 408557    4.54%
 4: 409125    4.55%
 5: 408812    4.54%
 6: 409418    4.55%
 7: 408365    4.54%
 8: 407992    4.53%
 9: 409262    4.55%
10: 408112    4.53%
11: 409995    4.56%
12: 409810    4.55%
13: 409638    4.55%
14: 408905    4.54%
15: 408484    4.54%
16: 408211    4.54%
17: 409773    4.55%
18: 409597    4.55%
19: 409727    4.55%
20: 409062    4.55%
21: 409634    4.55%
22: 409342    4.55%   
total: 100.00%

This is as close to uniform as I need for my purpose (fair dice throw, generating cryptographically strong codebooks for WWII cipher machines such as http://users.telenet.be/d.rijmenants/en/kl-7sim.htm, etc). The output does not show any appreciable bias.

Here's the source of cryptographically strong (true) random number generator: Intel Digital Random Number Generator and a sample code that produces 64-bit (unsigned) random numbers.

int rdrand64_step(unsigned long long int *therand)
{
  unsigned long long int foo;
  int cf_error_status;

  asm("rdrand %%rax; \
        mov $1,%%edx; \
        cmovae %%rax,%%rdx; \
        mov %%edx,%1; \
        mov %%rax, %0;":"=r"(foo),"=r"(cf_error_status)::"%rax","%rdx");
        *therand = foo;
  return cf_error_status;
}

I compiled it on Mac OS X with clang-6.0.1 (straight), and with gcc-4.8.3 using "-Wa,q" flag (because GAS does not support these new instructions).

How to tell Maven to disregard SSL errors (and trusting all certs)?

Create a folder ${USER_HOME}/.mvn and put a file called maven.config in it.

The content should be:

-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true

Hope this helps.

How to use bootstrap-theme.css with bootstrap 3?

I know this post is kinda old but...

  As 'witttness' pointed out.

About Your Own Custom Theme You might choose to modify bootstrap-theme.css when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.

  I see it as Bootstrap has seen over the years that everyone wants something a bit different than the core styles. While you could modify bootstrap.css it might break things and it could make updating to a newer version a real pain and time consuming. Downloading from a 'theme' site means you have to wait on if that creator updates that theme, big if sometimes, right?

  Some build their own 'custom.css' file and that's ok, but if you use 'bootstrap-theme.css' a lot of stuff is already built and this allows you to roll your own theme faster 'without' disrupting the core of bootstrap.css. I for one don't like the 3D buttons and gradients most of the time, so change them using bootstrap-theme.css. Add margins or padding, change the radius to your buttons, and so on...

How to create a folder with name as current date in batch (.bat) files

G:

cd G:/app/

mkdir %date:~7,2%%date:~-10,2%%date:~-4,4% 

cd %date:~7,2%%date:~-10,2%%date:~-4,4% 

sqlplus sys/sys as sysdba @c:/new

How do I put hint in a asp:textbox

The placeholder attribute

You're looking for the placeholder attribute. Use it like any other attribute inside your ASP.net control:

<asp:textbox id="txtWithHint" placeholder="hint" runat="server"/>

Don't bother about your IDE (i.e. Visual Studio) maybe not knowing the attribute. Attributes which are not registered with ASP.net are passed through and rendered as is. So the above code (basically) renders to:

<input type="text" placeholder="hint"/>

Using placeholder in resources

A fine way of applying the hint to the control is using resources. This way you may have localized hints. Let's say you have an index.aspx file, your App_LocalResources/index.aspx.resx file contains

<data name="WithHint.placeholder">
    <value>hint</value>
</data>

and your control looks like

<asp:textbox id="txtWithHint" meta:resourcekey="WithHint" runat="server"/>

the rendered result will look the same as the one in the chapter above.

Add attribute in code behind

Like any other attribute you can add the placeholder to the AttributeCollection:

txtWithHint.Attributes.Add("placeholder", "hint");

Matching exact string with JavaScript

var data =   {"values": [
    {"name":0,"value":0.12791263050161572},
    {"name":1,"value":0.13158780927382124}
]};

//JSON to string conversion
var a = JSON.stringify(data);
// replace all name with "x"- global matching
var t = a.replace(/name/g,"x"); 
// replace exactly the value rather than all values
var d = t.replace(/"value"/g, '"y"');
// String to JSON conversion
var data = JSON.parse(d);

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

import java.util.Scanner;
class TestClass {
    public static void main(String args[]) throws Exception {
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (Character.isUpperCase(ch[i])) {
                ch[i] = Character.toLowerCase(ch[i]);
            } else {
                ch[i] = Character.toUpperCase(ch[i]);
            }
        }
        System.out.println(ch);
    }
}

Pinging servers in Python

I ended up finding this question regarding a similar scenario. I tried out pyping but the example given by Naveen didn't work for me in Windows under Python 2.7.

An example that worked for me is:

import pyping

response = pyping.send('Your IP')

if response['ret_code'] == 0:
    print("reachable")
else:
    print("unreachable")