Programs & Examples On #Fisheye

A Fisheye-effect is a distortion of images, such as that provided by a Fisheye lens, by which a wide-angle effect is achieved. If you are looking for information on Atlassian's Fisheye source code browser web app, please see atlassian-fisheye.

How to get coordinates of an svg element?

You can use the function getBBox() to get the bounding box for the path. This will give you the position and size of the tightest rectangle that could contain the rendered path.

An advantage of using this method over reading the x and y values is that it will work with all graphical objects. There are more objects than paths that do not have x and y, for example circles that have cx and cy instead.

SVN Repository Search

I do like TRAC - this plugin might be helpful for your task: http://trac-hacks.org/wiki/RepoSearchPlugin

Hidden Columns in jqGrid

Try to use edithidden: true and also do

editoptions: { dataInit: function(element) { $(element).attr("readonly", "readonly"); } }

Or see jqGrid wiki for custom editing, you can setup any input type, even label I think.

How to fill Matrix with zeros in OpenCV?

How to fill Matrix with zeros in OpenCV?

To fill a pre-existing Mat object with zeros, you can use Mat::zeros()

Mat m1 = ...;
m1 = Mat::zeros(1, 1, CV_64F);

To intialize a Mat so that it contains only zeros, you can pass a scalar with value 0 to the constructor:

Mat m1 = Mat(1,1, CV_64F, 0.0);
//                        ^^^^double literal

The reason your version failed is that passing 0 as fourth argument matches the overload taking a void* better than the one taking a scalar.

How can I round down a number in Javascript?

Round towards negative infinity - Math.floor()

+3.5 => +3.0
-3.5 => -4.0

Round towards zero can be done using Math.trunc(). Older browsers do not support this function. If you need to support these, you can use Math.ceil() for negative numbers and Math.floor() for positive numbers.

+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

Try to delete all dirs in /usr/share/maven-repo - of course then maven will die so you must re-install and try again. In my case re-install from maven ver.3. to maven2 with deleting all repositories helped.

I tried by deleting all from .m2 but that didn't help.

Disable Transaction Log

You can't do without transaction logs in SQL Server, under any circumstances. The engine simply won't function.

You CAN set your recovery model to SIMPLE on your dev machines - that will prevent transaction log bloating when tran log backups aren't done.

ALTER DATABASE MyDB SET RECOVERY SIMPLE;

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

For anyone landing here who is trying to upgrade from MVC 4 to MVC5, I was able to resolve this issue by following the instructions at http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2.

I also had to install the "Microsoft.AspNet.WebApi.WebHost" package from nuget. But that's it.

Oh, and I had to create this appSetting: <add key="owin:AutomaticAppStartup" value="false" />

:)

Select count(*) from result query

You can wrap your query in another SELECT:

select count(*)
from
(
  select count(SID) tot  -- add alias
  from Test 
  where Date = '2012-12-10' 
  group by SID
) src;  -- add alias

See SQL Fiddle with Demo

In order for it to work, the count(SID) need a column alias and you have to provide an alias to the subquery itself.

How can I get the domain name of my site within a Django template?

I think what you want is to have access to the request context, see RequestContext.

What is simplest way to read a file into String?

Sadly, no.

I agree that such frequent operation should have easier implementation than copying of input line by line in loop, but you'll have to either write helper method or use external library.

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

How can jQuery deferred be used?

Another example using Deferreds to implement a cache for any kind of computation (typically some performance-intensive or long-running tasks):

var ResultsCache = function(computationFunction, cacheKeyGenerator) {
    this._cache = {};
    this._computationFunction = computationFunction;
    if (cacheKeyGenerator)
        this._cacheKeyGenerator = cacheKeyGenerator;
};

ResultsCache.prototype.compute = function() {
    // try to retrieve computation from cache
    var cacheKey = this._cacheKeyGenerator.apply(this, arguments);
    var promise = this._cache[cacheKey];

    // if not yet cached: start computation and store promise in cache 
    if (!promise) {
        var deferred = $.Deferred();
        promise = deferred.promise();
        this._cache[cacheKey] = promise;

        // perform the computation
        var args = Array.prototype.slice.call(arguments);
        args.push(deferred.resolve);
        this._computationFunction.apply(null, args);
    }

    return promise;
};

// Default cache key generator (works with Booleans, Strings, Numbers and Dates)
// You will need to create your own key generator if you work with Arrays etc.
ResultsCache.prototype._cacheKeyGenerator = function(args) {
    return Array.prototype.slice.call(arguments).join("|");
};

Here is an example of using this class to perform some (simulated heavy) calculation:

// The addingMachine will add two numbers
var addingMachine = new ResultsCache(function(a, b, resultHandler) {
    console.log("Performing computation: adding " + a + " and " + b);
    // simulate rather long calculation time by using a 1s timeout
    setTimeout(function() {
        var result = a + b;
        resultHandler(result);
    }, 1000);
});

addingMachine.compute(2, 4).then(function(result) {
    console.log("result: " + result);
});

addingMachine.compute(1, 1).then(function(result) {
    console.log("result: " + result);
});

// cached result will be used
addingMachine.compute(2, 4).then(function(result) {
    console.log("result: " + result);
});

The same underlying cache could be used to cache Ajax requests:

var ajaxCache = new ResultsCache(function(id, resultHandler) {
    console.log("Performing Ajax request for id '" + id + "'");
    $.getJSON('http://jsfiddle.net/echo/jsonp/?callback=?', {value: id}, function(data) {
        resultHandler(data.value);
    });
});

ajaxCache.compute("anID").then(function(result) {
    console.log("result: " + result);
});

ajaxCache.compute("anotherID").then(function(result) {
    console.log("result: " + result);
});

// cached result will be used
ajaxCache.compute("anID").then(function(result) {
    console.log("result: " + result);
});

You can play with the above code in this jsFiddle.

How to read a .xlsx file using the pandas Library in iPython?

Instead of using a sheet name, in case you don't know or can't open the excel file to check in ubuntu (in my case, Python 3.6.7, ubuntu 18.04), I use the parameter index_col (index_col=0 for the first sheet)

import pandas as pd
file_name = 'some_data_file.xlsx' 
df = pd.read_excel(file_name, index_col=0)
print(df.head()) # print the first 5 rows

Uses of content-disposition in an HTTP response header

For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition

Basic usage:

var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "myFile.txt";
cd.ModificationDate = DateTime.UtcNow;
cd.Size = 100;
Response.AppendHeader("content-disposition", cd.ToString());

Arduino IDE can't find ESP8266WiFi.h file

For those who are having trouble with fatal error: ESP8266WiFi.h: No such file or directory, you can install the package manually.

  1. Download the Arduino ESP8266 core from here https://github.com/esp8266/Arduino
  2. Go into library from the downloaded core and grab ESP8266WiFi.
  3. Drag that into your local Arduino/library folder. This can be found by going into preferences and looking at your Sketchbook location

You may still need to have the http://arduino.esp8266.com/stable/package_esp8266com_index.json package installed beforehand, however.

Edit: That wasn't the full issue, you need to make sure you have the correct ESP8266 Board selected before compiling.

Hope this helps others.

Make footer stick to bottom of page correctly

I would like to share how I solved mine using Javascript function that is called on page load. This solution positions the footer at the bottom of the screen when the height of the page content is less than the height of the screen.

_x000D_
_x000D_
function fix_layout(){_x000D_
  //increase content div length by uncommenting below line_x000D_
  //expandContent();_x000D_
  _x000D_
    var wraph = document.getElementById('wrapper').offsetHeight;_x000D_
    if(wraph<window.innerHeight){ //if content is less than screenheight_x000D_
        var headh   = document.getElementById('header').offsetHeight;_x000D_
        var conth   = document.getElementById('content').offsetHeight;_x000D_
        var footh   = document.getElementById('footer').offsetHeight;_x000D_
        //var foottop = window.innerHeight - (headh + conth + footh);_x000D_
        var foottop = window.innerHeight - (footh);_x000D_
        $("#footer").css({top:foottop+'px'});_x000D_
    }_x000D_
}_x000D_
_x000D_
function expandContent(){_x000D_
  $('#content').append('<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at ante. Mauris eleifend, quam a vulputate dictum, massa quam dapibus leo, eget vulputate orci purus ut lorem. In fringilla mi in ligula. Pellentesque aliquam quam vel dolor. Nunc adipiscing. Sed quam odio, tempus ac, aliquam molestie, varius ac, tellus. Vestibulum ut nulla aliquam risus rutrum interdum. Pellentesque lorem. Curabitur sit amet erat quis risus feugiat viverra. Pellentesque augue justo, sagittis et, lacinia at, venenatis non, arcu. Nunc nec libero. In cursus dictum risus. Etiam tristique nisl a nulla. Ut a orci. Curabitur dolor nunc, egestas at, accumsan at, malesuada nec, magna.</p>'+_x000D_
_x000D_
'<p>Nulla facilisi. Nunc volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut sit amet orci vel mauris blandit vehicula. Nullam quis enim. Integer dignissim viverra velit. Curabitur in odio. In hac habitasse platea dictumst. Ut consequat, tellus eu volutpat varius, justo orci elementum dolor, sed imperdiet nulla tellus ut diam. Vestibulum ipsum ante, malesuada quis, tempus ac, placerat sit amet, elit.</p>'+_x000D_
_x000D_
'<p>Sed eget turpis a pede tempor malesuada. Vivamus quis mi at leo pulvinar hendrerit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque aliquet lacus vitae pede. Nullam mollis dolor ac nisi. Phasellus sit amet urna. Praesent pellentesque sapien sed lacus. Donec lacinia odio in odio. In sit amet elit. Maecenas gravida interdum urna. Integer pretium, arcu vitae imperdiet facilisis, elit tellus tempor nisi, vel feugiat ante velit sit amet mauris. Vivamus arcu. Integer pharetra magna ac lacus. Aliquam vitae sapien in nibh vehicula auctor. Suspendisse leo mauris, pulvinar sed, tempor et, consequat ac, lacus. Proin velit. Nulla semper lobortis mauris. Duis urna erat, ornare et, imperdiet eu, suscipit sit amet, massa. Nulla nulla nisi, pellentesque at, egestas quis, fringilla eu, diam.</p>'+_x000D_
_x000D_
'<p>Donec semper, sem nec tristique tempus, justo neque commodo nisl, ut gravida sem tellus suscipit nunc. Aliquam erat volutpat. Ut tincidunt pretium elit. Aliquam pulvinar. Nulla cursus. Suspendisse potenti. Etiam condimentum hendrerit felis. Duis iaculis aliquam enim. Donec dignissim augue vitae orci. Curabitur luctus felis a metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In varius neque at enim. Suspendisse massa nulla, viverra in, bibendum vitae, tempor quis, lorem.</p>'+_x000D_
_x000D_
'<p>Donec dapibus orci sit amet elit. Maecenas rutrum ultrices lectus. Aliquam suscipit, lacus a iaculis adipiscing, eros orci pellentesque nisl, non pharetra dolor urna nec dolor. Integer cursus dolor vel magna. Integer ultrices feugiat sem. Proin nec nibh. Duis eu dui quis nunc sagittis lobortis. Fusce pharetra, enim ut sodales luctus, lectus arcu rhoncus purus, in fringilla augue elit vel lacus. In hac habitasse platea dictumst. Aliquam erat volutpat. Fusce iaculis elit id tellus. Ut accumsan malesuada turpis. Suspendisse potenti. Vestibulum lacus augue, lobortis mattis, laoreet in, varius at, nisi. Nunc gravida. Phasellus faucibus. In hac habitasse platea dictumst. Integer tempor lacus eget lectus. Praesent fringilla augue fringilla dui.</p>');_x000D_
}
_x000D_
/*sample CSS*/_x000D_
body{ background: black; margin: 0; }_x000D_
#header{ background: grey; }_x000D_
#content{background: yellow; }_x000D_
#footer{ background: red; position: absolute; }_x000D_
_x000D_
#header, #content, #footer{ display: inline-block; width: 100vw; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body onload="fix_layout()">_x000D_
        <div id="wrapper">_x000D_
            <div id="header" class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
                [some header elements here]_x000D_
            </div>_x000D_
            <div id="content" class="container">_x000D_
              [some content elements here]_x000D_
              _x000D_
              _x000D_
            </div>_x000D_
            <div id="footer" class="footer">_x000D_
                [some footer elements here]_x000D_
            </div>_x000D_
        </div>_x000D_
    </body>
_x000D_
_x000D_
_x000D_

Hope that helps.

Unresolved Import Issues with PyDev and Eclipse

There are two ways of solving this issue:

  • Delete the Python interpreter from "Python interpreters" and add it again.
  • Or just add the folder with the libraries in the interpreter you are using in your project, in my case I was using "bottle" and the folder I added was "c:\Python33\Lib\site-packages\bottle-0.11.6-py3.3.egg"

Now I don't see the error anymore, and the code completion feature works as well with "bottle".

How can I use UserDefaults in Swift?

ref: NSUserdefault objectTypes

Swift 3 and above

Store

UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key")  //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject

Retrieve

 UserDefaults.standard.bool(forKey: "Key")
 UserDefaults.standard.integer(forKey: "Key")
 UserDefaults.standard.string(forKey: "Key")

Remove

 UserDefaults.standard.removeObject(forKey: "Key")

Remove all Keys

 if let appDomain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: appDomain)
 }

Swift 2 and below

Store

NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "yourkey")
NSUserDefaults.standardUserDefaults().synchronize()

Retrieve

  var returnValue: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("yourkey") as? [NSString]

Remove

 NSUserDefaults.standardUserDefaults().removeObjectForKey("yourkey")


Register

registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them.

Default values from Defaults Configuration Files will automatically be registered.

for example detect the app from launch , create the struct for save launch

struct DetectLaunch {
static let keyforLaunch = "validateFirstlunch"
static var isFirst: Bool {
    get {
        return UserDefaults.standard.bool(forKey: keyforLaunch)
    }
    set {
        UserDefaults.standard.set(newValue, forKey: keyforLaunch)
    }
}
}

Register default values on app launch:

UserDefaults.standard.register(defaults: [
        DetectLaunch.isFirst: true
    ])

remove the value on app termination:

func applicationWillTerminate(_ application: UIApplication) {
    DetectLaunch.isFirst = false

}

and check the condition as

if DetectLaunch.isFirst {
  // app launched from first
}

UserDefaults suite name

another one property suite name, mostly its used for App Groups concept, the example scenario I taken from here :

The use case is that I want to separate my UserDefaults (different business logic may require Userdefaults to be grouped separately) by an identifier just like Android's SharedPreferences. For example, when a user in my app clicks on logout button, I would want to clear his account related defaults but not location of the the device.

let user = UserDefaults(suiteName:"User")

use of userDefaults synchronize, the detail info has added in the duplicate answer.

jQuery convert line breaks to br (nl2br equivalent)

Put this in your code (preferably in a general js functions library):

String.prototype.nl2br = function()
{
    return this.replace(/\n/g, "<br />");
}

Usage:

var myString = "test\ntest2";

myString.nl2br();

creating a string prototype function allows you to use this on any string.

How to scale an Image in ImageView to keep the aspect ratio

This worked for me:

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="39dip"
android:scaleType="centerCrop"
android:adjustViewBounds ="true"

How to form tuple column from two columns in Pandas

I'd like to add df.values.tolist(). (as long as you don't mind to get a column of lists rather than tuples)

import pandas as pd
import numpy as np

size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)}) 

%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

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

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

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

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

How can one change the timestamp of an old commit in Git?

If you want to perform the accepted answer (https://stackoverflow.com/a/454750/72809) in standard Windows command line, you need the following command:

git filter-branch -f --env-filter "if [ $GIT_COMMIT = 578e6a450ff5318981367fe1f6f2390ce60ee045 ]; then export GIT_AUTHOR_DATE='2009-10-16T16:00+03:00'; export GIT_COMMITTER_DATE=$GIT_AUTHOR_DATE; fi"

Notes:

  • It may be possible to split the command over multiple lines (Windows supports line splitting with the carret symbol ^), but I didn't succeed.
  • You can write ISO dates, saving a lot of time finding the right day-of-week and general frustration over the order of elements.
  • If you want the Author and Committer date to be the same, you can just reference the previously set variable.

Many thanks go to a blog post by Colin Svingen. Even though his code didn't work for me, it helped me find the correct solution.

How to set environment variables from within package.json?

Because I often find myself working with multiple environment variables, I find it useful to keep them in a separate .env file (make sure to ignore this from your source control). Then (in Linux) prepend export $(cat .env | xargs) && in your script command before starting your app.

Example .env file:

VAR_A=Hello World
VAR_B=format the .env file like this with new vars separated by a line break

Example index.js:

console.log('Test', process.env.VAR_A, process.env.VAR_B);

Example package.json:

{
  ...
  "scripts": {
    "start": "node index.js",

    "env-linux": "export $(cat .env | xargs) && env",
    "start-linux": "export $(cat .env | xargs) && npm start",

    "env-windows": "(for /F \"tokens=*\" %i in (.env) do set %i)",
    "start-windows": "(for /F \"tokens=*\" %i in (.env) do set %i) && npm start",

  }
  ...
}

Unfortunately I can't seem to set the environment variables by calling a script from a script -- like "start-windows": "npm run env-windows && npm start" -- so there is some redundancy in the scripts.

For a test you can see the env variables by running npm run env-linux or npm run env-windows, and test that they make it into your app by running npm run start-linux or npm run start-windows.

Styling the arrow on bootstrap tooltips

If you want to style only the colors of the tooltips do as follow:

.tooltip-inner { background-color: #000; color: #fff; }
.tooltip.top .tooltip-arrow { border-top-color: #000; }
.tooltip.right .tooltip-arrow { border-right-color: #000; }
.tooltip.bottom .tooltip-arrow { border-bottom-color: #000; }
.tooltip.left .tooltip-arrow { border-left-color: #000; }

Circle-Rectangle collision detection (intersection)

I've a method which avoids the expensive pythagoras if not necessary - ie. when bounding boxes of the rectangle and the circle do not intersect.

And it'll work for non-euclidean too:

class Circle {
 // create the bounding box of the circle only once
 BBox bbox;

 public boolean intersect(BBox b) {
    // test top intersect
    if (lat > b.maxLat) {
        if (lon < b.minLon)
            return normDist(b.maxLat, b.minLon) <= normedDist;
        if (lon > b.maxLon)
            return normDist(b.maxLat, b.maxLon) <= normedDist;
        return b.maxLat - bbox.minLat > 0;
    }

    // test bottom intersect
    if (lat < b.minLat) {
        if (lon < b.minLon)
            return normDist(b.minLat, b.minLon) <= normedDist;
        if (lon > b.maxLon)
            return normDist(b.minLat, b.maxLon) <= normedDist;
        return bbox.maxLat - b.minLat > 0;
    }

    // test middle intersect
    if (lon < b.minLon)
        return bbox.maxLon - b.minLon > 0;
    if (lon > b.maxLon)
        return b.maxLon - bbox.minLon > 0;
    return true;
  }
}
  • minLat,maxLat can be replaced with minY,maxY and the same for minLon, maxLon: replace it with minX, maxX
  • normDist ist just a bit faster method then the full distance calculation. E.g. without the square-root in euclidean space (or without a lot of other stuff for haversine): dLat=(lat-circleY); dLon=(lon-circleX); normed=dLat*dLat+dLon*dLon. Of course if you use that normDist method you'll need to do create a normedDist = dist*dist; for the circle

See the full BBox and Circle code of my GraphHopper project.

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

We are using the cordova-custom-config plugin to manage our Android configuration. In this case the solution was to add a new custom-preference to our config.xml:

    <platform name="android">

        <preference name="orientation" value="portrait" />

        <!-- ... other settings ... -->

        <!-- Allow http connections (by default Android only allows https) -->
        <!-- See: https://stackoverflow.com/questions/54752716/ -->
        <custom-preference
            name="android-manifest/application/@android:usesCleartextTraffic"
            value="true" />

    </platform>

Does anybody know how to do this only for development builds? I would be happy for release builds to leave this setting false.

(I see the iOS configuration offers buildType="debug" for that, but I'm not sure if this applies to Android configuration.)

Jackson: how to prevent field serialization

One should ask why you would want a public getter method for the password. Hibernate, or any other ORM framework, will do with a private getter method. For checking whether the password is correct, you can use

public boolean checkPassword(String password){
  return this.password.equals(anyHashingMethod(password));
}

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

SQL Query Where Date = Today Minus 7 Days

You can use the CURDATE() and DATE_SUB() functions to achieve this:

SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()    
GROUP BY URLx
ORDER BY Count DESC; 

Last Key in Python Dictionary

yes there is : len(data)-1.

For the first element it´s : 0

Spring Rest POST Json RequestBody Content type not supported

specify @JsonProperty in entity class constructor like this.

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

 @JsonCreator
 public Location(@JsonProperty("sl_no") Long sl_no, 
          @JsonProperty("location")String location,
          @JsonProperty("location_type") String 
          location_type,@JsonProperty("store_sl_no")Long store_sl_no) {
  this.sl_no = sl_no;
  this.location = location;
  this.location_type = location_type;
  this.store_sl_no = store_sl_no;
 } 
.......
.......
.......

Make anchor link go some pixels above where it's linked to

i was facing the similar issue and i resolved by using following code

$(document).on('click', 'a.page-scroll', function(event) {
        var $anchor = $(this);
        var desiredHeight = $(window).height() - 577;
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - desiredHeight
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });

How to create a circle icon button in Flutter?

RawMaterialButton(
  onPressed: () {},
  constraints: BoxConstraints(),
  elevation: 2.0,
  fillColor: Colors.white,
  child: Icon(
    Icons.pause,
    size: 35.0,
  ),
  padding: EdgeInsets.all(15.0),
  shape: CircleBorder(),
)

note down constraints: BoxConstraints(), it's for not allowing padding in left.

Happy fluttering!!

jquery change button color onclick

$('input[type="submit"]').click(function(){
$(this).css('color','red');
});

Use class, Demo:- http://jsfiddle.net/BX6Df/

   $('input[type="submit"]').click(function(){
          $(this).addClass('red');
});

if you want to toggle the color each click, you can try this:- http://jsfiddle.net/SMNks/

$('input[type="submit"]').click(function(){
  $(this).toggleClass('red');
});


.red
{
    background-color:red;
}

Updated answer for your comment.

http://jsfiddle.net/H2Xhw/

$('input[type="submit"]').click(function(){
    $('input[type="submit"].red').removeClass('red')
        $(this).addClass('red');
});

Focus Input Box On Load

$(document).ready(function() {
    $('#id').focus();
});

Search for string within text column in MySQL

Using like might take longer time so use full_text_search:

SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')

if checkbox is checked, do this

Probably you can go with this code to take actions as the checkbox is checked or unchecked.

$('#chk').on('click',function(){
    if(this.checked==true){
      alert('yes');
    }else{
      alert('no');
    }
});

How link to any local file with markdown syntax?

After messing around with @BringBackCommodore64 answer I figured it out

[link](file:///d:/absolute.md)    # absolute filesystem path
[link](./relative1.md)            # relative to opened file
[link](/relativeToProject.md)     # relative to opened project

All of them tested in Visual Studio Code and working,

Note: The absolute path works in editor but doesn't work in markdown preview mode!

ListView item background via custom selector

I'm not sure how to achieve your desired effect through the selector itself -- after all, by definition, there is one selector for the whole list.

However, you can get control on selection changes and draw whatever you want. In this sample project, I make the selector transparent and draw a bar on the selected item.

Copy a file from one folder to another using vbscripting

Please find the below code:

If ComboBox21.Value = "Delimited file" Then
    'Const txtFldrPath As String = "C:\Users\513090.CTS\Desktop\MACRO"      'Change to folder path containing text files
    Dim myValue2 As String
    myValue2 = ComboBox22.Value
    Dim txtFldrPath As Variant
    txtFldrPath = InputBox("Give the file path")
    'Dim CurrentFile As String: CurrentFile = Dir(txtFldrPath & "\" & "LL.txt")
    Dim strLine() As String
    Dim LineIndex As Long
    Dim myValue As Variant
    On Error GoTo Errhandler
    myValue = InputBox("Give the DELIMITER")

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    While txtFldrPath <> vbNullString
        LineIndex = 0
        Close #1
        'Open txtFldrPath & "\" & CurrentFile For Input As #1
        Open txtFldrPath For Input As #1
        While Not EOF(1)
            LineIndex = LineIndex + 1
            ReDim Preserve strLine(1 To LineIndex)
            Line Input #1, strLine(LineIndex)
        Wend
        Close #1

        With ActiveWorkbook.Sheets(myValue2).Range("A1").Resize(LineIndex, 1)
            .Value = WorksheetFunction.Transpose(strLine)
            .TextToColumns Other:=True, OtherChar:=myValue
        End With

        'ActiveSheet.UsedRange.EntireColumn.AutoFit
        'ActiveSheet.Copy
        'ActiveWorkbook.SaveAs xlsFldrPath & "\" & Replace(CurrentFile, ".txt", ".xls"), xlNormal
        'ActiveWorkbook.Close False
       ' ActiveSheet.UsedRange.ClearContents

        CurrentFile = Dir
    Wend
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

End If

Checking session if empty or not

You should first check if Session["emp_num"] exists in the session.

You can ask the session object if its indexer has the emp_num value or use string.IsNullOrEmpty(Session["emp_num"])

Determine Whether Two Date Ranges Overlap

the simplest

The simplest way is to use a well-engineered dedicated library for date-time work.

someInterval.overlaps( anotherInterval )

java.time & ThreeTen-Extra

The best in the business is the java.time framework built into Java 8 and later. Add to that the ThreeTen-Extra project that supplements java.time with additional classes, specifically the Interval class we need here.

As for the language-agnostic tag on this Question, the source code for both projects is available for use in other languages (mind their licenses).

Interval

The org.threeten.extra.Interval class is handy, but requires date-time moments (java.time.Instant objects) rather than date-only values. So we proceed by using the first moment of the day in UTC to represent the date.

Instant start = Instant.parse( "2016-01-01T00:00:00Z" );
Instant stop = Instant.parse( "2016-02-01T00:00:00Z" );

Create an Interval to represent that span of time.

Interval interval_A = Interval.of( start , stop );

We can also define an Interval with a starting moment plus a Duration.

Instant start_B = Instant.parse( "2016-01-03T00:00:00Z" );
Interval interval_B = Interval.of( start_B , Duration.of( 3 , ChronoUnit.DAYS ) );

Comparing to test for overlaps is easy.

Boolean overlaps = interval_A.overlaps( interval_B );

You can compare an Interval against another Interval or Instant:

All of these use the Half-Open approach to defining a span of time where the beginning is inclusive and the ending is exclusive.

.bashrc: Permission denied

.bashrc is not meant to be executed but sourced. Try this instead:

. ~/.bashrc

Cheers!

Intellij idea cannot resolve anything in maven

I had empty settings.xml file in Users/.../.m2/settings.xml. When i added

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      https://maven.apache.org/xsd/settings-1.0.0.xsd">

</settings>

all dependicies were loaded

Logical operators ("and", "or") in DOS batch

Athul Prakash (age 16 at the time) gave a logical idea for how to implement an OR test by negating the conditions in IF statements and then using the ELSE clause as the location to put the code that requires execution. I thought to myself that there are however two else clauses usually needed since he is suggesting using two IF statements, and so the executed code needs to be written twice. However, if a GOTO is used to skip past the required code, instead of writing ELSE clauses the code for execution only needs to be written once.

Here is a testable example of how I would implement Athul Prakash's negative logic to create an OR.

In my example, someone is allowed to drive a tank if they have a tank licence OR they are doing their military service. Enter true or false at the two prompts and you will be able to see whether the logic allows you to drive a tank.

@ECHO OFF
@SET /p tanklicence=tanklicence:
@SET /p militaryservice=militaryservice:

IF /I NOT %tanklicence%==true IF /I NOT %militaryservice%==true GOTO done

ECHO I am driving a tank with tanklicence set to %tanklicence% and militaryservice set to %militaryservice%

:done

PAUSE

Creating a segue programmatically

Storyboard Segues are not to be created outside of the storyboard. You will need to wire it up, despite the drawbacks.

UIStoryboardSegue Reference clearly states:

You do not create segue objects directly. Instead, the storyboard runtime creates them when it must perform a segue between two view controllers. You can still initiate a segue programmatically using the performSegueWithIdentifier:sender: method of UIViewController if you want. You might do so to initiate a segue from a source that was added programmatically and therefore not available in Interface Builder.

You can still programmatically tell the storyboard to present a view controller using a segue using presentModalViewController: or pushViewController:animated: calls, but you'll need a storyboard instance.

You can call UIStoryboards class method to get a named storyboard with bundle nil for the main bundle.

storyboardWithName:bundle:

Mark error in form using Bootstrap

(UPDATED with examples for Bootstrap v4, v3 and v3)

Examples of forms with validation classes for the past few major versions of Bootstrap.

Bootstrap v4

See the live version on codepen

bootstrap v4 form validation

<div class="container">
  <form>
    <div class="form-group row">
      <label for="inputEmail" class="col-sm-2 col-form-label text-success">Email</label>
      <div class="col-sm-7">
        <input type="email" class="form-control is-valid" id="inputEmail" placeholder="Email">
      </div>
    </div>

    <div class="form-group row">
      <label for="inputPassword" class="col-sm-2 col-form-label text-danger">Password</label>
      <div class="col-sm-7">
        <input type="password" class="form-control is-invalid" id="inputPassword" placeholder="Password">
      </div>
      <div class="col-sm-3">
        <small id="passwordHelp" class="text-danger">
          Must be 8-20 characters long.
        </small>      
      </div>
    </div>
  </form>
</div>

Bootstrap v3

See the live version on codepen

bootstrap v3 form validation

<form role="form">
  <div class="form-group has-warning">
    <label class="control-label" for="inputWarning">Input with warning</label>
    <input type="text" class="form-control" id="inputWarning">
    <span class="help-block">Something may have gone wrong</span>
  </div>
  <div class="form-group has-error">
    <label class="control-label" for="inputError">Input with error</label>
    <input type="text" class="form-control" id="inputError">
    <span class="help-block">Please correct the error</span>
  </div>
  <div class="form-group has-info">
    <label class="control-label" for="inputError">Input with info</label>
    <input type="text" class="form-control" id="inputError">
    <span class="help-block">Username is taken</span>
  </div>
  <div class="form-group has-success">
    <label class="control-label" for="inputSuccess">Input with success</label>
    <input type="text" class="form-control" id="inputSuccess" />
    <span class="help-block">Woohoo!</span>
  </div>
</form>

Bootstrap v2

See the live version on jsfiddle

bootstrap v2 form validation

The .error, .success, .warning and .info classes are appended to the .control-group. This is standard Bootstrap markup and styling in v2. Just follow that and you're in good shape. Of course you can go beyond with your own styles to add a popup or "inline flash" if you prefer, but if you follow Bootstrap convention and hang those validation classes on the .control-group it will stay consistent and easy to manage (at least since you'll continue to have the benefit of Bootstrap docs and examples)

  <form class="form-horizontal">
    <div class="control-group warning">
      <label class="control-label" for="inputWarning">Input with warning</label>
      <div class="controls">
        <input type="text" id="inputWarning">
        <span class="help-inline">Something may have gone wrong</span>
      </div>
    </div>
    <div class="control-group error">
      <label class="control-label" for="inputError">Input with error</label>
      <div class="controls">
        <input type="text" id="inputError">
        <span class="help-inline">Please correct the error</span>
      </div>
    </div>
    <div class="control-group info">
      <label class="control-label" for="inputInfo">Input with info</label>
      <div class="controls">
        <input type="text" id="inputInfo">
        <span class="help-inline">Username is taken</span>
      </div>
    </div>
    <div class="control-group success">
      <label class="control-label" for="inputSuccess">Input with success</label>
      <div class="controls">
        <input type="text" id="inputSuccess">
        <span class="help-inline">Woohoo!</span>
      </div>
    </div>
  </form>

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

Check for the name of the

templates

folder. it should be templates not template(without s).

How to implement common bash idioms in Python?

If your textfile manipulation usually is one-time, possibly done on the shell-prompt, you will not get anything better from python.

On the other hand, if you usually have to do the same (or similar) task over and over, and you have to write your scripts for doing that, then python is great - and you can easily create your own libraries (you can do that with shell scripts too, but it's more cumbersome).

A very simple example to get a feeling.

import popen2
stdout_text, stdin_text=popen2.popen2("your-shell-command-here")
for line in stdout_text:
  if line.startswith("#"):
    pass
  else
    jobID=int(line.split(",")[0].split()[1].lstrip("<").rstrip(">"))
    # do something with jobID

Check also sys and getopt module, they are the first you will need.

Can Mysql Split a column?

As an addendum to this, I've strings of the form: Some words 303

where I'd like to split off the numerical part from the tail of the string. This seems to point to a possible solution:

http://lists.mysql.com/mysql/222421

The problem however, is that you only get the answer "yes, it matches", and not the start index of the regexp match.

Mysql select distinct

Are you looking for "SELECT * FROM temp_tickets GROUP BY ticket_id ORDER BY ticket_id ?

UPDATE

SELECT t.* 
FROM 
(SELECT ticket_id, MAX(id) as id FROM temp_tickets GROUP BY ticket_id) a  
INNER JOIN temp_tickets t ON (t.id = a.id)

Android Endless List

I know its an old question and the Android world has mostly moved on to RecyclerViews, but for anyone interested, you may find this library very interesting.

It uses the BaseAdapter used with the ListView to detect when the list has been scrolled to the last item or when it is being scrolled away from the last item.

It comes with an example project(barely 100 lines of Activity code) that can be used to quickly understand how it works.

Simple usage:

class Boy{

private String name;
private double height;
private int age;
//Other code

}

An adapter to hold Boy objects would look like:


public class BoysAdapter extends EndlessAdapter<Boy>{




        ViewHolder holder = null;


        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(parent
                    .getContext());

            holder = new ViewHolder();

            convertView = inflater.inflate(
                    R.layout.list_cell, parent, false);


            holder.nameView = convertView.findViewById(R.id.cell);

            // minimize the default image.
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Boy boy = getItem(position);

        try {
            holder.nameView.setText(boy.getName());

            ///Other data rendering codes.

        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.getView(position,convertView,parent);

}

Notice how the BoysAdapter's getView method returns a call to the EndlessAdapter superclass's getView method. This is 100% essential.

Now to create the adapter, do:

   adapter = new ModelAdapter() {
            @Override
            public void onScrollToBottom(int bottomIndex, boolean moreItemsCouldBeAvailable) {

                if (moreItemsCouldBeAvailable) { 
                    makeYourServerCallForMoreItems();
                } else {
                    if (loadMore.getVisibility() != View.VISIBLE) {
                        loadMore.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onScrollAwayFromBottom(int currentIndex) { 
                loadMore.setVisibility(View.GONE);
            }

            @Override
            public void onFinishedLoading(boolean moreItemsReceived) { 
                if (!moreItemsReceived) {
                    loadMore.setVisibility(View.VISIBLE);
                }
            }
        };

The loadMore item is a button or other ui element that may be clicked to fetch more data from the url. When placed as described in the code, the adapter knows exactly when to show that button and when to disable it. Just create the button in your xml and place it as shown in the adapter code above.

Enjoy.

how to write value into cell with vba code without auto type conversion?

This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:

prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _ 
    param_cls_shift.Start_Date (string property of my class) 

How to split one string into multiple strings separated by at least one space in bash shell?

$ echo "This is   a sentence." | tr -s " " "\012"
This
is
a
sentence.

For checking for spaces, use grep:

$ echo "This is   a sentence." | grep " " > /dev/null
$ echo $?
0
$ echo "Thisisasentence." | grep " " > /dev/null     
$ echo $?
1

C# Numeric Only TextBox Control

From C#3.5 I assume you're using WPF.

Just make a two-way data binding from an integer property to your text-box. WPF will show the validation error for you automatically.

For the email case, make a two-way data binding from a string property that does Regexp validation in the setter and throw an Exception upon validation error.

Look up Binding on MSDN.

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

Aren't Python strings immutable? Then why does a + " " + b work?

Something is mutable only when we are able to change the values held in the memory location without changing the memory location itself.

The trick is: If you find that the memory location before and after the change are the same, it is mutable.

For example, list is mutable. How?

>> a = ['hello']
>> id(a)
139767295067632

# Now let's modify
#1
>> a[0] = "hello new"
>> a
['hello new']
Now that we have changed "a", let's see the location of a
>> id(a)
139767295067632
so it is the same as before. So we mutated a. So list is mutable.

A string is immutable. How do we prove it?

> a = "hello"
> a[0]
'h'
# Now let's modify it
> a[0] = 'n'
----------------------------------------------------------------------

we get

TypeError: 'str' object does not support item assignment

So we failed mutating the string. It means a string is immutable.

In you reassigning, you change the variable to point to a new location itself. Here you have not mutated the string, but mutating the variable itself. The following is what you are doing.

>> a = "hello"
>> id(a)
139767308749440
>> a ="world"
>> id(a)
139767293625808

id before and after reassignment is different, so it this proves that you are actually not mutating, but pointing the variable to new location. Which is not mutating that string, but mutating that variable.

App.Config file in console application C#

For .NET Core, add System.Configuration.ConfigurationManager from NuGet manager.
And read appSetting from App.config

<appSettings>
  <add key="appSetting1" value="1000" />
</appSettings>

Add System.Configuration.ConfigurationManager from NuGet Manager

enter image description here

ConfigurationManager.AppSettings.Get("appSetting1")

Javascript - Get Image height

Just load the image in a hidden <img> tag (style = "display none"), listen to the load event firing with jQuery, create a new Image() with JavaScript, set the source to the invisible image, and get the size like above.

Python error when trying to access list by index - "List indices must be integers, not str"

Were you expecting player to be a dict rather than a list?

>>> player=[1,2,3]
>>> player["score"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> player={'score':1, 'age': 2, "foo":3}
>>> player['score']
1

What do >> and << mean in Python?

They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.

| operate | bit value | octal value |                       description                        |
| ------- | --------- | ----------- | -------------------------------------------------------- |
|         | 00000100  |           4 |                                                          |
| 4 << 2  | 00010000  |          16 | move all bits to left 2 bits, filled with 0 at the right |
| 16 >> 2 | 00000100  |           4 | move all bits to right 2 bits, filled with 0 at the left |

What is token-based authentication?

When you register for a new website, often you are sent an email to activate your account. That email typically contains a link to click on. Part of that link, contains a token, the server knows about this token and can associate it with your account. The token would usually have an expiry date associated with it, so you may only have an hour to click on the link and activate your account. None of this would be possible with cookies or session variables, since its unknown what device or browser the customer is using to check emails.

Difference between Constructor and ngOnInit

constructor() is used to do dependency injection.

ngOnInit(), ngOnChanges() and ngOnDestroy() etc. are lifecycle methods. ngOnChanges() will be the first to be called, before ngOnInit(), when the value of a bound property changes, it will NOT be called if there is no change. ngOnDestroy() is called when the component is removed. To use it, OnDestroy needs to be implemented by the class.

Class has no objects member

By doing Question = new Question() (I assume the new is a typo) you are overwriting the Question model with an intance of Question. Like Sayse said in the comments: don't use the same name for your variable as the name of the model. So change it to something like my_question = Question().

Does a TCP socket connection have a "keep alive"?

In JAVA Socket – TCP connections are managed on the OS level, java.net.Socket does not provide any in-built function to set timeouts for keepalive packet on a per-socket level. But we can enable keepalive option for java socket but it takes 2 hours 11 minutes (7200 sec) by default to process after a stale tcp connections. This cause connection will be availabe for very long time before purge. So we found some solution to use Java Native Interface (JNI) that call native code(c++) to configure these options.

****Windows OS****

In windows operating system keepalive_time & keepalive_intvl can be configurable but tcp_keepalive_probes cannot be change.By default, when a TCP socket is initialized sets the keep-alive timeout to 2 hours and the keep-alive interval to 1 second. The default system-wide value of the keep-alive timeout is controllable through the KeepAliveTime registry setting which takes a value in milliseconds.

On Windows Vista and later, the number of keep-alive probes (data retransmissions) is set to 10 and cannot be changed.

On Windows Server 2003, Windows XP, and Windows 2000, the default setting for number of keep-alive probes is 5. The number of keep-alive probes is controllable. For windows Winsock IOCTLs library is used to configure the tcp-keepalive parameters.

int WSAIoctl( SocketFD, // descriptor identifying a socket SIO_KEEPALIVE_VALS, // dwIoControlCode (LPVOID) lpvInBuffer, // pointer to tcp_keepalive struct (DWORD) cbInBuffer, // length of input buffer NULL, // output buffer 0, // size of output buffer (LPDWORD) lpcbBytesReturned, // number of bytes returned NULL, // OVERLAPPED structure NULL // completion routine );

Linux OS

Linux has built-in support for keepalive which is need to be enabling TCP/IP networking in order to use it. Programs must request keepalive control for their sockets using the setsockopt interface.

int setsockopt(int socket, int level, int optname, const void *optval, socklen_t optlen)

Each client socket will be created using java.net.Socket. File descriptor ID for each socket will retrieve using java reflection.

How to get the CPU Usage in C#?

It's OK, I got it! Thanks for your help!

Here is the code to do it:

private void button1_Click(object sender, EventArgs e)
{
    selectedServer = "JS000943";
    listBox1.Items.Add(GetProcessorIdleTime(selectedServer).ToString());
}

private static int GetProcessorIdleTime(string selectedServer)
{
    try
    {
        var searcher = new
           ManagementObjectSearcher
             (@"\\"+ selectedServer +@"\root\CIMV2",
              "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");

        ManagementObjectCollection collection = searcher.Get();
        ManagementObject queryObj = collection.Cast<ManagementObject>().First();

        return Convert.ToInt32(queryObj["PercentIdleTime"]);
    }
    catch (ManagementException e)
    {
        MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
    }
    return -1;
}

Should I use past or present tense in git commit messages?

I wrote a fuller description on 365git.

The use of the imperative, present tense is one that takes a little getting used to. When I started mentioning it, it was met with resistance. Usually along the lines of “The commit message records what I have done”. But, Git is a distributed version control system where there are potentially many places to get changes from. Rather than writing messages that say what you’ve done; consider these messages as the instructions for what applying the commit will do. Rather than having a commit with the title:

Renamed the iVars and removed the common prefix.

Have one like this:

Rename the iVars to remove the common prefix

Which tells someone what applying the commit will do, rather than what you did. Also, if you look at your repository history you will see that the Git generated messages are written in this tense as well - “Merge” not “Merged”, “Rebase” not “Rebased” so writing in the same tense keeps things consistent. It feels strange at first but it does make sense (testimonials available upon application) and eventually becomes natural.

Having said all that - it’s your code, your repository: so set up your own guidelines and stick to them.

If, however, you do decide to go this way then git rebase -i with the reword option would be a good thing to look into.

How to plot multiple functions on the same figure, in Matplotlib?

To plot multiple graphs on the same figure you will have to do:

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, 'r') # plotting t, a separately 
plt.plot(t, b, 'b') # plotting t, b separately 
plt.plot(t, c, 'g') # plotting t, c separately 
plt.show()

enter image description here

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

I will add for those that get stuck trying to run PHP (Laravel in may case) or other unique IIS hosting situation with the 405 error, that you need to change the verbs in the handler for that for that specific situation... so since I was using PHP I went to the PHP handler and in the Request Restrictions, then Verbs tab, add the verbs you need. This was all I needed to add to the web.config to enable CORS in Laravel.

<handlers>
  <remove name="php-5.6.40" />
  <add name="php-5.6.40" path="*.php" verb="GET,HEAD,POST,PUT,DELETE,OPTIONS" modules="FastCgiModule" scriptProcessor="C:\Program Files (x86)\PHP\v5.6\php-cgi.exe" resourceType="Either" requireAccess="Script" />
</handlers>

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

How do I get the path of a process in Unix / Linux

A little bit late, but all the answers were specific to linux.

If you need also unix, then you need this:

char * getExecPath (char * path,size_t dest_len, char * argv0)
{
    char * baseName = NULL;
    char * systemPath = NULL;
    char * candidateDir = NULL;

    /* the easiest case: we are in linux */
    size_t buff_len;
    if (buff_len = readlink ("/proc/self/exe", path, dest_len - 1) != -1)
    {
        path [buff_len] = '\0';
        dirname (path);
        strcat  (path, "/");
        return path;
    }

    /* Ups... not in linux, no  guarantee */

    /* check if we have something like execve("foobar", NULL, NULL) */
    if (argv0 == NULL)
    {
        /* we surrender and give current path instead */
        if (getcwd (path, dest_len) == NULL) return NULL;
        strcat  (path, "/");
        return path;
    }


    /* argv[0] */
    /* if dest_len < PATH_MAX may cause buffer overflow */
    if ((realpath (argv0, path)) && (!access (path, F_OK)))
    {
        dirname (path);
        strcat  (path, "/");
        return path;
    }

    /* Current path */
    baseName = basename (argv0);
    if (getcwd (path, dest_len - strlen (baseName) - 1) == NULL)
        return NULL;

    strcat (path, "/");
    strcat (path, baseName);
    if (access (path, F_OK) == 0)
    {
        dirname (path);
        strcat  (path, "/");
        return path;
    }

    /* Try the PATH. */
    systemPath = getenv ("PATH");
    if (systemPath != NULL)
    {
        dest_len--;
        systemPath = strdup (systemPath);
        for (candidateDir = strtok (systemPath, ":"); candidateDir != NULL; candidateDir = strtok (NULL, ":"))
        {
            strncpy (path, candidateDir, dest_len);
            strncat (path, "/", dest_len);
            strncat (path, baseName, dest_len);

            if (access(path, F_OK) == 0)
            {
                free (systemPath);
                dirname (path);
                strcat  (path, "/");
                return path;
            }
        }
        free(systemPath);
        dest_len++;
    }

    /* again someone has use execve: we dont knowe the executable name; we surrender and give instead current path */
    if (getcwd (path, dest_len - 1) == NULL) return NULL;
    strcat  (path, "/");
    return path;
}

EDITED: Fixed the bug reported by Mark lakata.

MySQLi count(*) always returns 1

I find this way more readable:

$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
echo "there are {$count} rows in the table";

Not that I have anything against arrays...

Difference between socket and websocket?

Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.

I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How can I render repeating React elements?

This is, imo, the most elegant way to do it (with ES6). Instantiate you empty array with 7 indexes and map in one line:

Array.apply(null, Array(7)).map((i)=>
<Somecomponent/>
)

kudos to https://php.quicoto.com/create-loop-inside-react-jsx/

NGinx Default public www location?

For Ubuntu and docker images:

/usr/share/nginx/html/

Visual studio equivalent of java System.out

In System.Diagnostics,

Debug.Write()
Debug.WriteLine()

etc. will print to the Output window in VS.

How to write string literals in python without having to escape them?

If you're dealing with very large strings, specifically multiline strings, be aware of the triple-quote syntax:

a = r"""This is a multiline string
with more than one line
in the source code."""

HAProxy redirecting http to https (ssl)

  acl host-example hdr(host) -i www.example.com

  # for everything not https
  http-request redirect scheme https code 301 unless { ssl_fc }

  # for anything matching acl
  http-request redirect scheme https code 301 if host-example !{ ssl_fc }

How to center div vertically inside of absolutely positioned parent div

First of all note that vertical-align is only applicable to table cells and inline-level elements.

There are couple of ways to achieve vertical alignments which may or may not meet your needs. However I'll show you two methods from my favorites:

1. Using transform and top

_x000D_
_x000D_
.valign {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    /* vendor prefixes omitted due to brevity */
}
_x000D_
<div style="position: absolute; left: 50px; top: 50px;">
    <div style="text-align: left; position: absolute;height: 56px;background-color: pink;">
        <div class="valign" style="background-color: lightblue;">test</div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

The key point is that a percentage value on top is relative to the height of the containing block; While a percentage value on transforms is relative to the size of the box itself (the bounding box).

If you experience font rendering issues (blurry font), the fix is to add perspective(1px) to the transform declaration so it becomes:

transform: perspective(1px) translateY(-50%);

It's worth noting that CSS transform is supported in IE9+.

2. Using inline-block (pseudo-)elements

In this method, we have two sibling inline-block elements which are aligned vertically at the middle by vertical-align: middle declaration.

One of them has a height of 100% of its parent and the other is our desired element whose we wanted to align it at the middle.

_x000D_
_x000D_
.parent {
    text-align: left;
    position: absolute;
    height: 56px;
    background-color: pink;
    white-space: nowrap;
    font-size: 0; /* remove the gap between inline level elements */
}

.dummy-child { height: 100%; }

.valign {
    font-size: 16px; /* re-set the font-size */
}

.dummy-child, .valign {
    display: inline-block;
    vertical-align: middle;
}
_x000D_
<div style="position: absolute; left: 50px; top: 50px;">
    <div class="parent">
        <div class="dummy-child"></div>
        <div class="valign" style="background-color: lightblue;">test</div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

Finally, we should use one of the available methods to remove the gap between inline-level elements.

What are public, private and protected in object oriented programming?

All the three are access modifiers and keywords which are used in a class. Anything declared in public can be used by any object within the class or outside the class,variables in private can only be used by the objects within the class and could not be changed through direct access(as it can change through functions like friend function).Anything defined under protected section can be used by the class and their just derived class.

Getting multiple values with scanf()

You can do this with a single call, like so:

scanf( "%i %i %i %i", &minx, &maxx, &miny, &maxy);

How do I read a text file of about 2 GB?

I always use 010 Editor to open huge files. It can handle 2 GB easily. I was manipulating files with 50 GB with 010 Editor :-)

It's commercial now, but it has a trial version.

wget command to download a file and save as a different filename

Also notice the order of parameters on the command line. At least on some systems (e.g. CentOS 6):

wget -O FILE URL

works. But:

wget URL -O FILE

does not work.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

@Autowired - No qualifying bean of type found for dependency at least 1 bean

Just add below annotation with qualifier name of service in service Implementation class:

@Service("employeeService")
@Transactional
public class EmployeeServiceImpl implements EmployeeService{
}

How do you loop in a Windows batch file?

Conditionally perform a command several times.

  • syntax-FOR-Files

    FOR %%parameter IN (set) DO command 
    
  • syntax-FOR-Files-Rooted at Path

    FOR /R [[drive:]path] %%parameter IN (set) DO command 
    
  • syntax-FOR-Folders

    FOR /D %%parameter IN (folder_set) DO command 
    
  • syntax-FOR-List of numbers

    FOR /L %%parameter IN (start,step,end) DO command 
    
  • syntax-FOR-File contents

    FOR /F ["options"] %%parameter IN (filenameset) DO command 
    

    or

    FOR /F ["options"] %%parameter IN ("Text string to process") DO command
    
  • syntax-FOR-Command Results

    FOR /F ["options"] %%parameter IN ('command to process') DO command
    

It

  • Take a set of data
  • Make a FOR Parameter %%G equal to some part of that data
  • Perform a command (optionally using the parameter as part of the command).
  • --> Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G instead of %%G.

FOR Parameters

  • The first parameter has to be defined using a single character, for example the letter G.

  • FOR %%G IN ...

    In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value

    If this clause results in a single value then %%G is set equal to that value and the command is performed.

    If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)

    If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.

    You can of course pick any letter of the alphabet other than %%G. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.

Search for a string in Enum and return the Enum

class EnumStringToInt // to search for a string in enum
{
    enum Numbers{one,two,hree};
    static void Main()
    {
        Numbers num = Numbers.one; // converting enum to string
        string str = num.ToString();
        //Console.WriteLine(str);
        string str1 = "four";
        string[] getnames = (string[])Enum.GetNames(typeof(Numbers));
        int[] getnum = (int[])Enum.GetValues(typeof(Numbers));
        try
        {
            for (int i = 0; i <= getnum.Length; i++)
            {
                if (str1.Equals(getnames[i]))
                {
                    Numbers num1 = (Numbers)Enum.Parse(typeof(Numbers), str1);
                    Console.WriteLine("string found:{0}", num1);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Value not found!", ex);
        }
    }
}

R - Markdown avoiding package loading messages

This is an old question, but here's another way to do it.

You can modify the R code itself instead of the chunk options, by wrapping the source call in suppressPackageStartupMessages(), suppressMessages(), and/or suppressWarnings(). E.g:

```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```

You can also put those functions around your library() calls inside the "source.R" script.

How to order a data frame by one descending and one ascending column?

I'm afraid Roman Luštrik's answer is wrong. It works on this input by chance. Consider for example its output on a very similar input (with an additional line similar to the original line 3 with "c" in the I2 column):

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2   3   5   52  43  61  6   b
6   4   3   72  NA  59  1   a
1   5   6   55  48  60  6   f
2   4   4   65  64  58  2   b
1   5   6   55  48  60  6   c"), header = TRUE)

rum$I2 <- as.character(rum$I2)
rum[order(rum$I1, rev(rum$I2), decreasing = TRUE), ]

  P1 P2 P3 T1 T2 T3 I1 I2
3  1  5  6 55 48 60  6  f
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

This is not the desired result: the first three values of I2 are f b c instead of b c f, which would be expected since the secondary sort is I2 in ascending order.

To get the reverse order of I2, you want the large values to be small and vice versa. For numeric values multiplying by -1 will do it, but for characters its a bit more tricky. A general solution for characters/strings would be to go through factors, reverse the levels (to make large values small and small values large) and change the factor back to characters:

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2   3   5   52  43  61  6   b
6   4   3   72  NA  59  1   a
1   5   6   55  48  60  6   f
2   4   4   65  64  58  2   b
1   5   6   55  48  60  6   c"), header = TRUE)

f=factor(rum$I2)
levels(f) = rev(levels(f))
rum[order(rum$I1, as.character(f), decreasing = TRUE), ]

  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

Storing Form Data as a Session Variable

Yes this is possible. kizzie is correct with the session_start(); having to go first.

another observation I made is that you need to filter your form data using:

strip_tags($value);

and/or

stripslashes($value);

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'))

Increment counter with loop

what led me to this page is that I set within a page then the inside of an included page I did the increment

and here is the problem

so to solve such a problem, simply use scope="request" when you declare the variable or the increment

//when you set the variale add scope="request"
<c:set var="nFilters" value="${0}" scope="request"/>
//the increment, it can be happened inside an included page
<c:set var="nFilters" value="${nFilters + 1}"  scope="request" />

hope this saves your time

Error importing Seaborn module in Python

I solved this problem by looking at sys.path (the path for finding modules) while in ipython and noticed that I was in a special environment (because I use conda).

so i went to my terminal and typed "source activate py27" is my python 2.7 environment. and then "conda update seaborn", restarted my jupyter kernel, and then all was good.

Declare multiple module.exports in Node.js

If the files are written using ES6 export, you can write:

module.exports = {
  ...require('./foo'),
  ...require('./bar'),
};

How to upgrade scikit-learn package in anaconda

Anaconda comes with the conda package manager which is designed to handle these kinds of upgrades. Start by updating conda itself to get the most recent package lists:

conda update conda

And then install the version of scikit-learn you want

conda install scikit-learn=0.17

All necessary dependencies will be upgraded as well. If you have trouble with conda on Windows, there are some relevant FAQ here: http://docs.continuum.io/anaconda/faq

How do I use a delimiter with Scanner.useDelimiter in Java?

With Scanner the default delimiters are the whitespace characters.

But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:

  1. Using the Scanner method: useDelimiter(String pattern)
  2. Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.

So useDelimiter() methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:

And here is an Example:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    scan.useDelimiter("/");
    // Printing the tokenized Strings
    while(scan.hasNext()){
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();
}

Prints this output:

Anna Mills
Female
18

Android - Share on Facebook, Twitter, Mail, ecc

String message = "This is testing."
Intent shareText = new Intent(Intent.ACTION_SEND);
shareText .setType("text/plain");
shareText .putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(shareText , "Title of the dialog the system will open"));

Switching the order of block elements with CSS

This method worked for me without flexbox:

_x000D_
_x000D_
#blockA,_x000D_
#blockB,_x000D_
#blockC {_x000D_
    border: 1px solid black;_x000D_
    padding: 20px;_x000D_
}_x000D_
_x000D_
_x000D_
.reverseOrder,_x000D_
#blockA,_x000D_
#blockB,_x000D_
#blockC {_x000D_
    -webkit-transform: rotate(180deg);_x000D_
       -moz-transform: rotate(180deg);_x000D_
        -ms-transform: rotate(180deg);_x000D_
         -o-transform: rotate(180deg);_x000D_
            transform: rotate(180deg);_x000D_
}
_x000D_
<div class="reverseOrder">_x000D_
    <div id="blockA">Block A</div>_x000D_
    <div id="blockB">Block B</div>_x000D_
    <div id="blockC">Block C</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

How to add footnotes to GitHub-flavoured Markdown?

For short notes, providing an anchor element with a title attribute creates a "tooltip".

<a title="Note text goes here."><sup>n</sup></a>

Otherwise, for more involved notes, it looks like your best bet is maintaining named links manually.

How to check if an array is empty?

you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.

should use size_t or ssize_t

ssize_t is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX] (SSIZE_MAX is system-dependent).

So you should use size_t whenever you mean to return a size in bytes, and ssize_t whenever you would return either a size in bytes or a (negative) error value.

See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

Python SQLite: database is locked

The database is locked by another process that is writing to it. You have to wait until the other transaction is committed. See the documentation of connect()

SQL Server error on update command - "A severe error occurred on the current command"

in my case, the method: context.Database.CreateIfNotExists(); called up multiple times before create database and crashed an error A severe error occurred on the current command. The results, if any, should be discarded.

Why can't I have abstract static methods in C#?

Here is a situation where there is definitely a need for inheritance for static fields and methods:

abstract class Animal
{
  protected static string[] legs;

  static Animal() {
    legs=new string[0];
  }

  public static void printLegs()
  {
    foreach (string leg in legs) {
      print(leg);
    }
  }
}


class Human: Animal
{
  static Human() {
    legs=new string[] {"left leg", "right leg"};
  }
}


class Dog: Animal
{
  static Dog() {
    legs=new string[] {"left foreleg", "right foreleg", "left hindleg", "right hindleg"};
  }
}


public static void main() {
  Dog.printLegs();
  Human.printLegs();
}


//what is the output?
//does each subclass get its own copy of the array "legs"?

Pass Multiple Parameters to jQuery ajax call

Don't use string concatenation to pass parameters, just use a data hash:

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: { jewellerId: filter, locale: 'en-US' },
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});

UPDATE:

As suggested by @Alex in the comments section, an ASP.NET PageMethod expects parameters to be JSON encoded in the request, so JSON.stringify should be applied on the data hash:

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ jewellerId: filter, locale: 'en-US' }),
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});

Clone an image in cv2 python

My favorite method uses cv2.copyMakeBorder with no border, like so.

copy = cv2.copyMakeBorder(original,0,0,0,0,cv2.BORDER_REPLICATE)

disable a hyperlink using jQuery

$('.my-link').click(function(e) { e.preventDefault(); }); 

You could use:

$('.my-link').click(function(e) { return false; }); 

But I don't like to use this myself as it is more cryptic, even though it is used extensively throughout much jQuery code.

RecyclerView - Get view at particular position

To get specific view from recycler view list OR show error at edittext of recycler view.

private void popupErrorMessageAtPosition(int itemPosition) {

    RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(itemPosition);
    View view = viewHolder.itemView;
    EditText etDesc = (EditText) view.findViewById(R.id.et_description);
    etDesc.setError("Error message here !");
}

jquery remove "selected" attribute of option?

This works:

$("#myselect").find('option').removeAttr("selected");

or

$("#myselect").find('option:selected').removeAttr("selected");

jsFiddle

Limit the size of a file upload (html input element)

var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 2097152){
       alert("File is too big!");
       this.value = "";
    };
};

This example should work fine. I set it up for roughly 2MB, 1MB in Bytes is 1,048,576 so you can multiply it by the limit you need.

Here is the jsfiddle example for more clearence:
https://jsfiddle.net/7bjfr/808/

password-check directive in angularjs

I was dealing with the same issue and found a good blog post about it written by Piotr Buda. It's a good read and it explains the process very well. The code is as follows:

directives.directive("repeatPassword", function() {
    return {
        require: "ngModel",
        link: function(scope, elem, attrs, ctrl) {
            var otherInput = elem.inheritedData("$formController")[attrs.repeatPassword];

            ctrl.$parsers.push(function(value) {
                if(value === otherInput.$viewValue) {
                    ctrl.$setValidity("repeat", true);
                    return value;
                }
                ctrl.$setValidity("repeat", false);
            });

            otherInput.$parsers.push(function(value) {
                ctrl.$setValidity("repeat", value === ctrl.$viewValue);
                return value;
            });
        }
    };
});

So you could do something like:

<input type="password" name="repeatPassword" id="repeatPassword" placeholder="repeat password" ng-model="user.repeatPassword" repeat-password="password" required>

Credit goes to the author

Tooltips for cells in HTML table (no Javascript)

if (data[j] =='B'){
    row.cells[j].title="Basic";
}

In Java script conditionally adding title by comparing value of Data. The Table is generated by Java script dynamically.

Dynamically add script tag with src that may include document.write

the only way to do this is to replace document.write with your own function which will append elements to the bottom of your page. It is pretty straight forward with jQuery:

document.write = function(htmlToWrite) {
  $(htmlToWrite).appendTo('body');
}

If you have html coming to document.write in chunks like the question example you'll need to buffer the htmlToWrite segments. Maybe something like this:

document.write = (function() {
  var buffer = "";
  var timer;
  return function(htmlPieceToWrite) {
    buffer += htmlPieceToWrite;
    clearTimeout(timer);
    timer = setTimeout(function() {
      $(buffer).appendTo('body');
      buffer = "";
    }, 0)
  }
})()

How to create a numeric vector of zero length in R

Suppose you want to create a vector x whose length is zero. Now let v be any vector.

> v<-c(4,7,8)
> v
[1] 4 7 8
> x<-v[0]
> length(x)
[1] 0

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

If you are providing mappings like this:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ClassificationMap());
        modelBuilder.Configurations.Add(new CompanyMap());
        modelBuilder.Configurations.Add(new GroupMap());
        ....  
    }

Remember to add the map for BaseCs.

You won't get a compile error if it is missing. But you will get a runtime error when you use the entity.

Installing Homebrew on OS X

macOS Big Sur

Had to add this to Terminal cmd to get Brew running.

  • Add Homebrew to your PATH in /Users/*username/.zprofile:

      echo 'eval $(/opt/homebrew/bin/brew shellenv)' >> /Users/*username/.zprofile
      eval $(/opt/homebrew/bin/brew shellenv)
    

*username = your local machine username

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

What is the default access modifier in Java?

The Default access modifier is package-private (i.e DEFAULT) and it is visible only from the same package.

Writing files in Node.js

Currently there are three ways to write a file:

  1. fs.write(fd, buffer, offset, length, position, callback)

    You need to wait for the callback to ensure that the buffer is written to disk. It's not buffered.

  2. fs.writeFile(filename, data, [encoding], callback)

    All data must be stored at the same time; you cannot perform sequential writes.

  3. fs.createWriteStream(path, [options])

    Creates a WriteStream, which is convenient because you don't need to wait for a callback. But again, it's not buffered.

A WriteStream, as the name says, is a stream. A stream by definition is “a buffer” containing data which moves in one direction (source ? destination). But a writable stream is not necessarily “buffered”. A stream is “buffered” when you write n times, and at time n+1, the stream sends the buffer to the kernel (because it's full and needs to be flushed).

In other words: “A buffer” is the object. Whether or not it “is buffered” is a property of that object.

If you look at the code, the WriteStream inherits from a writable Stream object. If you pay attention, you’ll see how they flush the content; they don't have any buffering system.

If you write a string, it’s converted to a buffer, and then sent to the native layer and written to disk. When writing strings, they're not filling up any buffer. So, if you do:

write("a")
write("b")
write("c")

You're doing:

fs.write(new Buffer("a"))
fs.write(new Buffer("b"))
fs.write(new Buffer("c"))

That’s three calls to the I/O layer. Although you're using “buffers”, the data is not buffered. A buffered stream would do: fs.write(new Buffer ("abc")), one call to the I/O layer.

As of now, in Node.js v0.12 (stable version announced 02/06/2015) now supports two functions: cork() and uncork(). It seems that these functions will finally allow you to buffer/flush the write calls.

For example, in Java there are some classes that provide buffered streams (BufferedOutputStream, BufferedWriter...). If you write three bytes, these bytes will be stored in the buffer (memory) instead of doing an I/O call just for three bytes. When the buffer is full the content is flushed and saved to disk. This improves performance.

I'm not discovering anything, just remembering how a disk access should be done.

How do I print the type or class of a variable in Swift?

You can still access the class, through className (which returns a String).

There are actually several ways to get the class, for example classForArchiver, classForCoder, classForKeyedArchiver (all return AnyClass!).

You can't get the type of a primitive (a primitive is not a class).

Example:

var ivar = [:]
ivar.className // __NSDictionaryI

var i = 1
i.className // error: 'Int' does not have a member named 'className'

If you want to get the type of a primitive, you have to use bridgeToObjectiveC(). Example:

var i = 1
i.bridgeToObjectiveC().className // __NSCFNumber

IE11 prevents ActiveX from running

Try this tag on the pages that use the ActiveX control:

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

Note: this has to be the very first element in the <head> section.

Split comma separated column data into additional columns

If the number of fields in the CSV is constant then you could do something like this:

select a[1], a[2], a[3], a[4]
from (
    select regexp_split_to_array('a,b,c,d', ',')
) as dt(a)

For example:

=> select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
 a | a | a | a 
---+---+---+---
 a | b | c | d
(1 row)

If the number of fields in the CSV is not constant then you could get the maximum number of fields with something like this:

select max(array_length(regexp_split_to_array(csv, ','), 1))
from your_table

and then build the appropriate a[1], a[2], ..., a[M] column list for your query. So if the above gave you a max of 6, you'd use this:

select a[1], a[2], a[3], a[4], a[5], a[6]
from (
    select regexp_split_to_array(csv, ',')
    from your_table
) as dt(a)

You could combine those two queries into a function if you wanted.

For example, give this data (that's a NULL in the last row):

=> select * from csvs;
     csv     
-------------
 1,2,3
 1,2,3,4
 1,2,3,4,5,6

(4 rows)

=> select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
 max 
-----
   6
(1 row)

=> select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
 a | a | a | a | a | a 
---+---+---+---+---+---
 1 | 2 | 3 |   |   | 
 1 | 2 | 3 | 4 |   | 
 1 | 2 | 3 | 4 | 5 | 6
   |   |   |   |   | 
(4 rows)

Since your delimiter is a simple fixed string, you could also use string_to_array instead of regexp_split_to_array:

select ...
from (
    select string_to_array(csv, ',')
    from csvs
) as dt(a);

Thanks to Michael for the reminder about this function.

You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.

What is the difference between IQueryable<T> and IEnumerable<T>?

Here is what I wrote on a similar post (on this topic). (And no, I don't usually quote myself, but these are very good articles.)

"This article is helpful: IQueryable vs IEnumerable in LINQ-to-SQL.

Quoting that article, 'As per the MSDN documentation, calls made on IQueryable operate by building up the internal expression tree instead. "These methods that extend IQueryable(Of T) do not perform any querying directly. Instead, their functionality is to build an Expression object, which is an expression tree that represents the cumulative query. "'

Expression trees are a very important construct in C# and on the .NET platform. (They are important in general, but C# makes them very useful.) To better understand the difference, I recommend reading about the differences between expressions and statements in the official C# 5.0 specification here. For advanced theoretical concepts that branch into lambda calculus, expressions enable support for methods as first-class objects. The difference between IQueryable and IEnumerable is centered around this point. IQueryable builds expression trees whereas IEnumerable does not, at least not in general terms for those of us who don't work in the secret labs of Microsoft.

Here is another very useful article that details the differences from a push vs. pull perspective. (By "push" vs. "pull," I am referring to direction of data flow. Reactive Programming Techniques for .NET and C#

Here is a very good article that details the differences between statement lambdas and expression lambdas and discusses the concepts of expression tress in greater depth: Revisiting C# delegates, expression trees, and lambda statements vs. lambda expressions.."

Convert DataTable to List<T>

There is a little example that you can use

            DataTable dt = GetCustomersDataTable(null);            

            IEnumerable<SelectListItem> lstCustomer = dt.AsEnumerable().Select(x => new SelectListItem()
            {
                Value = x.Field<string>("CustomerId"),
                Text = x.Field<string>("CustomerDescription")
            }).ToList();

            return lstCustomer;

Launch Android application without main Activity and start Service on launching application

The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found.

Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing. Then click ok and run the App.

(Since there is no launcher activity, No app will be show in the Apps menu.).

Use CASE statement to check if column exists in table - SQL Server

Try this one -

SELECT *
FROM ...
WHERE EXISTS(SELECT 1 
        FROM sys.columns c
        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
            AND c.name = 'ModifiedByUser'
    )

How do I calculate the date six months from the current date using the datetime Python module?

I found this solution to be good. (This uses the python-dateutil extension)

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() + relativedelta(months=+6)

The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)

$ date(2010,12,31)+relativedelta(months=+1)
  datetime.date(2011, 1, 31)

$ date(2010,12,31)+relativedelta(months=+2)
  datetime.date(2011, 2, 28)

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT * FROM 
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser

Configuring user and password with Git Bash

Try ssh-agent for installing the SSH key for use with Git. It should auto login after use of a passphrase.

Set textbox to readonly and background color to grey in jquery

Can add disable like below and can get data on submit. something like this .. DEMO

Html

<input type="hidden" name="email" value="email" />
<input type="text" id="dis" class="disable" value="email"   name="email" >

JS

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

CSS

    .disable { opacity : .35; background-color:lightgray; border:1px solid gray;}

Installing specific laravel version with composer create-project

From the composer help create-project command

The create-project command creates a new project from a given
package into a new directory. If executed without params and in a directory with a composer.json file it installs the packages for the current project.
You can use this command to bootstrap new projects or setup a clean
version-controlled installation for developers of your project.

[version]
You can also specify the version with the package name using = or : as separator.

To install unstable packages, either specify the version you want, or use the --stability=dev (where dev can be one of RC, beta, alpha or dev).

This command works:

composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist

This works with the * notation.

Determine if Python is running inside virtualenv

This is an improvement of the accepted answer by Carl Meyer. It works with virtualenv for Python 3 and 2 and also for the venv module in Python 3:

import sys


def is_venv():
    return (hasattr(sys, 'real_prefix') or
            (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))

The check for sys.real_prefix covers virtualenv, the equality of non-empty sys.base_prefix with sys.prefix covers venv.

Consider a script that uses the function like this:

if is_venv():
    print('inside virtualenv or venv')
else:
    print('outside virtualenv or venv')

And the following invocation:

$ python2 test.py 
outside virtualenv or venv

$ python3 test.py 
outside virtualenv or venv

$ python2 -m virtualenv virtualenv2
...
$ . virtualenv2/bin/activate
(virtualenv2) $ python test.py 
inside virtualenv or venv
(virtualenv2) $ deactivate

$ python3 -m virtualenv virtualenv3
...
$ . virtualenv3/bin/activate
(virtualenv3) $ python test.py 
inside virtualenv or venv
(virtualenv3) $ deactivate 

$ python3 -m venv venv3
$ . venv3/bin/activate
(venv3) $ python test.py 
inside virtualenv or venv
(venv3) $ deactivate 

How to fit in an image inside span tag?

Try this.

<span style="padding-right:3px; padding-top: 3px; display:inline-block;">

<img class="manImg" src="images/ico_mandatory.gif"></img>

</span>

What is the JavaScript equivalent of var_dump or print_r in PHP?

Firebug.

Then, in your javascript:

var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);

Now you can look at the console, click on the statement and see what is inside blah

How can I see what I am about to push with git?

For a list of files to be pushed, run:

git diff --stat --cached [remote/branch]

example:

git diff --stat --cached origin/master

For the code diff of the files to be pushed, run:

git diff [remote repo/branch]

To see full file paths of the files that will change, run:

git diff --numstat [remote repo/branch]

If you want to see these diffs in a GUI, you will need to configure git for that. See How do I view 'git diff' output with a visual diff program?.

Can I create view with parameter in MySQL?

CREATE VIEW MyView AS
   SELECT Column, Value FROM Table;


SELECT Column FROM MyView WHERE Value = 1;

Is the proper solution in MySQL, some other SQLs let you define Views more exactly.

Note: Unless the View is very complicated, MySQL will optimize this just fine.

Time complexity of nested for-loop

Yes, nested loops are one way to quickly get a big O notation.

Typically (but not always) one loop nested in another will cause O(n²).

Think about it, the inner loop is executed i times, for each value of i. The outer loop is executed n times.

thus you see a pattern of execution like this: 1 + 2 + 3 + 4 + ... + n times

Therefore, we can bound the number of code executions by saying it obviously executes more than n times (lower bound), but in terms of n how many times are we executing the code?

Well, mathematically we can say that it will execute no more than n² times, giving us a worst case scenario and therefore our Big-Oh bound of O(n²). (For more information on how we can mathematically say this look at the Power Series)

Big-Oh doesn't always measure exactly how much work is being done, but usually gives a reliable approximation of worst case scenario.


4 yrs later Edit: Because this post seems to get a fair amount of traffic. I want to more fully explain how we bound the execution to O(n²) using the power series

From the website: 1+2+3+4...+n = (n² + n)/2 = n²/2 + n/2. How, then are we turning this into O(n²)? What we're (basically) saying is that n² >= n²/2 + n/2. Is this true? Let's do some simple algebra.

  • Multiply both sides by 2 to get: 2n² >= n² + n?
  • Expand 2n² to get:n² + n² >= n² + n?
  • Subtract n² from both sides to get: n² >= n?

It should be clear that n² >= n (not strictly greater than, because of the case where n=0 or 1), assuming that n is always an integer.

Actual Big O complexity is slightly different than what I just said, but this is the gist of it. In actuality, Big O complexity asks if there is a constant we can apply to one function such that it's larger than the other, for sufficiently large input (See the wikipedia page)

Loop through all the rows of a temp table and call a stored procedure for each row

something like this?

DECLARE maxval, val, @ind INT;
SELECT MAX(ID) as maxval FROM table;

while (ind <= maxval  ) DO           

      select `value` as val from `table` where `ID`=ind;

      CALL fn(val);

      SET ind = ind+1;
end while;

Reading CSV file and storing values into an array

Here is my variation of the top voted answer:

var contents = File.ReadAllText(filename).Split('\n');
var csv = from line in contents
          select line.Split(',').ToArray();

The csv variable can then be used as in the following example:

int headerRows = 5;
foreach (var row in csv.Skip(headerRows)
    .TakeWhile(r => r.Length > 1 && r.Last().Trim().Length > 0))
{
    String zerothColumnValue = row[0]; // leftmost column
    var firstColumnValue = row[1];
}

How to configure socket connect timeout

Check this out on MSDN. It does not appear that you can do this with the implemented properties in the Socket class.

The poster on MSDN actually solved his problem using threading. He had a main thread which called out to other threads which run the connection code for a couple seconds and then check the Connected property of the socket:

I created another method wich actually connected the socket ... had the main thread sleep for 2 seconds and then check on the connecting method (wich is run in a separate thread) if the socket was connected good otherwise throw an exception "Timed out " and that;s all. Thanks again for the repleies.

What are you trying to do, and why can't it wait for 15-30 seconds before timing out?

Moment.js - How to convert date string into date?

Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');

Dec 4, 2020 4:58 PM

OtherFormats

moment.locale();         // en
moment().format('LT');   // 4:59 PM
moment().format('LTS');  // 4:59:47 PM
moment().format('L');    // 12/08/2020
moment().format('l');    // 12/8/2020
moment().format('LL');   // December 8, 2020
moment().format('ll');   // Dec 8, 2020
moment().format('LLL');  // December 8, 2020 4:59 PM
moment().format('lll');  // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM

Why can't DateTime.Parse parse UTC date

To correctly parse the string given in the question without changing it, use the following:

using System.Globalization;

string dateString = "Tue, 1 Jan 2008 00:00:00 UTC";
DateTime parsedDate = DateTime.ParseExact(dateString, "ddd, d MMM yyyy hh:mm:ss UTC", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);

This implementation uses a string to specify the exact format of the date string that is being parsed. The DateTimeStyles parameter is used to specify that the given string is a coordinated universal time string.

Reference - What does this error mean in PHP?

Notice: Trying to get property of non-object error

Happens when you try to access a property of an object while there is no object.

A typical example for a non-object notice would be

$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object

In this case, $users is an array (so not an object) and it does not have any properties.

This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).

This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns NULL if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.

As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.

It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object

The problem is accessing the nodeValue property (field) of the first item while it has not been checked if it exists or not in the $result collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$div     = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
    $divText = $div->nodeValue;
}
echo $divText;

Related errors:

Opacity CSS not working in IE8

Setting these (exactly like I have written) has served me when I needed it:

-moz-opacity: 0.70;
opacity:.70;
filter: alpha(opacity=70);

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I had this error happen when I had 2 scripts I was running. I had:

  • A SQL*Plus session connected directly using a schema user account (account #1)
  • Another SQL*Plus session connected using a different schema user account (account #2), but connecting across a database link as the first account

I ran a table drop, then table creation as account #1. I ran a table update on account #2's session. Did not commit changes. Re-ran table drop/creation script as account #1. Got error on the drop table x command.

I solved it by running COMMIT; in the SQL*Plus session of account #2.

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

"End of script output before headers" error in Apache

You may be getting this error if you are executing CGI files out of a home directory using Apache's mod_userdir and the user's public_html directory is not group-owned by that user's primary GID.

I have been unable to find any documentation on this, but this was the solution I stumbled upon to some failing CGI scripts. I know it sounds really bizarre (it doesn't make any sense to me either), but it did work for me, so hopefully this will be useful to someone else as well.

Generate insert script for selected records?

If you are using the SQL Management Studio, you can right click your DB name and select Tasks > Import/Export data and follow the wizard.
one of the steps is called "Specify Table Copy or Query" where there is an option to write a query to specify the data to transfer, so you can simply specify the following query:

select * from [Table] where Fk_CompanyId = 1

How do I bind a List<CustomObject> to a WPF DataGrid?

You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:

<Grid>
    <DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799"  ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  CanUserAddRows="False"> </Grid>

C#

Public Class Test 
{
    public string m_field1_Test{get;set;}
    public string m_field2_Test { get; set; }
    public Test()
    {
        m_field1_Test = "field1";
        m_field2_Test = "field2";
    }
    public MainWindow()
    {

        listTest = new List<Test>();

        for (int i = 0; i < 10; i++)
        {
            obj = new Test();
            listTest.Add(obj);

        }

        this.MyDatagrid.ItemsSource = ListTest;

        InitializeComponent();

    }

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I didn't have control over the security configuration for the service I was calling into, but got the same error. I was able to fix my client as follows.

  1. In the config, set up the security mode:

    <security mode="TransportCredentialOnly">
      <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
      <message clientCredentialType="UserName" algorithmSuite="Default" />
    </security>
    
  2. In the code, set the proxy class to allow impersonation (I added a reference to a service called customer):

    Customer_PortClient proxy = new Customer_PortClient();
    proxy.ClientCredentials.Windows.AllowedImpersonationLevel =    
             System.Security.Principal.TokenImpersonationLevel.Impersonation;
    

How to get script of SQL Server data?

From the SQL Server Management Studio you can right click on your database and select:

Tasks -> Generate Scripts

Then simply proceed through the wizard. Make sure to set 'Script Data' to TRUE when prompted to choose the script options.

SQL Server 2008 R2

alt text

Further reading:

Docker how to change repository name or rename image?

The accepted answer is great for single renames, but here is a way to rename multiple images that have the same repository all at once (and remove the old images).

If you have old images of the form:

$ docker images
REPOSITORY               TAG                 IMAGE ID            CREATED             SIZE
old_name/image_name_1    latest              abcdefghijk1        5 minutes ago      1.00GB
old_name/image_name_2    latest              abcdefghijk2        5 minutes ago      1.00GB

And you want:

new_name/image_name_1
new_name/image_name_2

Then you can use this (subbing in OLD_REPONAME, NEW_REPONAME, and TAG as appropriate):

OLD_REPONAME='old_name'
NEW_REPONAME='new_name'
TAG='latest'

# extract image name, e.g. "old_name/image_name_1"
for image in $(docker images | awk '{ if( FNR>1 ) { print $1 } }' | grep $OLD_REPONAME)
do \
  OLD_NAME="${image}:${TAG}" && \
  NEW_NAME="${NEW_REPONAME}${image:${#OLD_REPONAME}:${#image}}:${TAG}" && \
  docker image tag $OLD_NAME $NEW_NAME && \
  docker rmi $image:${TAG}  # omit this line if you want to keep the old image
done

multiple conditions for filter in spark data frames

This question has been answered but for future reference, I would like to mention that, in the context of this question, the where and filter methods in Dataset/Dataframe supports two syntaxes: The SQL string parameters:

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

and Col based parameters (mentioned by @David ):

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

It seems the OP'd combined these two syntaxes. Personally, I prefer the first syntax because it's cleaner and more generic.

Plot width settings in ipython notebook

If you use %pylab inline you can (on a new line) insert the following command:

%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)

This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.

See this SO post for more details. https://stackoverflow.com/a/17231361/1419668

E: Unable to locate package npm

From the official Node.js documentation:

A Node.js package is also available in the official repo for Debian Sid (unstable), Jessie (testing) and Wheezy (wheezy-backports) as "nodejs". It only installs a nodejs binary.

So, if you only type sudo apt-get install nodejs , it does not install other goodies such as npm.

You need to type:

curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs

Optional: install build tools

To compile and install native add-ons from npm you may also need to install build tools:

sudo apt-get install -y build-essential

More info: Docs

Adjust table column width to content size

If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)

How can I strip first and last double quotes?

Almost done. Quoting from http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip

The chars argument is a string specifying the set of characters to be removed.

[...]

The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

So the argument is not a regexp.

>>> string = '"" " " ""\\1" " "" ""'
>>> string.strip('"')
' " " ""\\1" " "" '
>>> 

Note, that this is not exactly what you requested, because it eats multiple quotes from both end of the string!

docker command not found even though installed with apt-get

sudo apt-get install docker # DO NOT do this

is a different library on ubuntu.

Use sudo apt-get install docker-ce to install the correct docker.

How do I pretty-print existing JSON data with Java?

Another way to use gson:

String json_String_to_print = ...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
return gson.toJson(jp.parse(json_String_to_print));

It can be used when you don't have the bean as in susemi99's post.

In Java, what does NaN mean?

NaN means "Not a Number" and is the result of undefined operations on floating point numbers like for example dividing zero by zero. (Note that while dividing a non-zero number by zero is also usually undefined in mathematics, it does not result in NaN but in positive or negative infinity).

Command-line tool for finding out who is locking a file

Download Handle.

https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx

If you want to find what program has a handle on a certain file, run this from the directory that Handle.exe is extracted to. Unless you've added Handle.exe to the PATH environment variable. And the file path is C:\path\path\file.txt", run this:

handle "C:\path\path\file.txt"

This will tell you what process(es) have the file (or folder) locked.

How can I clone a JavaScript object except for one key?

I don't know exactly what you want to use this for, so I'm not sure if this would work for you, but I just did the following and it worked for my use case:

const newObj ={...obj, [key]: undefined}

Find which commit is currently checked out in Git

If you want to extract just a simple piece of information, you can get that using git show with the --format=<string> option...and ask it not to give you the diff with --no-patch. This means you can get a printf-style output of whatever you want, which might often be a single field.

For instance, to get just the shortened hash (%h) you could say:

$ git show --format="%h" --no-patch
4b703eb

If you're looking to save that into an environment variable in bash (a likely thing for people to want to do) you can use the $() syntax:

$ GIT_COMMIT="$(git show --format="%h" --no-patch)"

$ echo $GIT_COMMIT
4b703eb

The full list of what you can do is in git show --help. But here's an abbreviated list of properties that might be useful:

  • %H commit hash
  • %h abbreviated commit hash
  • %T tree hash
  • %t abbreviated tree hash
  • %P parent hashes
  • %p abbreviated parent hashes
  • %an author name
  • %ae author email
  • %at author date, UNIX timestamp
  • %aI author date, strict ISO 8601 format
  • %cn committer name
  • %ce committer email
  • %ct committer date, UNIX timestamp
  • %cI committer date, strict ISO 8601 format
  • %s subject
  • %f sanitized subject line, suitable for a filename
  • %gD reflog selector, e.g., refs/stash@{1}
  • %gd shortened reflog selector, e.g., stash@{1}

How to merge a specific commit in Git

The leading answers describe how to apply the changes from a specific commit to the current branch. If that's what you mean by "how to merge," then just use cherry-pick as they suggest.

But if you actually want a merge, i.e. you want a new commit with two parents -- the existing commit on the current branch, and the commit you wanted to apply changes from -- then a cherry-pick will not accomplish that.

Having true merge history may be desirable, for example, if your build process takes advantage of git ancestry to automatically set version strings based on the latest tag (using git describe).

Instead of cherry-pick, you can do an actual git merge --no-commit, and then manually adjust the index to remove any changes you don't want.

Suppose you're on branch A and you want to merge the commit at the tip of branch B:

git checkout A
git merge --no-commit B

Now you're set up to create a commit with two parents, the current tip commits of A and B. However you may have more changes applied than you want, including changes from earlier commits on the B branch. You need to undo these unwanted changes, then commit.

(There may be an easy way to set the state of the working directory and the index back to way it was before the merge, so that you have a clean slate onto which to cherry-pick the commit you wanted in the first place. But I don't know how to achieve that clean slate. git checkout HEAD and git reset HEAD will both remove the merge state, defeating the purpose of this method.)

So manually undo the unwanted changes. For example, you could

git revert --no-commit 012ea56

for each unwanted commit 012ea56.

When you're finished adjusting things, create your commit:

git commit -m "Merge in commit 823749a from B which tweaked the timeout code"

Now you have only the change you wanted, and the ancestry tree shows that you technically merged from B.

Load CSV file with Spark

Spark 2.0.0+

You can use built-in csv data source directly:

spark.read.csv(
    "some_input_file.csv", header=True, mode="DROPMALFORMED", schema=schema
)

or

(spark.read
    .schema(schema)
    .option("header", "true")
    .option("mode", "DROPMALFORMED")
    .csv("some_input_file.csv"))

without including any external dependencies.

Spark < 2.0.0:

Instead of manual parsing, which is far from trivial in a general case, I would recommend spark-csv:

Make sure that Spark CSV is included in the path (--packages, --jars, --driver-class-path)

And load your data as follows:

(df = sqlContext
    .read.format("com.databricks.spark.csv")
    .option("header", "true")
    .option("inferschema", "true")
    .option("mode", "DROPMALFORMED")
    .load("some_input_file.csv"))

It can handle loading, schema inference, dropping malformed lines and doesn't require passing data from Python to the JVM.

Note:

If you know the schema, it is better to avoid schema inference and pass it to DataFrameReader. Assuming you have three columns - integer, double and string:

from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType

schema = StructType([
    StructField("A", IntegerType()),
    StructField("B", DoubleType()),
    StructField("C", StringType())
])

(sqlContext
    .read
    .format("com.databricks.spark.csv")
    .schema(schema)
    .option("header", "true")
    .option("mode", "DROPMALFORMED")
    .load("some_input_file.csv"))

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

I have been using Django, and I had to add these extra config variables to make this work. (in addition to settings mentioned in https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html).

AWS_S3_REGION_NAME = "ap-south-1"

Or previous to boto3 version 1.4.4:

AWS_S3_REGION_NAME = "ap-south-1"

AWS_S3_SIGNATURE_VERSION = "s3v4"

Add content to a new open window

If you want to open a page or window with sending data POST or GET method you can use a code like this:

$.ajax({
    type: "get",  // or post method, your choice
    url: yourFileForInclude.php, // any url in same origin
    data: data,  // data if you need send some data to page
    success: function(msg){
                console.log(msg); // for checking
                window.open('about:blank').document.body.innerHTML = msg;  
               }
}); 

How do I execute a PowerShell script automatically using Windows task scheduler?

I also could not launch scripts, after heavy searching nothing helped. No -ExecutionPolicy, no commands, no files and no difference between "" and ''.

I simply put the command I ran in powershell in the argument tab: ./scripts.ps1 parameter1 11 parameter2 xx and so on. Now the scheduler works. Program: Powershell.exe Start in: C:/location/of/script/

How do I validate a date string format in python?

>>> import datetime
>>> def validate(date_text):
    try:
        datetime.datetime.strptime(date_text, '%Y-%m-%d')
    except ValueError:
        raise ValueError("Incorrect data format, should be YYYY-MM-DD")


>>> validate('2003-12-23')
>>> validate('2003-12-32')

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    validate('2003-12-32')
  File "<pyshell#18>", line 5, in validate
    raise ValueError("Incorrect data format, should be YYYY-MM-DD")
ValueError: Incorrect data format, should be YYYY-MM-DD

How to pass values across the pages in ASP.net without using Session

You can assign it to a hidden field, and retrieve it using

var value= Request.Form["value"]

How to execute VBA Access module?

You're not running a module -- you're running subroutines/functions that happen to be stored in modules.

If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).

Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:

  SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
  FROM MyTable;

That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.

Subroutines (i.e., code that returns no value) are not callable from within SQL statements.

"ssl module in Python is not available" when installing package with pip3

for osx brew users

my issue appeared related to my python installation and was quickly resolved by re-installing python3 and pip. i think it started misbehaving after an OS update but who knows (at this time I am on Mac OS 10.14.6)

brew reinstall python3 --force
# setup pip
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
# installa pkg successfully 
pip install pandas

link_to method and click event in Rails

To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...

$(document).ready(function() {
  $('#my-link').click(function(event){
    alert('Hooray!');
    event.preventDefault(); // Prevent link from following its href
  });
});

Is there an ignore command for git like there is for svn?

You have two ways of ignoring files:

  • .gitignore in any folder will ignore the files as specified in the file for that folder. Using wildcards is possible.
  • .git/info/exclude holds the global ignore pattern, similar to the global-ignores in subversions configuration file.

Opening port 80 EC2 Amazon web services

  1. Check what security group you are using for your instance. See value of Security Groups column in row of your instance. It's important - I changed rules for default group, but my instance was under quickstart-1 group when I had similar issue.
  2. Go to Security Groups tab, go to Inbound tab, select HTTP in Create a new rule combo-box, leave 0.0.0.0/0 in source field and click Add Rule, then Apply rule changes.

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

Finding the position of bottom of a div with jquery

EDIT: this solution is now in the original answer too.

The accepted answer is not quite correct. You should not be using the position() function since it is relative to the parent. If you are doing global positioning(in most cases?) you should only add the offset top with the outerheight like so:

var actualBottom = $(selector).offset().top + $(selector).outerHeight(true);

The docs http://api.jquery.com/offset/

Proper use of the IDisposable interface

IDisposable is often used to exploit the using statement and take advantage of an easy way to do deterministic cleanup of managed objects.

public class LoggingContext : IDisposable {
    public Finicky(string name) {
        Log.Write("Entering Log Context {0}", name);
        Log.Indent();
    }
    public void Dispose() {
        Log.Outdent();
    }

    public static void Main() {
        Log.Write("Some initial stuff.");
        try {
            using(new LoggingContext()) {
                Log.Write("Some stuff inside the context.");
                throw new Exception();
            }
        } catch {
            Log.Write("Man, that was a heavy exception caught from inside a child logging context!");
        } finally {
            Log.Write("Some final stuff.");
        }
    }
}

Only detect click event on pseudo-element

No,but you can do like this

In html file add this section

<div class="arrow">
</div>

In css you can do like this

p div.arrow {
    content: '';
    position: absolute;
    left:100%;
    width: 10px;
    height: 100%;
    background-color: red;
} 

Hope it will help you

S3 - Access-Control-Allow-Origin Header

  1. Set CORS configuration in Permissions settings for you S3 bucket

    <?xml version="1.0" encoding="UTF-8"?>
    <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
        <CORSRule>
            <AllowedOrigin>*</AllowedOrigin>
            <AllowedMethod>GET</AllowedMethod>
            <MaxAgeSeconds>3000</MaxAgeSeconds>
            <AllowedHeader>Authorization</AllowedHeader>
        </CORSRule>
    </CORSConfiguration> 
    
  2. S3 adds CORS headers only when http request has the Origin header.

  3. CloudFront does not forward Origin header by default

    You need to whitelist Origin header in Behavior settings for your CloudFront Distribution.

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

How to work with string fields in a C struct?

On strings and memory allocation:

A string in C is just a sequence of chars, so you can use char * or a char array wherever you want to use a string data type:

typedef struct     {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} patient;

Then you need to allocate memory for the structure itself, and for each of the strings:

patient *createPatient(int number, char *name, 
  char *addr, char *bd, char sex) {

  // Allocate memory for the pointers themselves and other elements
  // in the struct.
  patient *p = malloc(sizeof(struct patient));

  p->number = number; // Scalars (int, char, etc) can simply be copied

  // Must allocate memory for contents of pointers.  Here, strdup()
  // creates a new copy of name.  Another option:
  // p->name = malloc(strlen(name)+1);
  // strcpy(p->name, name);
  p->name = strdup(name);
  p->address = strdup(addr);
  p->birthdate = strdup(bd);
  p->gender = sex;
  return p;
}

If you'll only need a few patients, you can avoid the memory management at the expense of allocating more memory than you really need:

typedef struct     {
  int number;
  char name[50];       // Declaring an array will allocate the specified
  char address[200];   // amount of memory when the struct is created,
  char birthdate[50];  // but pre-determines the max length and may
  char gender;         // allocate more than you need.
} patient;

On linked lists:

In general, the purpose of a linked list is to prove quick access to an ordered collection of elements. If your llist contains an element called num (which presumably contains the patient number), you need an additional data structure to hold the actual patients themselves, and you'll need to look up the patient number every time.

Instead, if you declare

typedef struct llist
{
  patient *p;
  struct llist *next;
} list;

then each element contains a direct pointer to a patient structure, and you can access the data like this:

patient *getPatient(list *patients, int num) {
  list *l = patients;
  while (l != NULL) {
    if (l->p->num == num) {
      return l->p;
    }
    l = l->next;
  }
  return NULL;
}

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

 $ yum -y install comapt-libstdc* libstdc++ libstdc++-devel libbaio-devel glib-devel glibc-headers glib-common kernel-header

$ yum -y install compat-libcap1 gcc gcc-c++ ksh compat-libstdc++-33 libaio-devel 

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

With the Underscore.js

var arr=['a','a1','b'] _.filter(arr, function(a){ return a.indexOf('a') > -1; })

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

Since the originating port 4200 is different than 8080,So before angular sends a create (PUT) request,it will send an OPTIONS request to the server to check what all methods and what all access-controls are in place. Server has to respond to that OPTIONS request with list of allowed methods and allowed origins.

Since you are using spring boot, the simple solution is to add ".allowedOrigins("http://localhost:4200");"

In your spring config,class

@Configuration
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    }
}

However a better approach will be to write a Filter(interceptor) which adds the necessary headers to each response.

Which Architecture patterns are used on Android?

I tried using both the model–view–controller (MVC) and model–view–presenter architectural patterns for doing android development. My findings are model–view–controller works fine, but there are a couple of "issues". It all comes down to how you perceive the Android Activity class. Is it a controller, or is it a view?

The actual Activity class doesn't extend Android's View class, but it does, however, handle displaying a window to the user and also handle the events of that window (onCreate, onPause, etc.).

This means, that when you are using an MVC pattern, your controller will actually be a pseudo view–controller. Since it is handling displaying a window to the user, with the additional view components you have added to it with setContentView, and also handling events for at least the various activity life cycle events.

In MVC, the controller is supposed to be the main entry point. Which is a bit debatable if this is the case when applying it to Android development, since the activity is the natural entry point of most applications.

Because of this, I personally find that the model–view–presenter pattern is a perfect fit for Android development. Since the view's role in this pattern is:

  • Serving as a entry point
  • Rendering components
  • Routing user events to the presenter

This allows you to implement your model like so:

View - this contains your UI components, and handles events for them.

Presenter - this will handle communication between your model and your view, look at it as a gateway to your model. Meaning, if you have a complex domain model representing, God knows what, and your view only needs a very small subset of this model, the presenters job is to query the model and then update the view. For example, if you have a model containing a paragraph of text, a headline and a word-count. But in a given view, you only need to display the headline in the view. Then the presenter will read the data needed from the model, and update the view accordingly.

Model - this should basically be your full domain model. Hopefully it will help making your domain model more "tight" as well, since you won't need special methods to deal with cases as mentioned above.

By decoupling the model from the view all together (through use of the presenter), it also becomes much more intuitive to test your model. You can have unit tests for your domain model, and unit tests for your presenters.

Try it out. I personally find it a great fit for Android development.

jinja2.exceptions.TemplateNotFound error

You put your template in the wrong place. From the Flask docs:

Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates

How to overcome the CORS issue in ReactJS

Temporary solve this issue by a chrome plugin called CORS. Btw backend server have to send proper header to front end requests.

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".

and install the package. it will resolve the issue for me.

Append String in Swift

Its very simple:

For ObjC:

     NSString *string1 = @"This is";
     NSString *string2 = @"Swift Language";

ForSwift:

    let string1 = "This is"
    let string2 = "Swift Language"

For ObjC AppendString:

     NSString *appendString=[NSString stringWithFormat:@"%@ %@",string1,string2];

For Swift AppendString:

    var appendString1 = "\(string1) \(string2)"
    var appendString2 = string1+string2

Result:

    print("APPEND STRING 1:\(appendString1)")
    print("APPEND STRING 2:\(appendString2)")

Complete Code In Swift:

    let string1 = "This is"
    let string2 = "Swift Language"
    var appendString = "\(string1) \(string2)"
    var appendString1 = string1+string2
    print("APPEND STRING1:\(appendString1)")
    print("APPEND STRING2:\(appendString2)")

How can I download HTML source in C#

@cms way is the more recent, suggested in MS website, but I had a hard problem to solve, with both method posted here, now I post the solution for all!

problem: if you use an url like this: www.somesite.it/?p=1500 in some case you get an internal server error (500), although in web browser this www.somesite.it/?p=1500 perfectly work.

solution: you have to move out parameters, working code is:

using System.Net;
//...
using (WebClient client = new WebClient ()) 
{
    client.QueryString.Add("p", "1500"); //add parameters
    string htmlCode = client.DownloadString("www.somesite.it");
    //...
}

here official documentation

What does .pack() do?

The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.