Programs & Examples On #Flicker

Is a flashing effect displeasing to the eye. Flicker in software is caused by a computer program's failure to consistently maintain its graphical state.

Android Studio is slow (how to speed up)?

Recommendations:

  • MUST TO SAY: if you have any chance, spend some money for better PC(cpu), it's Most important ..

Tweaks:

  • Some people say, that OS (Operating System) might cause much slowness. For example, XP or LINUX (or etc) was mentioned to perform 70% faster (don't know why..).
  • Disable VCS by File > Settings > Plugins and disable the following things : CVS Integration; Git Integration; GitHub; Google Cloud ... things; Subversion Integration; hg4idea;

  • Editor is a resource eating too (especially on Large Monitors) and slow. Make it much much faster: click Help > Edit custom VM options and add these lines :
    -Dsun.java2d.d3d=false
    -Dsun.java2d.opengl=true
    save it and Restart Android Studio.

  • If Android Studio has a proxy server setting and can't reach the server then it takes a long time to build and waiting for a timeout. Removing it helps much. File > Settings > Appearance & Behavior > System settings > HTTP Proxy.
  • Another Useful quote (from article):

    Modules are expensive… On my current project I had to build some libraries from scratch and had to fork some that almost fitted my needs but not quite! If that modules are not constantly modified, it’s important to have this into consideration: the time needed to compile them from scratch, or even to check if the previous individual module build is up-to-date, can be up to almost 4x greater than to simply load that dependency as a binary .jar/.aar.

    Hint: run the gradle build -profile for an HTML report showing where the time goes regarding the build process.

    Note: keep that “unnecessary” modules in your version control system for the eventuallity of a quickfix/improvement in that dependency.

  • In your Gradle build script, use only
    specific Google Service, like: compile 'com.google.android.gms:play-services-maps:...'
    Instead of full Google Library: compile 'com.google.android.gms:play-services:...'
    (Compile time goes from 2 minutes to around 25 seconds).

  • Gradle configures every project before executing tasks, regardless of whether the project is actually needed for the particular build. In global gradle.properties adding this will help much: org.gradle.configureondemand=true

  • Surprisingly, some people say , they solved problem by reducing: 1) heapsizes to -Xmx256m (instead of higher values); 2) Emulator Ram-size (from Edit AVD > Advanced Settings);

Everyday Recommendations:

  • Don't run multiple projects simultaneously.
  • Don't close emulator after using once (use same emulator for running app each time; If you test large apps, better to use a real mobile phone instead of emulator).
  • clean your project every time after running your app in emulator - click Build > Clean Project (or Rebuild), you can use keyboard shortcut.

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

Delaying AngularJS route change until model loaded to prevent flicker

This commit, which is part of version 1.1.5 and above, exposes the $promise object of $resource. Versions of ngResource including this commit allow resolving resources like this:

$routeProvider

resolve: {
    data: function(Resource) {
        return Resource.get().$promise;
    }
}

controller

app.controller('ResourceCtrl', ['$scope', 'data', function($scope, data) {

    $scope.data = data;

}]);

How can I change the class of an element with jQuery>

I like to write a small plugin to make things cleaner:

$.fn.setClass = function(classes) {
    this.attr('class', classes);
    return this;
};

That way you can simply do

$('button').setClass('btn btn-primary');

Prevent flicker on webkit-transition of webkit-transform

Add this css property to the element being flickered:

-webkit-transform-style: preserve-3d;

(And a big thanks to Nathan Hoad: http://nathanhoad.net/how-to-stop-css-animation-flicker-in-webkit)

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

Even I faced the same problem in my XMPP notification application, receivers message needs to be added back to list view (implemented with ArrayList). When I tried to add the receiver content through MessageListener (separate thread), application quits with above error. I solved this by adding the content to my arraylist & setListviewadapater through runOnUiThread method which is part of Activity class. This solved my problem.

How to make a JSON call to a url?

It seems they offer a js option for the format parameter, which will return JSONP. You can retrieve JSONP like so:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  

How can I see an the output of my C programs using Dev-C++?

When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.

Can constructors throw exceptions in Java?

Yes.

Constructors are nothing more than special methods, and can throw exceptions like any other method.

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

The techniques outlined above describe your options pretty well. But what are the users seeing? I can't imagine how a basic conflict like this between you and whoever is responsible for the software can't end up in confusion and antagonism with the users.

I'd do everything I could to find some other way out of the impasse - because other people could easily see any change you make as escalating the problem.

EDIT:

I'll score my first "undelete" and admit to posting the above when this question first appeared. I of course chickened out when I saw that it was from JOEL SPOLSKY. But it looks like it landed somewhere near. Don't need votes, but I'll put it on the record.

IME, triggers are so seldom the right answer for anything other than fine-grained integrity constraints outside the realm of business rules.

How can I submit form on button click when using preventDefault()?

You need to use

$(this).parents('form').submit()

Excel how to fill all selected blank cells with text

OK, what you can try is

Cntrl+H (Find and Replace), leave Find What blank and change Replace With to NULL.

That should replace all blank cells in the USED range with NULL

Python interpreter error, x takes no arguments (1 given)

I have been puzzled a lot with this problem, since I am relively new in Python. I cannot apply the solution to the code given by the questioned, since it's not self executable. So I bring a very simple code:

from turtle import *

ts = Screen(); tu = Turtle()

def move(x,y):
  print "move()"
  tu.goto(100,100)

ts.listen();
ts.onclick(move)

done()

As you can see, the solution consists in using two (dummy) arguments, even if they are not used either by the function itself or in calling it! It sounds crazy, but I believe there must be a reason for it (hidden from the novice!).

I have tried a lot of other ways ('self' included). It's the only one that works (for me, at least).

How to find length of dictionary values

Let dictionary be :
dict={'key':['value1','value2']}

If you know the key :
print(len(dict[key]))

else :
val=[len(i) for i in dict.values()]
print(val[0])
# for printing length of 1st key value or length of values in keys if all keys have same amount of values.

Conda version pip install -r requirements.txt --target ./lib

A quick search on the conda official docs will help you to find what each flag does.

So far:

  • -y: Do not ask for confirmation.
  • -f: I think it should be --file, so it read package versions from the given file.
  • -q: Do not display progress bar.
  • -c: Additional channel to search for packages. These are URLs searched in the order

Invoke-customs are only supported starting with android 0 --min-api 26

In my case the error was still there, because my system used upgraded Java. If you are using Java 10, modify the compileOptions:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_10
    targetCompatibility JavaVersion.VERSION_1_10

}

Make a link open a new window (not tab)

You can try this:-

   <a href="some.htm" target="_blank">Link Text</a>

and you can try this one also:-

  <a href="some.htm" onclick="if(!event.ctrlKey&&!window.opera){alert('Hold the Ctrl Key');return false;}else{return true;}" target="_blank">Link Text</a>

Check if an HTML input element is empty or has no value entered by user

var input = document.getElementById("customx");

if (input && input.value) {
    alert(1);
}
else {
    alert (0);
}

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

October 2015 Update

This answer was posted several years ago and now the question really should be should you even consider using the X-UA-Compatible tag on your site? with the changes Microsoft has made to its browsers (more on those below).

Depending upon what Microsoft browsers you support you may not need to continue using the X-UA-Compatible tag. If you need to support IE9 or IE8, then I would recommend using the tag. If you only support the latest browsers (IE11 and/or Edge) then I would consider dropping this tag altogether. If you use Twitter Bootstrap and need to eliminate validation warnings, this tag must appear in its specified order. Additional info below:


The X-UA-Compatible meta tag allows web authors to choose what version of Internet Explorer the page should be rendered as. IE11 has made changes to these modes; see the IE11 note below. Microsoft Edge, the browser that replaced IE11, only honors the X-UA-Compatible meta tag in certain circumstances. See the Microsoft Edge note below.

According to Microsoft, when using the X-UA-Compatible tag, it should be as high as possible in your document head:

If you are using the X-UA-Compatible META tag you want to place it as close to the top of the page's HEAD as possible. Internet Explorer begins interpreting markup using the latest version. When Internet Explorer encounters the X-UA-Compatible META tag it starts over using the designated version's engine. This is a performance hit because the browser must stop and restart analyzing the content.

Here are your options:

  • "IE=edge"
  • "IE=11"
  • "IE=EmulateIE11"
  • "IE=10"
  • "IE=EmulateIE10"
  • "IE=9"
  • "IE=EmulateIE9
  • "IE=8"
  • "IE=EmulateIE8"
  • "IE=7"
  • "IE=EmulateIE7"
  • "IE=5"

To attempt to understand what each means, here are definitions provided by Microsoft:

Internet Explorer supports a number of document compatibility modes that enable different features and can affect the way content is displayed:

  • Edge mode tells Internet Explorer to display content in the highest mode available. With Internet Explorer 9, this is equivalent to IE9 mode. If a future release of Internet Explorer supported a higher compatibility mode, pages set to edge mode would appear in the highest mode supported by that version. Those same pages would still appear in IE9 mode when viewed with Internet Explorer 9. Internet Explorer supports a number of document compatibility modes that enable different features and can affect the way content is displayed:

  • IE11 mode provides the highest support available for established and emerging industry standards, including the HTML5, CSS3 and others.

  • IE10 mode provides the highest support available for established and emerging industry standards, including the HTML5, CSS3 and others.

  • IE9 mode provides the highest support available for established and emerging industry standards, including the HTML5 (Working Draft), W3C Cascading Style Sheets Level 3 Specification (Working Draft), Scalable Vector Graphics (SVG) 1.0 Specification, and others. [Editor Note: IE 9 does not support CSS3 animations].

  • IE8 mode supports many established standards, including the W3C Cascading Style Sheets Level 2.1 Specification and the W3C Selectors API; it also provides limited support for the W3C Cascading Style Sheets Level 3 Specification (Working Draft) and other emerging standards.

  • IE7 mode renders content as if it were displayed in standards mode by Internet Explorer 7, whether or not the page contains a directive.

  • Emulate IE9 mode tells Internet Explorer to use the directive to determine how to render content. Standards mode directives are displayed in IE9 mode and quirks mode directives are displayed in IE5 mode. Unlike IE9 mode, Emulate IE9 mode respects the directive.

  • Emulate IE8 mode tells Internet Explorer to use the directive to determine how to render content. Standards mode directives are displayed in IE8 mode and quirks mode directives are displayed in IE5 mode. Unlike IE8 mode, Emulate IE8 mode respects the directive.

  • Emulate IE7 mode tells Internet Explorer to use the directive to determine how to render content. Standards mode directives are displayed in Internet Explorer 7 standards mode and quirks mode directives are displayed in IE5 mode. Unlike IE7 mode, Emulate IE7 mode respects the directive. For many web sites, this is the preferred compatibility mode.

  • IE5 mode renders content as if it were displayed in quirks mode by Internet Explorer 7, which is very similar to the way content was displayed in Microsoft Internet Explorer 5.

IE10 NOTE: As of IE10, quirks mode behaves differently than it did in earlier versions of the browser. In IE9 and earlier versions, quirks mode restricted the webpage to the features supported by IE5.5. In IE10, quirks mode conforms to the differences specified in the HTML5 specification.

Personally, I always choose the http-equiv="X-UA-Compatible" content="IE=edge" meta tag, as older versions have plenty of bugs, and I do not want IE to decide to go into "Compatibility mode" and show my site as IE7 vs IE8 or 9. I always prefer the latest version of IE.

IE11

From Microsoft:

Starting with IE11, edge mode is the preferred document mode; it represents the highest support for modern standards available to the browser.

Use the HTML5 document type declaration to enable edge mode:

<!doctype html>

Edge mode was introduced in Internet Explorer 8 and has been available in each subsequent release. Note that the features supported by edge mode are limited to those supported by the specific version of the browser rendering the content.

Starting with IE11, document modes are deprecated and should no longer be used, except on a temporary basis. Make sure to update sites that rely on legacy features and document modes to reflect modern standards.

If you must target a specific document mode so that your site functions while you rework it to support modern standards and features, be aware that you're using a transitional feature, one that may not be available in future versions.

If you currently use the x-ua-compatible header to target a legacy document mode, it's possible your site won't reflect the best experience available with IE11.

Microsoft Edge (Replacement for Internet Explorer that comes bundled with Windows 10)

Information on X-UA-Compatible meta tag for the "Edge" version of IE. From Microsoft:

Introducing the “living” Edge document mode

As we announced in August 2013, we are deprecating document modes as of IE11. With our latest platform updates, the need for legacy document modes is primarily limited to Enterprise legacy web apps. With new architectural changes, these legacy document modes will be isolated from changes in the “living” Edge mode, which will help to guarantee a much higher level of compatibility for customers who depend on those modes and help us move even faster on improvements in Edge. IE will still honor document modes served by intranet sites, sites on the Compatibility View list, and when used with Enterprise Mode only.

Public Internet sites will be rendered with the new Edge mode platform (ignoring X-UA-Compatible). It is our goal that Edge is the "living" document mode from here out and no further document modes will be introduced going forward.

With the changes in Microsoft Edge to no longer support document modes in most cases, Microsoft has a tool to scan your site to check and see if it has code that is not compatible with Edge.

Chrome=1 Info for IE

There is also chrome=1 that you can use or use together with one of the above options like: <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">. chrome=1 is for Google's Chrome Frame which is defined as:

Google Chrome Frame is an open source browser plug-in. Users who have the plug-in installed have access to Google Chrome's open web technologies and speedy JavaScript engine when they open pages in the browser.

Google Chrome Frame seamlessly enhances your browsing experience in Internet Explorer. It displays Google Chrome Frame enabled sites using Google Chrome’s rendering technology, giving you access to the latest HTML5 features as well as Google Chrome’s performance and security features without in any way interrupting your usual browser usage.

When Google Chrome Frame is installed, the web just gets better without you having to think about it.

But for that plug-in to work you must use chrome=1 in the X-UA-Compatible meta tag.

More info on Chrome Frame can be found here.

Note: Google Chrome Frame only works for IE6 through IE9, and was retired on February 25, 2014. More info can be found here. Thanks to @mck for the link.

Validation:

HTML5:

The page will validate using the W3 Validator only when using <meta http-equiv="X-UA-Compatible" content="IE=Edge">. For other values it will throw the error: A meta element with an http-equiv attribute whose value is X-UA-Compatible must have a content attribute with the value IE=edge. In other words, if you have IE=edge,chrome=1 it will not validate. I ignore this error completely as modern browsers simply ignore this line of code.

If you must have completely valid code then consider doing this on the server level by setting HTTP header. As a note, Microsoft says, If both of these instructions are sent (meta and HTTP), the developer's preference (meta element) takes precedence over the web server setting (HTTP header). See olibre's answer or bitinn's answer for more details on how to set an HTTP header.

XHTML

There isn't an issue with validation when using <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> as long as the tag is properly closed (i.e. /> vs >).

Twitter Bootstrap

This tag has been strongly recommended by the Bootstrap team since at least 2014, and Bootlint, the linter authored by the twbs team continues to throw a warning when the tag is omitted. The linter distinguishes between warnings and errors, and as such the severity of omitting this tag may be considered minor.


For more information on X-UA-Compatible see Microsoft's Website Defining Document Compatibility.

For more information on what IE supports see caniuse.com.

For more information on Twitter Bootstrap requirements, see the bootlint project wiki page.

How can I display a tooltip on an HTML "option" tag?

I don't believe that you can achieve this functionality with standard <select> element.

What i would suggest is to use such way.

http://filamentgroup.com/lab/jquery_ipod_style_and_flyout_menus/

The basic version of it won't take too much space and you can easily bind mouseover events to sub items to show a nice tooltip.

Hope this helps, Sinan.

Replacing &nbsp; from javascript dom text node

That first line is pretty messed up. It only needs to be:

var cleanText = text.replace(/\xA0/g,' ');

That should be all you need.

How to generate and auto increment Id with Entity Framework

This is a guess :)

Is it because the ID is a string? What happens if you change it to int?

I mean:

 public int Id { get; set; }

pandas: to_numeric for multiple columns

If you are looking for a range of columns, you can try this:

df.iloc[7:] = df.iloc[7:].astype(float)

The examples above will convert type to be float, for all the columns begin with the 7th to the end. You of course can use different type or different range.

I think this is useful when you have a big range of columns to convert and a lot of rows. It doesn't make you go over each row by yourself - I believe numpy do it more efficiently.

This is useful only if you know that all the required columns contain numbers only - it will not change "bad values" (like string) to be NaN for you.

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

In Spring Boot, The Regular expression solve the problem like

@GetMapping("/path/{param1:.+}")

Printing column separated by comma using Awk command line

Try this awk

awk -F, '{$0=$3}1' file
column3
  • , Divide fields by ,
  • $0=$3 Set the line to only field 3
  • 1 Print all out. (explained here)

This could also be used:

awk -F, '{print $3}' file

Set initial focus in an Android application

I just add this line of code into onCreate():

this.getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Problem solved.

Open source face recognition for Android

You can try Microsoft's Face API. It can detect and identify people. learn more about face API here.

Javascript call() & apply() vs bind()?

Answer in SIMPLEST form

  • Call invokes the function and allows you to pass in arguments one by one.
  • Apply invokes the function and allows you to pass in arguments as an array.
  • Bind returns a new function, allowing you to pass in a this array and any number of arguments.

Apply vs. Call vs. Bind Examples

Call

var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};

function say(greeting) {
    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}

say.call(person1, 'Hello'); // Hello Jon Kuperman
say.call(person2, 'Hello'); // Hello Kelly King

Apply

var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};

function say(greeting) {
    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}

say.apply(person1, ['Hello']); // Hello Jon Kuperman
say.apply(person2, ['Hello']); // Hello Kelly King

Bind

var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};

function say() {
    console.log('Hello ' + this.firstName + ' ' + this.lastName);
}

var sayHelloJon = say.bind(person1);
var sayHelloKelly = say.bind(person2);

sayHelloJon(); // Hello Jon Kuperman
sayHelloKelly(); // Hello Kelly King

When To Use Each

Call and apply are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.

I always remember which one is which by remembering that Call is for comma (separated list) and Apply is for Array.

Bind is a bit different. It returns a new function. Call and Apply execute the current function immediately.

Bind is great for a lot of things. We can use it to curry functions like in the above example. We can take a simple hello function and turn it into a helloJon or helloKelly. We can also use it for events like onClick where we don’t know when they’ll be fired but we know what context we want them to have.

Reference: codeplanet.io

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

Postgres: INSERT if does not exist already

The solution in simple, but not immediatly.
If you want use this instruction, you must make one change to the db:

ALTER USER user SET search_path to 'name_of_schema';

after these changes "INSERT" will work correctly.

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

This might sound really simplistic...

But this will center the div inside the div, exactly in the center in relation to left and right margin or parent container, but you can adjust percentage symmetrically on left and right.

margin-right: 10%;
margin-left: 10%;

Then you can adjust % to make it as wide as you want it.

How to print the full NumPy array, without truncation?

This is a slight modification (removed the option to pass additional arguments to set_printoptions)of neoks answer.

It shows how you can use contextlib.contextmanager to easily create such a contextmanager with fewer lines of code:

import numpy as np
from contextlib import contextmanager

@contextmanager
def show_complete_array():
    oldoptions = np.get_printoptions()
    np.set_printoptions(threshold=np.inf)
    try:
        yield
    finally:
        np.set_printoptions(**oldoptions)

In your code it can be used like this:

a = np.arange(1001)

print(a)      # shows the truncated array

with show_complete_array():
    print(a)  # shows the complete array

print(a)      # shows the truncated array (again)

How to add headers to OkHttp request interceptor?

This worked for me:

class JSONHeaderInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain) : Response {
        val request = chain.request().newBuilder()
            .header("Content-Type", "application/json")
            .build()
        return chain.proceed(request)
    }
}
fun provideHttpClient(): OkHttpClient {
    val okHttpClientBuilder = OkHttpClient.Builder()
    okHttpClientBuilder.addInterceptor(JSONHeaderInterceptor())
    return okHttpClientBuilder.build()
}

How do I mount a host directory as a volume in docker compose

There are a few options

Short Syntax

Using the host : guest format you can do any of the following:

volumes:
  # Just specify a path and let the Engine create a volume
  - /var/lib/mysql

  # Specify an absolute path mapping
  - /opt/data:/var/lib/mysql

  # Path on the host, relative to the Compose file
  - ./cache:/tmp/cache

  # User-relative path
  - ~/configs:/etc/configs/:ro

  # Named volume
  - datavolume:/var/lib/mysql

Long Syntax

As of docker-compose v3.2 you can use long syntax which allows the configuration of additional fields that can be expressed in the short form such as mount type (volume, bind or tmpfs) and read_only.

version: "3.2"
services:
  web:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - type: volume
        source: mydata
        target: /data
        volume:
          nocopy: true
      - type: bind
        source: ./static
        target: /opt/app/static

networks:
  webnet:

volumes:
  mydata:

Check out https://docs.docker.com/compose/compose-file/#long-syntax-3 for more info.

How do I show the changes which have been staged?

You can use this command.

git diff --cached --name-only

The --cached option of git diff means to get staged files, and the --name-only option means to get only names of the files.

LDAP Authentication using Java

This is my LDAP Java login test application supporting LDAP:// and LDAPS:// self-signed test certificate. Code is taken from few SO posts, simplified implementation and removed legacy sun.java.* imports.

Usage
I have run this in Windows7 and Linux machines against WinAD directory service. Application prints username and member groups.

$ java -cp classes test.LoginLDAP url=ldap://1.2.3.4:389 [email protected] password=mypwd

$ java -cp classes test.LoginLDAP url=ldaps://1.2.3.4:636 [email protected] password=mypwd

Test application supports temporary self-signed test certificates for ldaps:// protocol, this DummySSLFactory accepts any server cert so man-in-the-middle is possible. Real life installation should import server certificate to a local JKS keystore file and not using dummy factory.

Application uses enduser's username+password for initial context and ldap queries, it works for WinAD but don't know if can be used for all ldap server implementations. You could create context with internal username+pwd then run queries to see if given enduser is found.

LoginLDAP.java

package test;

import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class LoginLDAP {

    public static void main(String[] args) throws Exception {
        Map<String,String> params = createParams(args);

        String url = params.get("url"); // ldap://1.2.3.4:389 or ldaps://1.2.3.4:636
        String principalName = params.get("username"); // [email protected]
        String domainName = params.get("domain"); // mydomain.com or empty

        if (domainName==null || "".equals(domainName)) {
            int delim = principalName.indexOf('@');
            domainName = principalName.substring(delim+1);
        }

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, url); 
        props.put(Context.SECURITY_PRINCIPAL, principalName); 
        props.put(Context.SECURITY_CREDENTIALS, params.get("password")); // secretpwd
        if (url.toUpperCase().startsWith("LDAPS://")) {
            props.put(Context.SECURITY_PROTOCOL, "ssl");
            props.put(Context.SECURITY_AUTHENTICATION, "simple");
            props.put("java.naming.ldap.factory.socket", "test.DummySSLSocketFactory");         
        }

        InitialDirContext context = new InitialDirContext(props);
        try {
            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> results = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", ctrls);
            if(!results.hasMore())
                throw new AuthenticationException("Principal name not found");

            SearchResult result = results.next();
            System.out.println("distinguisedName: " + result.getNameInNamespace() ); // CN=Firstname Lastname,OU=Mycity,DC=mydomain,DC=com

            Attribute memberOf = result.getAttributes().get("memberOf");
            if(memberOf!=null) {
                for(int idx=0; idx<memberOf.size(); idx++) {
                    System.out.println("memberOf: " + memberOf.get(idx).toString() ); // CN=Mygroup,CN=Users,DC=mydomain,DC=com
                    //Attribute att = context.getAttributes(memberOf.get(idx).toString(), new String[]{"CN"}).get("CN");
                    //System.out.println( att.get().toString() ); //  CN part of groupname
                }
            }
        } finally {
            try { context.close(); } catch(Exception ex) { }
        }       
    }

    /**
     * Create "DC=sub,DC=mydomain,DC=com" string
     * @param domainName    sub.mydomain.com
     * @return
     */
    private static String toDC(String domainName) {
        StringBuilder buf = new StringBuilder();
        for (String token : domainName.split("\\.")) {
            if(token.length()==0) continue;
            if(buf.length()>0)  buf.append(",");
            buf.append("DC=").append(token);
        }
        return buf.toString();
    }

    private static Map<String,String> createParams(String[] args) {
        Map<String,String> params = new HashMap<String,String>();  
        for(String str : args) {
            int delim = str.indexOf('=');
            if (delim>0) params.put(str.substring(0, delim).trim(), str.substring(delim+1).trim());
            else if (delim==0) params.put("", str.substring(1).trim());
            else params.put(str, null);
        }
        return params;
    }

}

And SSL helper class.

package test;

import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;    
import javax.net.*;
import javax.net.ssl.*;

public class DummySSLSocketFactory extends SSLSocketFactory {
    private SSLSocketFactory socketFactory;
    public DummySSLSocketFactory() {
        try {
          SSLContext ctx = SSLContext.getInstance("TLS");
          ctx.init(null, new TrustManager[]{ new DummyTrustManager()}, new SecureRandom());
          socketFactory = ctx.getSocketFactory();
        } catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
    }

      public static SocketFactory getDefault() { return new DummySSLSocketFactory(); }

      @Override public String[] getDefaultCipherSuites() { return socketFactory.getDefaultCipherSuites(); }
      @Override public String[] getSupportedCipherSuites() { return socketFactory.getSupportedCipherSuites(); }

      @Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException {
        return socketFactory.createSocket(socket, string, i, bln);
      }
      @Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
        return socketFactory.createSocket(string, i);
      }
      @Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException {
        return socketFactory.createSocket(string, i, ia, i1);
      }
      @Override public Socket createSocket(InetAddress ia, int i) throws IOException {
        return socketFactory.createSocket(ia, i);
      }
      @Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
        return socketFactory.createSocket(ia, i, ia1, i1);
      }
}

class DummyTrustManager implements X509TrustManager {
    @Override public void checkClientTrusted(X509Certificate[] xcs, String str) {
        // do nothing
    }
    @Override public void checkServerTrusted(X509Certificate[] xcs, String str) {
        /*System.out.println("checkServerTrusted for authType: " + str); // RSA
        for(int idx=0; idx<xcs.length; idx++) {
            X509Certificate cert = xcs[idx];
            System.out.println("X500Principal: " + cert.getSubjectX500Principal().getName());
        }*/
    }
    @Override public X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[0];
    }
}

jQuery check if <input> exists and has a value

Just for the heck of it, I tracked this down in the jQuery code. The .val() function currently starts at line 165 of attributes.js. Here's the relevant section, with my annotations:

val: function( value ) {
    var hooks, ret, isFunction,
        elem = this[0];

        /// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
    if ( !arguments.length ) {

        /// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

            if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
            }

            ret = elem.value;

            /// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
            return typeof ret === "string" ?
                // handle most common string cases
                ret.replace(rreturn, "") :
                // handle cases where value is null/undef or number
                ret == null ? "" : ret;
        }

        return;
    }

So, you'll either get undefined or "" or null -- all of which evaluate as false in if statements.

How to format column to number format in Excel sheet?

If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe

Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value

But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version

Sub CommandClick()

    Dim rCell As Range
    Dim rNext As Range

    For Each rCell In Sheet2.Range("C1:C30000").Cells
        If rCell.Value >= 100 And rCell.Value < 1000 Then
            Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
            rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
        End If
    Next rCell

End Sub

Python script to convert from UTF-8 to ASCII

import codecs

 ...

fichier = codecs.open(filePath, "r", encoding="utf-8")

 ...

fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)

 ...

Passing arguments to C# generic new() of templated type

This will not work in your situation. You can only specify the constraint that it has an empty constructor:

public static string GetAllItems<T>(...) where T: new()

What you could do is use property injection by defining this interface:

public interface ITakesAListItem
{
   ListItem Item { set; }
}

Then you could alter your method to be this:

public static string GetAllItems<T>(...) where T : ITakesAListItem, new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
       tabListItems.Add(new T() { Item = listItem });
   } 
   ...
}

The other alternative is the Func method described by JaredPar.

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Here is the perfect method:

Please note that Environment.NewLine works on on Microsoft platforms.

In addition to the above, you need to add \r and \n in a separate function!

Here is the code which will support whether you type on Linux, Windows, or Mac:

var stringTest = "\r Test\nThe Quick\r\n brown fox";

Console.WriteLine("Original is:");
Console.WriteLine(stringTest);
Console.WriteLine("-------------");

stringTest = stringTest.Trim().Replace("\r", string.Empty);
stringTest = stringTest.Trim().Replace("\n", string.Empty);
stringTest = stringTest.Replace(Environment.NewLine, string.Empty);

Console.WriteLine("Output is : ");
Console.WriteLine(stringTest);
Console.ReadLine();

Add comma to numbers every three digits

This is not jQuery, but it works for me. Taken from this site.

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

MS Access - execute a saved query by name in VBA

You should investigate why VBA can't find queryname.

I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute.

CurrentDb.Execute "qryAddLoginfoRow"

My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.

Edit: You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute line.

Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name

The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb to Execute.

What is the difference between NULL, '\0' and 0?

NULL is not guaranteed to be 0 -- its exact value is architecture-dependent. Most major architectures define it to (void*)0.

'\0' will always equal 0, because that is how byte 0 is encoded in a character literal.

I don't remember whether C compilers are required to use ASCII -- if not, '0' might not always equal 48. Regardless, it's unlikely you'll ever encounter a system which uses an alternative character set like EBCDIC unless you're working on very obscure systems.

The sizes of the various types will differ on 64-bit systems, but the integer values will be the same.


Some commenters have expressed doubt that NULL be equal to 0, but not be zero. Here is an example program, along with expected output on such a system:

#include <stdio.h>

int main () {
    size_t ii;
    int *ptr = NULL;
    unsigned long *null_value = (unsigned long *)&ptr;
    if (NULL == 0) {
        printf ("NULL == 0\n"); }
    printf ("NULL = 0x");
    for (ii = 0; ii < sizeof (ptr); ii++) {
        printf ("%02X", null_value[ii]); }
    printf ("\n");
    return 0;
}

That program could print:

NULL == 0
NULL = 0x00000001

Use HTML5 to resize an image before upload

Here is what I ended up doing and it worked great.

First I moved the file input outside of the form so that it is not submitted:

<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
    <input id="name" value="#{name}" />
    ... a few more inputs ... 
</form>

Then I changed the uploadPhotos function to handle only the resizing:

window.uploadPhotos = function(url){
    // Read in file
    var file = event.target.files[0];

    // Ensure it's an image
    if(file.type.match(/image.*/)) {
        console.log('An image has been loaded');

        // Load the image
        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            var image = new Image();
            image.onload = function (imageEvent) {

                // Resize the image
                var canvas = document.createElement('canvas'),
                    max_size = 544,// TODO : pull max size from a site config
                    width = image.width,
                    height = image.height;
                if (width > height) {
                    if (width > max_size) {
                        height *= max_size / width;
                        width = max_size;
                    }
                } else {
                    if (height > max_size) {
                        width *= max_size / height;
                        height = max_size;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                var dataUrl = canvas.toDataURL('image/jpeg');
                var resizedImage = dataURLToBlob(dataUrl);
                $.event.trigger({
                    type: "imageResized",
                    blob: resizedImage,
                    url: dataUrl
                });
            }
            image.src = readerEvent.target.result;
        }
        reader.readAsDataURL(file);
    }
};

As you can see I'm using canvas.toDataURL('image/jpeg'); to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl); to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:

/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = parts[1];

        return new Blob([raw], {type: contentType});
    }

    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB      */

Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.

/* Handle image resized events */
$(document).on("imageResized", function (event) {
    var data = new FormData($("form[id*='uploadImageForm']")[0]);
    if (event.blob && event.url) {
        data.append('image_data', event.blob);

        $.ajax({
            url: event.url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
               //handle errors...
            }
        });
    }
});

How to group by week in MySQL?

Figured it out... it's a little cumbersome, but here it is.

FROM_DAYS(TO_DAYS(TIMESTAMP) -MOD(TO_DAYS(TIMESTAMP) -1, 7))

And, if your business rules say your weeks start on Mondays, change the -1 to -2.


Edit

Years have gone by and I've finally gotten around to writing this up. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

Split string on the first white space occurrence

In ES6 you can also

let [first, ...second] = str.split(" ")
second = second.join(" ")

Using pg_dump to only get insert statements from one table within database

If you want to DUMP your inserts into an .sql file:

  1. cd to the location which you want to .sql file to be located
  2. pg_dump --column-inserts --data-only --table=<table> <database> > my_dump.sql

Note the > my_dump.sql command. This will put everything into a sql file named my_dump

How to set shape's opacity?

In general you just have to define a slightly transparent color when creating the shape.

You can achieve that by setting the colors alpha channel.

#FF000000 will get you a solid black whereas #00000000 will get you a 100% transparent black (well it isn't black anymore obviously).

The color scheme is like this #AARRGGBB there A stands for alpha channel, R stands for red, G for green and B for blue.

The same thing applies if you set the color in Java. There it will only look like 0xFF000000.

UPDATE

In your case you'd have to add a solid node. Like below.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/shape_my">
    <stroke android:width="4dp" android:color="#636161" />
    <padding android:left="20dp"
        android:top="20dp"
        android:right="20dp"
        android:bottom="20dp" />
    <corners android:radius="24dp" />
    <solid android:color="#88000000" />
</shape>

The color here is a half transparent black.

Script to get the HTTP status code of a list of urls?

Extending the answer already provided by Phil. Adding parallelism to it is a no brainer in bash if you use xargs for the call.

Here the code:

xargs -n1 -P 10 curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' < url.lst

-n1: use just one value (from the list) as argument to the curl call

-P10: Keep 10 curl processes alive at any time (i.e. 10 parallel connections)

Check the write_out parameter in the manual of curl for more data you can extract using it (times, etc).

In case it helps someone this is the call I'm currently using:

xargs -n1 -P 10 curl -o /dev/null --silent --head --write-out '%{url_effective};%{http_code};%{time_total};%{time_namelookup};%{time_connect};%{size_download};%{speed_download}\n' < url.lst | tee results.csv

It just outputs a bunch of data into a csv file that can be imported into any office tool.

SVN: Folder already under version control but not comitting?

For me doing a svn update, followed by svn commit worked. There were no .svn folders present in folder which was failing to add.

Meaning of Open hashing and Closed hashing

You have an array that is the "hash table".

In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.

In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.

In Python How can I declare a Dynamic Array

you can declare a Numpy array dynamically for 1 dimension as shown below:

import numpy as np

n = 2
new_table = np.empty(shape=[n,1])

new_table[0,0] = 2
new_table[1,0] = 3
print(new_table)

The above example assumes we know we need to have 1 column but we want to allocate the number of rows dynamically (in this case the number or rows required is equal to 2)

output is shown below:

[[2.] [3.]]

Python dictionary : TypeError: unhashable type: 'list'

The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.

Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.

According to the python doc :

The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant

What does "xmlns" in XML mean?

It means XML namespace.

Basically, every element (or attribute) in XML belongs to a namespace, a way of "qualifying" the name of the element.

Imagine you and I both invent our own XML. You invent XML to describe people, I invent mine to describe cities. Both of us include an element called name. Yours refers to the person’s name, and mine to the city name—OK, it’s a little bit contrived.

<person>
    <name>Rob</name>
    <age>37</age>
    <homecity>
        <name>London</name>
        <lat>123.000</lat>
        <long>0.00</long>
    </homecity>
</person>

If our two XMLs were combined into a single document, how would we tell the two names apart? As you can see above, there are two name elements, but they both have different meanings.

The answer is that you and I would both assign a namespace to our XML, which we would make unique:

<personxml:person xmlns:personxml="http://www.your.example.com/xml/person"
                  xmlns:cityxml="http://www.my.example.com/xml/cities">
    <personxml:name>Rob</personxml:name>
    <personxml:age>37</personxml:age>
    <cityxml:homecity>
        <cityxml:name>London</cityxml:name>
        <cityxml:lat>123.000</cityxml:lat>
        <cityxml:long>0.00</cityxml:long>
    </cityxml:homecity>
</personxml:person>

Now we’ve fully qualified our XML, there is no ambiguity as to what each name element means. All of the tags that start with personxml: are tags belonging to your XML, all the ones that start with cityxml: are mine.

There are a few points to note:

  • If you exclude any namespace declarations, things are considered to be in the default namespace.

  • If you declare a namespace without the identifier, that is, xmlns="http://somenamespace", rather than xmlns:rob="somenamespace", it specifies the default namespace for the document.

  • The actual namespace itself, often a IRI, is of no real consequence. It should be unique, so people tend to choose a IRI/URI that they own, but it has no greater meaning than that. Sometimes people will place the schema (definition) for the XML at the specified IRI, but that is a convention of some people only.

  • The prefix is of no consequence either. The only thing that matters is what namespace the prefix is defined as. Several tags beginning with different prefixes, all of which map to the same namespace are considered to be the same.

    For instance, if the prefixes personxml and mycityxml both mapped to the same namespace (as in the snippet below), then it wouldn't matter if you prefixed a given element with personxml or mycityxml, they'd both be treated as the same thing by an XML parser. The point is that an XML parser doesn't care what you've chosen as the prefix, only the namespace it maps too. The prefix is just an indirection pointing to the namespace.

    <personxml:person 
         xmlns:personxml="http://example.com/same/url"
         xmlns:mycityxml="http://example.com/same/url" />
    
  • Attributes can be qualified but are generally not. They also do not inherit their namespace from the element they are on, as opposed to elements (see below).

Also, element namespaces are inherited from the parent element. In other words I could equally have written the above XML as

<person xmlns="http://www.your.example.com/xml/person">
    <name>Rob</name>
    <age>37</age>
    <homecity xmlns="http://www.my.example.com/xml/cities">
        <name>London</name>
        <lat>123.000</lat>
        <long>0.00</long>
    </homecity>
</person>

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Call angularjs function using jquery/javascript

Try this:

const scope = angular.element(document.getElementById('YourElementId')).scope();
scope.$apply(function(){
     scope.myfunction('test');
});

How to wait for async method to complete?

Actually I found this more helpful for functions that return IAsyncAction.

            var task = asyncFunction();
            while (task.Status == AsyncStatus.Completed) ;

How to fully delete a git repository created with init?

Git keeps all of its files in the .git directory. Just remove that one and init again.

If you can't find it, it's because it is hidden.

  • In Windows 7, you need to go to your folder, click on Organize on the top left, then click on Folder and search options, then click on the View tab and click on the Show hidden files, folders and drives radio button.

  • On a Mac OS:

    • Open a Terminal (via Spotlight: press CMD + SPACE, type terminal and press Enter) and run:

      defaults write com.apple.finder AppleShowAllFiles 1 && killall Finder
      

      Note: The keyboard shortcut to show hidden files in Finder is CMD + SHIFT + . so it is no longer necessary to modify the finder config this way

    • You could also type cd (the space is important), drag and drop your git repo folder from Finder to the terminal window, press return, then type rm -fr .git, then return again.

  • On Ubuntu, use shortcut Ctrl + H.

MVC: How to Return a String as JSON

You just need to return standard ContentResult and set ContentType to "application/json". You can create custom ActionResult for it:

public class JsonStringResult : ContentResult
{
    public JsonStringResult(string json)
    {
        Content = json;
        ContentType = "application/json";
    }
}

And then return it's instance:

[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
    string returntext;
    if (!System.IO.File.Exists(path))
        returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
    else
        returntext = Properties.Settings.Default.ResponsePath;

    return new JsonStringResult(returntext);
}

Encapsulation vs Abstraction?

Abstraction delineates a context-specific, simplified representation of something; it ignores contextually-irrelevant details and includes contextually-important details.

Encapsulation restricts outside access to something's parts and bundles that thing's state with the procedures that use the state.


Take people, for instance. In the context of surgery a useful abstraction ignores a person's religious beliefs and includes the person's body. Further, people encapsulate their memories with the thought processes that use those memories. An abstraction need not have encapsulation; for instance, a painting of a person neither hides its parts nor bundles procedures with its state. And, encapsulation need not have an associated abstraction; for instance, real people (not abstract ones) encapsulate their organs with their metabolism.

How to set default Checked in checkbox ReactJS?

this can be done with pure js

              <Form.Group controlId="categoryStatus">
                <Form.Check
                  type="checkbox"
                  label="Category Status Active/In-active"
                  onChange={this.handleChecked}                 
                />
              </Form.Group>

  //Load category to form : to edit
  GetCategoryById(id) {
    this.UpdateId = id
    axios.get('http://localhost:4000/Category/edit/' + id)
      .then(response => {
        this.setState({
          category_name: response.data.category_name,
          category_description: response.data.category_description,
          is_active: response.data.is_active,
        });

        response.data.is_active == 1 ? document.getElementById("categoryStatus").checked = true : document.getElementById("categoryStatus").checked = false;
      })
      .catch(function (error) {
        console.log(error);
      })
  }


Build Eclipse Java Project from Command Line

After 27 years, I too, am uncomfortable developing in an IDE. I tried these suggestions (above) - and probably just didn't follow everything right -- so I did a web-search and found what worked for me at 'http://incise.org/android-development-on-the-command-line.html'.

The answer seemed to be a combination of all the answers above (please tell me if I'm wrong and accept my apologies if so).

As mentioned above, eclipse/adt does not create the necessary ant files. In order to compile without eclipse IDE (and without creating ant scripts):

1) Generate build.xml in your top level directory:

android list targets  (to get target id used below)

android update project --target target_id --name project_name  --path top_level_directory

   ** my sample project had a target_id of 1 and a project name of 't1', and 
   I am building from the top level directory of project
   my command line looks like android update project --target 1 --name t1 --path `pwd`

2) Next I compile the project. I was a little confused by the request to not use 'ant'. Hopefully -- requester meant that he didn't want to write any ant scripts. I say this because the next step is to compile the application using ant

 ant target

    this confused me a little bit, because i thought they were talking about the
    android device, but they're not.  It's the mode  (debug/release)
    my command line looks like  ant debug

3) To install the apk onto the device I had to use ant again:

 ant target install

    ** my command line looked like  ant debug install

4) To run the project on my android phone I use adb.

 adb shell 'am start -n your.project.name/.activity'

    ** Again there was some confusion as to what exactly I had to use for project 
    My command line looked like adb shell 'am start -n com.example.t1/.MainActivity'
    I also found that if you type 'adb shell' you get put to a cli shell interface
    where you can do just about anything from there.

3A) A side note: To view the log from device use:

 adb logcat

3B) A second side note: The link mentioned above also includes instructions for building the entire project from the command.

Hopefully, this will help with the question. I know I was really happy to find anything about this topic here.

How to get the previous url using PHP

I can't add a comment yet, so I wanted to share that HTTP_REFERER is not always sent.

Notice: Undefined index: HTTP_REFERER

Python "\n" tag extra line

This:

    print "\n"

is printing out two \n characters -- the one you tell it to, and the one that Python prints out at the end of any line which doesn't end with a , like you use in print a,. Simply use

    print

instead.

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

In my case, this has been resolved by going to control panel > java > security > then add url in the exception site list. Then apply. Test again the site and it should now allow you to run the local java.

Get property value from C# dynamic object by string (reflection?)

Thought this might help someone in the future.

If you know the property name already, you can do something like the following:

[HttpPost]
[Route("myRoute")]
public object SomeApiControllerMethod([FromBody] dynamic args){
   var stringValue = args.MyPropertyName.ToString();
   //do something with the string value.  If this is an int, we can int.Parse it, or if it's a string, we can just use it directly.
   //some more code here....
   return stringValue;
}

Get user input from textarea

Just in case, instead of [(ngModel)] you can use (input) (is fired when a user writes something in the input <textarea>) or (blur) (is fired when a user leaves the input <textarea>) event,

<textarea cols="30" rows="4" (input)="str = $event.target.value"></textarea>

Is module __file__ attribute absolute or relative?

With the help of the of Guido mail provided by @kindall, we can understand the standard import process as trying to find the module in each member of sys.path, and file as the result of this lookup (more details in PyMOTW Modules and Imports.). So if the module is located in an absolute path in sys.path the result is absolute, but if it is located in a relative path in sys.path the result is relative.

Now the site.py startup file takes care of delivering only absolute path in sys.path, except the initial '', so if you don't change it by other means than setting the PYTHONPATH (whose path are also made absolute, before prefixing sys.path), you will get always an absolute path, but when the module is accessed through the current directory.

Now if you trick sys.path in a funny way you can get anything.

As example if you have a sample module foo.py in /tmp/ with the code:

import sys
print(sys.path)
print (__file__)

If you go in /tmp you get:

>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
./foo.py

When in in /home/user, if you add /tmp your PYTHONPATH you get:

>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
/tmp/foo.py

Even if you add ../../tmp, it will be normalized and the result is the same.

But if instead of using PYTHONPATH you use directly some funny path you get a result as funny as the cause.

>>> import sys
>>> sys.path.append('../../tmp')
>>> import foo
['', '/usr/lib/python3.3', .... , '../../tmp']
../../tmp/foo.py

Guido explains in the above cited thread, why python do not try to transform all entries in absolute paths:

we don't want to have to call getpwd() on every import .... getpwd() is relatively slow and can sometimes fail outright,

So your path is used as it is.

How to display a pdf in a modal window?

You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page

Also you can use Flash to embed the document into any HTML page like that:

<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
    <p>
        It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
    </p>
</object>

How to call a PHP function on the click of a button

You should make the button call the same page and in a PHP section check if the button was pressed:

HTML:

<form action="theSamePage.php" method="post">
    <input type="submit" name="someAction" value="GO" />
</form>

PHP:

<?php
    if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
    {
        func();
    }
    function func()
    {
        // do stuff     
    }
?>

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

It looks necessary to put a SET IDENTITY_INSERT Database.dbo.Baskets ON; before every SQL INSERT sending batch.

You can send several INSERT ... VALUES ... commands started with one SET IDENTITY_INSERT ... ON; string at the beginning. Just don't put any batch separator between.

I don't know why the SET IDENTITY_INSERT ... ON stops working after the sending block (for ex.: .ExecuteNonQuery() in C#). I had to put SET IDENTITY_INSERT ... ON; again at the beginning of next SQL command string.

Get environment variable value in Dockerfile

So you can do: cat Dockerfile | envsubst | docker build -t my-target -

Then have a Dockerfile with something like:

ENV MY_ENV_VAR $MY_ENV_VAR

I guess there might be a problem with some special characters, but this works for most cases at least.

How to implement LIMIT with SQL Server?

Syntactically MySQL LIMIT query is something like this:

SELECT * FROM table LIMIT OFFSET, ROW_COUNT

This can be translated into Microsoft SQL Server like

SELECT * FROM 
(
    SELECT TOP #{OFFSET+ROW_COUNT} *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rnum 
    FROM table
) a
WHERE rnum > OFFSET

Now your query select * from table1 LIMIT 10,20 will be like this:

SELECT * FROM 
(
    SELECT TOP 30 *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rnum 
    FROM table1
) a
WHERE rnum > 10 

Concatenate two JSON objects

okay, you can do this in one line of code. you'll need json2.js for this (you probably already have.). the two json objects here are unparsed strings.

json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';

json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';

concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));

Append text to textarea with javascript

Tray to add text with html value to textarea but it wil not works

value :

$(document).on('click', '.edit_targets_btn', function() {
            $('#add_edit_targets').modal('show');
            $('#add_edit_targets_form')[0].reset();
            $('#targets_modal_title').text('Doel bijwerken');
            $('#action').val('targets_update');
            $('#targets_submit_btn').val('Opslaan');

            $('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
            $('#targets_title').val($(this).attr("title"));
            $("#targets_content").append($(this).attr("content"));

            tinymce.init({
                selector: '#targets_content',
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                },
                browser_spellcheck : true,
                plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
                toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
                relative_urls : false,
                remove_script_host : false,
                image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
                min_height: 250,
                branding: false
            });
        });

How can I know if Object is String type object?

Either use instanceof or method Class.isAssignableFrom(Class<?> cls).

When to use Task.Delay, when to use Thread.Sleep?

The biggest difference between Task.Delay and Thread.Sleep is that Task.Delay is intended to run asynchronously. It does not make sense to use Task.Delay in synchronous code. It is a VERY bad idea to use Thread.Sleep in asynchronous code.

Normally you will call Task.Delay() with the await keyword:

await Task.Delay(5000);

or, if you want to run some code before the delay:

var sw = new Stopwatch();
sw.Start();
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;

Guess what this will print? Running for 0.0070048 seconds. If we move the await delay above the Console.WriteLine instead, it will print Running for 5.0020168 seconds.

Let's look at the difference with Thread.Sleep:

class Program
{
    static void Main(string[] args)
    {
        Task delay = asyncTask();
        syncCode();
        delay.Wait();
        Console.ReadLine();
    }

    static async Task asyncTask()
    {
        var sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("async: Starting");
        Task delay = Task.Delay(5000);
        Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        await delay;
        Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        Console.WriteLine("async: Done");
    }

    static void syncCode()
    {
        var sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("sync: Starting");
        Thread.Sleep(5000);
        Console.WriteLine("sync: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        Console.WriteLine("sync: Done");
    }
}

Try to predict what this will print...

async: Starting
async: Running for 0.0070048 seconds
sync: Starting
async: Running for 5.0119008 seconds
async: Done
sync: Running for 5.0020168 seconds
sync: Done

Also, it is interesting to notice that Thread.Sleep is far more accurate, ms accuracy is not really a problem, while Task.Delay can take 15-30ms minimal. The overhead on both functions is minimal compared to the ms accuracy they have (use Stopwatch Class if you need something more accurate). Thread.Sleep still ties up your Thread, Task.Delay release it to do other work while you wait.

How to select ALL children (in any level) from a parent in jQuery?

Use jQuery.find() to find children more than one level deep.

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

$('#google_translate_element').find('*').unbind('click');

You need the '*' in find():

Unlike in the rest of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.

How to rename a pane in tmux?

yes you can rename pane names, and not only window names starting with tmux >= 2.3. Just type the following in your shell:

printf '\033]2;%s\033\\' 'title goes here'

you might need to add the following to your .tmux.conf to display pane names:

# Enable names for panes
set -g pane-border-status top

you can also automatically assign a name:

set -g pane-border-format "#P: #{pane_current_command}"

Text Editor For Linux (Besides Vi)?

Try Scribes . It tries to be a TextMate replacement for Linux

2020 edit: forgotten in the mists of history

Oracle: not a valid month

To know the actual date format, insert a record by using sysdate. That way you can find the actual date format. for example

insert into emp values(7936, 'Mac', 'clerk', 7782, sysdate, 1300, 300, 10);

now, select the inserted record.

select ename, hiredate from emp where ename='Mac';

the result is

ENAME   HIREDATE
Mac     06-JAN-13

voila, now your actual date format is found.

Can I use an HTML input type "date" to collect only a year?

There is input type month in HTML5 which allows to select month and year. Month selector works with autocomplete.

Check the example in JSFiddle.

<!DOCTYPE html>
<html>
<body>
    <header>
        <h1>Select a month below</h1>
    </header>
    Month example
    <input type="month" />
</body>
</html>

Use Ant for running program with command line arguments

Can you be a bit more specific about what you're trying to do and how you're trying to do it?

If you're attempting to invoke the program using the <exec> task you might do the following:

<exec executable="name-of-executable">
  <arg value="arg0"/>
  <arg value="arg1"/>
</exec>

Get month name from date in Oracle

In Oracle (atleast 11g) database :

If you hit

select to_char(SYSDATE,'Month') from dual;

It gives unformatted month name, with spaces, for e.g. May would be given as 'May '. The string May will have spaces.

In order to format month name, i.e to trim spaces, you need

select to_char(SYSDATE,'fmMonth') from dual;

This would return 'May'.

Multiple conditions in a C 'for' loop

The comma operator evaluates all its operands and yields the value of the last one. So basically whichever condition you write first, it will be disregarded, and the second one will be significant only.

for (i = 0; j >= 0, i <= 5; i++)

is thus equivalent with

for (i = 0; i <= 5; i++)

which may or may not be what the author of the code intended, depending on his intents - I hope this is not production code, because if the programmer having written this wanted to express an AND relation between the conditions, then this is incorrect and the && operator should have been used instead.

DateTime group by date and hour

SELECT [activity_dt], COUNT(*) as [Count]
  FROM 
 (SELECT dateadd(hh, datediff(hh, '20010101', [activity_dt]), '20010101') as [activity_dt]
    FROM table) abc
 GROUP BY [activity_dt]

Where is a log file with logs from a container?

A container's logs can be found in :

/var/lib/docker/containers/<container id>/<container id>-json.log

(if you use the default log format which is json)

How can I send the "&" (ampersand) character via AJAX?

encodeURIComponent(Your text here);

This will truncate special characters.

Going to a specific line number using Less in Unix

For editing this is possible in nano via +n from command line, e.g.,

nano +16 file.txt

To open file.txt to line 16.

Convert js Array() to JSon object for use with JQuery .ajax

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

How to embed matplotlib in pyqt - for Dummies

Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...


import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

import random

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # instead of ax.hold(False)
        self.figure.clear()

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        # ax.hold(False) # deprecated, see above

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

Can a java file have more than one class?

Yes You can have more than one Class in one .Java file . But You have make one of them Public . and save .java file with same name as name of public class. when you will compile that .java file than you will get Separate .class files for each class defined in .java file .

Apart from this there are too many method for defining more than one class in one .java file .

  1. use concept of Inner Classes.
  2. Use Concept of Anonymous Classes .

Deck of cards JAVA

First you have an architectural issue with your classes. You moved the property deck inside your class Card. But of couse it is a property of the card deck and thus has to be inside class DeckOfCards. The initialization loop should then not be in the constructor of Card but of your deck class. Moreover, the deck is an array of int at the moment but should be an array of Cards.

Second, inside method Deal you should refer to suits as Card.suits and make this member static final. Same for ranks.

And last, please stick to naming conventions. Method names are always starting with a lower case letter, i.e. shuffle instead of Shuffle.

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

How can I return to a parent activity correctly?

What worked for me was adding:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

to TheRelevantActivity.java and now it is working as expected

and yeah don't forget to add:

getSupportActionbar.setDisplayHomeAsUpEnabled(true); in onCreate() method

recyclerview No adapter attached; skipping layout

I have solved this error. You just need to add layout manager and add the empty adapter.

Like this code:

myRecyclerView.setLayoutManager(...//your layout manager);
        myRecyclerView.setAdapter(new RecyclerView.Adapter() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                return null;
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

            }

            @Override
            public int getItemCount() {
                return 0;
            }
        });
//other code's 
// and for change you can use if(mrecyclerview.getadapter != speacialadapter){
//replice your adapter
//}

How to run the sftp command with a password from Bash script?

You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:

vi test_script.sh

Add the following to your file:

#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>

cd <base directory for your put file>

lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT

And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq .Then make your script executable chmod +x test_script.sh and execute it ./test_script.sh.

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use .getScript() and run your code after it loads:

 $.getScript("my_lovely_script.js", function(){

    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script

 });

You can see a better explanation here: How do I include a JavaScript file in another JavaScript file?

Loop in react-native

First of all, I recommend writing the item you want to render multiple times (in your case list of fields) as a separate component:

function Field() {
    return (
        <View>
            <View>
                <TextInput />
            </View>
            <View>
                <TextInput />
            </View>
            <View>
                <TextInput />
            </View>
        </View>
    );
}

Then, in your case, when rendering based on some number and not a list, I'd move the for loop outside of the render method for a more readable code:

renderFields() {
    const noGuest = this.state.guest;
    const fields = [];
    for (let i=0; i < noGuest; i++) {
        // Try avoiding the use of index as a key, it has to be unique!
        fields.push(
            <Field key={"guest_"+i} />
        );
    }
    return fields;
}

render () {
    return (
        <View>
            <View>
                <View><Text>No</Text></View>
                <View><Text>Name</Text></View>
                <View><Text>Preference</Text></View>
            </View>
            {this.renderFields()}
        </View>;
    )
}

However, there are many more ways to render looped content in react native. Most of the ways are covered in this article, so please check it out if you're interested in more details! The examples in article are from React, but everything applies to React Native as well!

Fit website background image to screen size

Try this:

background: url(../IMAGES/background.jpg) no-repeat;
background-size: auto auto;

How can I view the shared preferences file using Android Studio?

In the Device File Explorer follow the below path :-

/data/data/com.**package_name**.test/shared_prefs/com.**package_name**.test_preferences.xml

Multiple Inheritance in C#

This is along the lines of Lawrence Wenham's answer, but depending on your use case, it may or may not be an improvement -- you don't need the setters.

public interface IPerson {
  int GetAge();
  string GetName();
}

public interface IGetPerson {
  IPerson GetPerson();
}

public static class IGetPersonAdditions {
  public static int GetAgeViaPerson(this IGetPerson getPerson) { // I prefer to have the "ViaPerson" in the name in case the object has another Age property.
    IPerson person = getPerson.GetPersion();
    return person.GetAge();
  }
  public static string GetNameViaPerson(this IGetPerson getPerson) {
    return getPerson.GetPerson().GetName();
  }
}

public class Person: IPerson, IGetPerson {
  private int Age {get;set;}
  private string Name {get;set;}
  public IPerson GetPerson() {
    return this;
  }
  public int GetAge() {  return Age; }
  public string GetName() { return Name; }
}

Now any object that knows how to get a person can implement IGetPerson, and it will automatically have the GetAgeViaPerson() and GetNameViaPerson() methods. From this point, basically all Person code goes into IGetPerson, not into IPerson, other than new ivars, which have to go into both. And in using such code, you don't have to be concerned about whether or not your IGetPerson object is itself actually an IPerson.

limit text length in php and provide 'Read more' link

This is what I use:

// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {

    // truncate string
    $stringCut = substr($string, 0, 500);
    $endPoint = strrpos($stringCut, ' ');

    //if the string doesn't contain any space then it will cut without word basis.
    $string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
    $string .= '... <a href="/this/story">Read More</a>';
}
echo $string;

You can tweak it further but it gets the job done in production.

Java : Accessing a class within a package, which is the better way?

Import package is for better readability;

Fully qualified class has to be used in special scenarios. For example, same class name in different package, or use reflect such as Class.forName().

How to vertically align text in input type="text"?

IF vertical align won't work use padding. padding-top: 10px; it will shift the text to the bottom or padding-bottom: 10px; to shift the text in the text box to top

adjust the padding size till it suit the size you want. Thats the hack

How to link a folder with an existing Heroku app

Use heroku's fork

  1. Use the new "heroku fork" command! It will copy all the environment and you have to update the github repo after!

    heroku fork -a sourceapp targetapp
    
  2. Clone it local

    git clone [email protected]:youamazingapp.git
    
  3. Make a new repo on github and add it

    git remote add origin https://github.com/yourname/your_repo.git
    
  4. Push on github

    git push origin master
    

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper div:

.dimmed {
  position: relative;
}

.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
}

I'm using rgba here, but of course you can use other transparency methods if you like.

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

How to use conditional breakpoint in Eclipse?

From Eclipsepedia on how to set a conditional breakpoint:

First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as list.size()==0. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.

Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.

In Python, how do I split a string and keep the separators?

If one wants to split string while keeping separators by regex without capturing group:

def finditer_with_separators(regex, s):
    matches = []
    prev_end = 0
    for match in regex.finditer(s):
        match_start = match.start()
        if (prev_end != 0 or match_start > 0) and match_start != prev_end:
            matches.append(s[prev_end:match.start()])
        matches.append(match.group())
        prev_end = match.end()
    if prev_end < len(s):
        matches.append(s[prev_end:])
    return matches

regex = re.compile(r"[\(\)]")
matches = finditer_with_separators(regex, s)

If one assumes that regex is wrapped up into capturing group:

def split_with_separators(regex, s):
    matches = list(filter(None, regex.split(s)))
    return matches

regex = re.compile(r"([\(\)])")
matches = split_with_separators(regex, s)

Both ways also will remove empty groups which are useless and annoying in most of the cases.

How can you print a variable name in python?

Rather than ask for details to a specific solution, I recommend describing the problem you face; I think you'll get better answers. I say this since there's almost certainly a better way to do whatever it is you're trying to do. Accessing variable names in this way is not commonly needed to solve problems in any language.

That said, all of your variable names are already in dictionaries which are accessible through the built-in functions locals and globals. Use the correct one for the scope you are inspecting.

One of the few common idioms for inspecting these dictionaries is for easy string interpolation:

>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe

This sort of thing tends to be a bit more readable than the alternatives even though it requires inspecting variables by name.

Easy way to password-protect php page

Some easy ways:
Use Apache's digest authorization.
Use lighttpd's digest authorization.
Use php's header digest authorization.

If you want you can also make it so only certain ip addresses can login.. :) really easy with lighttpd

Update: I will post some examples soon, so don't vote down for no examples, i just need to get some down for this answer.

If you want to use sessions the following is the best way to go:

# admin.php
session_start();
if(!$_SESSION["AUTH"])
    require_once "login.php";
# Do stuff, we are logged in..

# login.php
session_start();
if($_REQUEST["username"] == "user" && $_REQUEST["password"] == "pass")
    $_SESSION["AUTH"] = true;
else $_SESSION["AUTH"] = false; # This logs you out if you visit this login script page without login details.

if($_SESSION["AUTH"])
    require_once "admin.php";

This method does not contain the examples for above but you seamed interested in this method. The other method examples are still to come, I have not got enough time to get it for apache or lighttpd settings and the php header auth: http://php.net/manual/en/features.http-auth.php Will do.

Break a previous commit into multiple commits

Please note there's also git reset --soft HEAD^. It's similar to git reset (which defaults to --mixed) but it retains the index contents. So that if you've added/removed files, you have them in the index already.

Turns out to be very useful in case of giant commits.

force css grid container to fill full screen of device

If you want the .wrapper to be fullscreen, just add the following in the wrapper class:

position: absolute; width: 100%; height: 100%;

You can also add top: 0 and left:0

Get the cartesian product of a series of lists?

Here is a recursive generator, which doesn't store any temporary lists

def product(ar_list):
    if not ar_list:
        yield ()
    else:
        for a in ar_list[0]:
            for prod in product(ar_list[1:]):
                yield (a,)+prod

print list(product([[1,2],[3,4],[5,6]]))

Output:

[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]

How to create a file name with the current date & time in Python?

This prints in an easy to read format -

import datetime

time_now  = datetime.datetime.now().strftime('%m_%d_%Y_%H_%M_%S') 

print(time_now)

Output: 02_03_2021_22_44_50

Unable to Install Any Package in Visual Studio 2015

Repairing Visual Studio 2015 seems to have resolved this issue for me. See this issue for NuGet in GitHub.

How to convert a Hibernate proxy to a real entity object

Starting from Hiebrnate 5.2.10 you can use Hibernate.proxy method to convert a proxy to your real entity:

MyEntity myEntity = (MyEntity) Hibernate.unproxy( proxyMyEntity );

C++, How to determine if a Windows Process is running?

The process handle will be signaled if it exits.

So the following will work (error handling removed for brevity):

BOOL IsProcessRunning(DWORD pid)
{
    HANDLE process = OpenProcess(SYNCHRONIZE, FALSE, pid);
    DWORD ret = WaitForSingleObject(process, 0);
    CloseHandle(process);
    return ret == WAIT_TIMEOUT;
}

Note that process ID's can be recycled - it's better to cache the handle that is returned from the CreateProcess call.

You can also use the threadpool API's (SetThreadpoolWait on Vista+, RegisterWaitForSingleObject on older platforms) to receive a callback when the process exits.

EDIT: I missed the "want to do something to the process" part of the original question. You can use this technique if it is ok to have potentially stale data for some small window or if you want to fail an operation without even attempting it. You will still have to handle the case where the action fails because the process has exited.

Can I convert long to int?

Convert.ToInt32(myValue);

Though I don't know what it will do when it's greater than int.MaxValue.

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

Array.Add vs +=

The most common idiom for creating an array without using the inefficient += is something like this, from the output of a loop:

$array = foreach($i in 1..10) { 
  $i
}
$array

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

Josh says: "....Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h."

I'm a native Spanish Speaker and "ch" is not a letter but two "c" and "h" and the Spanish alphabet is like: abcdefghijklmn ñ opqrstuvwxyz We don't expect "ch" after "h" but "i" The alphabet is the same as in English except for the ñ or in HTML "&ntilde ;"

Alex

Find the differences between 2 Excel worksheets?

LibreOffice provides a Workbook Compare feature: Edit -> Compare Document

Can Google Chrome open local links?

Hopefully this helps others in an enterprise setting looking for a solution. My solution after much tinkering was the following:

Follow the steps in the following link to install legacy browser extension and gpo settings: https://support.google.com/chrome/a/answer/3019558?hl=en&ref_topic=3062034

Enabled legacy browser redirect for "file://" through chrome gpo configuration Google Chrome -> Legacy Browser Support -> "Websites to open in alternative browser"

Configure gpo to also install extension: https://chrome.google.com/webstore/detail/enable-local-file-links/nikfmfgobenbhmocjaaboihbeocackld that redirects file:// links to bypass chrome file:// link block.

The extension opens the links which then triggers google chrome to open the link in internet explorer. The result is IE opens a window, then opens the file/folder for the user, then IE closes itself.

Do checkbox inputs only post data if they're checked?

From HTML 4 spec, which should be consistent across almost all browsers:

http://www.w3.org/TR/html401/interact/forms.html#checkbox

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.

Successful is defined as follows:

A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.

Default instance name of SQL Server Express

in my case the right server name was the name of my computer. for example John-PC, or somth

Why should I use a pointer rather than the object itself?

It's very unfortunate that you see dynamic allocation so often. That just shows how many bad C++ programmers there are.

In a sense, you have two questions bundled up into one. The first is when should we use dynamic allocation (using new)? The second is when should we use pointers?

The important take-home message is that you should always use the appropriate tool for the job. In almost all situations, there is something more appropriate and safer than performing manual dynamic allocation and/or using raw pointers.

Dynamic allocation

In your question, you've demonstrated two ways of creating an object. The main difference is the storage duration of the object. When doing Object myObject; within a block, the object is created with automatic storage duration, which means it will be destroyed automatically when it goes out of scope. When you do new Object(), the object has dynamic storage duration, which means it stays alive until you explicitly delete it. You should only use dynamic storage duration when you need it. That is, you should always prefer creating objects with automatic storage duration when you can.

The main two situations in which you might require dynamic allocation:

  1. You need the object to outlive the current scope - that specific object at that specific memory location, not a copy of it. If you're okay with copying/moving the object (most of the time you should be), you should prefer an automatic object.
  2. You need to allocate a lot of memory, which may easily fill up the stack. It would be nice if we didn't have to concern ourselves with this (most of the time you shouldn't have to), as it's really outside the purview of C++, but unfortunately, we have to deal with the reality of the systems we're developing for.

When you do absolutely require dynamic allocation, you should encapsulate it in a smart pointer or some other type that performs RAII (like the standard containers). Smart pointers provide ownership semantics of dynamically allocated objects. Take a look at std::unique_ptr and std::shared_ptr, for example. If you use them appropriately, you can almost entirely avoid performing your own memory management (see the Rule of Zero).

Pointers

However, there are other more general uses for raw pointers beyond dynamic allocation, but most have alternatives that you should prefer. As before, always prefer the alternatives unless you really need pointers.

  1. You need reference semantics. Sometimes you want to pass an object using a pointer (regardless of how it was allocated) because you want the function to which you're passing it to have access that that specific object (not a copy of it). However, in most situations, you should prefer reference types to pointers, because this is specifically what they're designed for. Note this is not necessarily about extending the lifetime of the object beyond the current scope, as in situation 1 above. As before, if you're okay with passing a copy of the object, you don't need reference semantics.

  2. You need polymorphism. You can only call functions polymorphically (that is, according to the dynamic type of an object) through a pointer or reference to the object. If that's the behavior you need, then you need to use pointers or references. Again, references should be preferred.

  3. You want to represent that an object is optional by allowing a nullptr to be passed when the object is being omitted. If it's an argument, you should prefer to use default arguments or function overloads. Otherwise, you should preferably use a type that encapsulates this behavior, such as std::optional (introduced in C++17 - with earlier C++ standards, use boost::optional).

  4. You want to decouple compilation units to improve compilation time. The useful property of a pointer is that you only require a forward declaration of the pointed-to type (to actually use the object, you'll need a definition). This allows you to decouple parts of your compilation process, which may significantly improve compilation time. See the Pimpl idiom.

  5. You need to interface with a C library or a C-style library. At this point, you're forced to use raw pointers. The best thing you can do is make sure you only let your raw pointers loose at the last possible moment. You can get a raw pointer from a smart pointer, for example, by using its get member function. If a library performs some allocation for you which it expects you to deallocate via a handle, you can often wrap the handle up in a smart pointer with a custom deleter that will deallocate the object appropriately.

Syntax error: Illegal return statement in JavaScript

where are you trying to return the value? to console in dev tools is better for debugging

<script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
  if(ask==false){
    return false;     
  } else {
    return true;
  }
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>

CREATE DATABASE permission denied in database 'master' (EF code-first)

run this on your master database

ALTER SERVER ROLE sysadmin ADD MEMBER your-user;  
GO 

How to get the indexpath.row when an element is activated?

Solution:

You have a button (myButton) or any other view in cell. Assign tag in cellForRowAt like this

cell.myButton.tag = indexPath.row

Now in you tapFunction or any other. Fetch it out like this and save it in a local variable.

currentCellNumber = (sender.view?.tag)!

After this you can use anywhere this currentCellNumber to get the indexPath.row of selected button.

Enjoy!

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

Call to undefined method mysqli_stmt::get_result

Your system is missing the mysqlnd driver!

If you are able to install new packages on your (Debian/Ubuntu-based) server, install the driver:

sudo apt-get install php5-mysqlnd

and then restart your web server:

sudo /etc/init.d/apache2 restart

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

Windows equivalent to UNIX pwd

Open notepad as administrator and write:

@echo %cd%

Save it in c:\windows\system32\ with the name "pwd.cmd" (be careful not to save pwd.cmd.txt)

Then you have the pwd command.

Drop shadow on a div container?

This works for me on all my browsers:

.shadow {
-moz-box-shadow: 0 0 30px 5px #999;
-webkit-box-shadow: 0 0 30px 5px #999;
}

then just give any div the shadow class, no jQuery required.

Showing percentages above bars on Excel column graph

You can do this with a pivot table and add a line with the pourcentage for each category like brettdj showed in his answer. But if you want to keep your data as it is, there is a solution by using some javascript.

Javascript is a powerful language offering a lot of useful data visualization libraries like plotly.js.

Here is a working code I have written for you:

https://www.funfun.io/1/#/edit/5a58c6368dfd67466879ed27

In this example, I use a Json file to get the data from the embedded spreadsheet, so I can use it in my javascript code and create a bar chart.

I calculate the percentage by adding the values of all the category present in the table and using this formula (you can see it in the script.js file): Percentage (%) = 100 x partial value / total value

It automatically calculates the total and pourcentage even if you add more categories.

I used plotly.js to create my chart, it has a good documentation and lots of examples for beginners, this code gets all the option you want to use:

var trace1 = {
    x: xValue, 
    y: data,
    type: 'bar',
    text: yValue,
    textposition: 'auto',
    hoverinfo: 'none',
    marker: {
    color: 'yellow',
    opacity: 0.6,
    line: {
      color: 'yellow',
      width: 1.5
    }
  }
};

It is rather self explanatory, the text is where you put the percentage.

Once you've made your chart you can load it in excel by passing the URL in the Funfun add-in. Here is how it looks like with my example:

final

I know it is an old post but I hope it helps people with the same problem !

Disclosure : I’m a developer of funfun

Set auto height and width in CSS/HTML for different screen sizes

///UPDATED DEMO 2 WATCH SOLUTION////

I hope that is the solution you're looking for! DEMO1 DEMO2

With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!

You can do that with that code here:

<div class="navTop">
<h1>Title</h1>
    <nav>Dynamic menu</nav>
</div>
<div class="container">
    <section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
    Footer
</footer>

With that css:

.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}

And a bit of jquery:

$(document).ready(function() {
  function setHeight() {
    var top = $('.navTop').outerHeight();
    var bottom = $('footer').outerHeight();
    var totHeight = $(window).height();
    $('section').css({ 
      'height': totHeight - top - bottom + 'px'
    });
  }

  $(window).on('resize', function() { setHeight(); });
  setHeight();
});

DEMO 1

If you don't want jquery

<div class="row">
    <h1>Title</h1>
    <nav>NAV</nav>
</div>

<div class="row container">
    <div class="content">
        <div class="sidebar">
            SIDEBAR
        </div>
        <div class="contents">
            CONTENTS
        </div>
    </div>
    <footer>Footer</footer>
</div>

CSS

*{
margin:0;padding:0;    
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%; 
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{ 
position: fixed; 
bottom: 0; 
left: 0; 
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}

DEMO 2

How to fix 'Microsoft Excel cannot open or save any more documents'

After giving necessary permissions in DCOM configurations I also needed to change the identity of my application in the IIS to a custom account

PHP class not found but it's included

In fact, it's a very old thread but useful...

When namespace declaration is part of your php class file "this kind of weird errors tends to appear".

Solution: Use namespace with {, your code shows like this:

<?php

namespace path_to\lib {

require_once "folder/php_class_file_where_namespace_declaration_is_part_of_it.php";

**YOUR CODE HERE**

<?php } ?>

Python debugging tips

If you don't like spending time in debuggers (and don't appreciate poor usability of pdb command line interface), you can dump execution trace and analyze it later. For example:

python -m trace -t setup.py install > execution.log

This will dump all source line of setup.py install execution to execution.log.

To make it easier to customize trace output and write your own tracers, I put together some pieces of code into xtrace module (public domain).

jQuery datepicker, onSelect won't work

I have downloaded the datepicker from jqueryui.com/download and I got 1.7.2 version but still onSelect function didn't work. Here is what i had -

$("#datepicker").datepicker();

$("#datepicker").datepicker({ 
      onSelect: function(value, date) { 
         alert('The chosen date is ' + value); 
      } 
});

I found the solution in this page -- problem with jquery datepicker onselect . Removed the $("#datepicker").datepicker(); once and it worked.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Get the correct week number of a given date

Here is an extension version and nullable version of il_guru's answer.

Extension:

public static int GetIso8601WeekOfYear(this DateTime time)
{
    var day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        time = time.AddDays(3);
    }

    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

Nullable:

public static int? GetIso8601WeekOfYear(this DateTime? time)
{
    return time?.GetIso8601WeekOfYear();
}

Usages:

new DateTime(2019, 03, 15).GetIso8601WeekOfYear(); //returns 11
((DateTime?) new DateTime(2019, 03, 15)).GetIso8601WeekOfYear(); //returns 11
((DateTime?) null).GetIso8601WeekOfYear(); //returns null

What is the LDF file in SQL Server?

The LDF file holds the database transaction log. See, for example, http://www.databasedesign-resource.com/sql-server-transaction-log.html for a full explanation. There are ways to shrink the transaction file; for example, see http://support.microsoft.com/kb/873235.

Remove white space below image

Had this prob, found perfect solution elsewhere if you dont want you use block just add

img { vertical-align: top }

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

How to limit google autocomplete results to City and Country only

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
   body {_x000D_
         font-family: sans-serif;_x000D_
         font-size: 14px;_x000D_
   }_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
   function initialize() {_x000D_
      var input = document.getElementById('searchTextField');_x000D_
      var options = {_x000D_
        types: ['geocode'] //this should work !_x000D_
      };_x000D_
      var autocomplete = new google.maps.places.Autocomplete(input, options);_x000D_
   }_x000D_
   google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
   <div>_x000D_
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
   </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

var options = {
  types: ['geocode'] //this should work !
};
var autocomplete = new google.maps.places.Autocomplete(input, options);

reference to other types: http://code.google.com/apis/maps/documentation/places/supported_types.html#table2

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

Try with the fully qualified name for the resource:

private static final String FILENAME = "resources/skyscrapper";

Regexp Java for password validation

Thanks for all answers, based on all them but extending sphecial characters:

@SuppressWarnings({"regexp", "RegExpUnexpectedAnchor", "RegExpRedundantEscape"})
String PASSWORD_SPECIAL_CHARS = "@#$%^`<>&+=\"!ºª·#~%&'¿¡€,:;*/+-.=_\\[\\]\\(\\)\\|\\_\\?\\\\";
int PASSWORD_MIN_SIZE = 8;
String PASSWORD_REGEXP = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[" + PASSWORD_SPECIAL_CHARS + "])(?=\\S+$).{"+PASSWORD_MIN_SIZE+",}$";

Unit tested:

enter image description here

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

This problem happened with me when I used jQUery Fancybox inside a website with many others jQuery plugins. When I used the LightBox (site here) instead of Fancybox, the problem is gone.

Convert JSON array to Python list

data will return you a string representation of a list, but it is actually still a string. Just check the type of data with type(data). That means if you try using indexing on this string representation of a list as such data['fruits'][0], it will return you "[" as it is the first character of data['fruits']

You can do json.loads(data['fruits']) to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here

How to get current date time in milliseconds in android

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int mSec = calendar.get(Calendar.MILLISECOND);

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

You can have the AI play itself in some sample games to learn from. Use a supervised learning algorithm, to help it along.

How do I make a redirect in PHP?

Yes, it's possible to use PHP. We will redirect to another page.

Try following code:

<?php
    header("Location:./"); // Redirect to index file
    header("Location:index.php"); // Redirect to index file
    header("Location:example.php");
?>

Subset dataframe by multiple logical conditions of rows to remove

The ! should be around the outside of the statement:

data[!(data$v1 %in% c("b", "d", "e")), ]

  v1 v2 v3 v4
1  a  v  d  c
2  a  v  d  d
5  c  k  d  c
6  c  r  p  g

How to index into a dictionary?

actually I found a novel solution that really helped me out, If you are especially concerned with the index of a certain value in a list or data set, you can just set the value of dictionary to that Index!:

Just watch:

list = ['a', 'b', 'c']
dictionary = {}
counter = 0
for i in list:
   dictionary[i] = counter
   counter += 1

print(dictionary) # dictionary = {'a':0, 'b':1, 'c':2}

Now through the power of hashmaps you can pull the index your entries in constant time (aka a whole lot faster)

SELECT FOR UPDATE with SQL Server

OK, a single select wil by default use "Read Committed" transaction isolation which locks and therefore stops writes to that set. You can change the transaction isolation level with

Set Transaction Isolation Level { Read Uncommitted | Read Committed | Repeatable Read | Serializable }
Begin Tran
  Select ...
Commit Tran

These are explained in detail in SQL Server BOL

Your next problem is that by default SQL Server 2K5 will escalate the locks if you have more than ~2500 locks or use more than 40% of 'normal' memory in the lock transaction. The escalation goes to page, then table lock

You can switch this escalation off by setting "trace flag" 1211t, see BOL for more information

Clear android application user data

To clear Application Data Please Try this way.

    public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null &amp;&amp; dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

How to change the JDK for a Jenkins job?

Here is my experience with Jenkins version 1.636: as long as I have only one "Install automatically" JDK configured in Jenkins JDK section, I don't see "JDK" dropdown in Job=>Configure section, but as soon as I added second JDK in Jenkins config, JDK dropdown appeared in Job=>Configure section with 3 options [(System), JDK1, JDK2]

Python JSON dump / append to .txt with each variable on new line

Your question is a little unclear. If you're generating hostDict in a loop:

with open('data.txt', 'a') as outfile:
    for hostDict in ....:
        json.dump(hostDict, outfile)
        outfile.write('\n')

If you mean you want each variable within hostDict to be on a new line:

with open('data.txt', 'a') as outfile:
    json.dump(hostDict, outfile, indent=2)

When the indent keyword argument is set it automatically adds newlines.

ASP.NET MVC3 - textarea with @Html.EditorFor

Declare in your Model with

  [DataType(DataType.MultilineText)]
  public string urString { get; set; }

Then in .cshtml can make use of editor as below. you can make use of @cols and @rows for TextArea size

     @Html.EditorFor(model => model.urString, new { htmlAttributes = new { @class = "",@cols = 35, @rows = 3 } })

Thanks !

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

If you think lambdas are evil then read no further. As requested, you can write the fast and memory-efficient solution with one expression:

x = {'a':1, 'b':2}
y = {'b':10, 'c':11}
z = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)
print z
{'a': 1, 'c': 11, 'b': 10}
print x
{'a': 1, 'b': 2}

As suggested above, using two lines or writing a function is probably a better way to go.

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

User @janot has already mentioned this above, but this took me some time to filter the best solution.

There are two Broad use cases:

1) 2 hardware are connected, first is emulator and other is a Device.
Solution : adb -e shell....whatever-command for emulator and adb -d shell....whatever-command for device.

2) n number of devices are connected (all emulators or Phones/Tablets) via USB/ADB-WiFi:

Solution: Step1) run adb devices THis will give you list of devices currently connected (via USB or ADBoverWiFI)
Step2) now run adb -s <device-id/IP-address> shell....whatever-command no matter how many devices you have.

Example
to clear app data on a device connected on wifi ADB I would execute:
adb -s 172.16.34.89:5555 shell pm clear com.package-id

to clear app data connected on my usb connected device I would execute:
adb -s 5210d21be2a5643d shell pm clear com.package-id

How to dynamic new Anonymous Class?

Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic.

Now, if you were to use an ExpandoObject and reference it through a dynamic variable, you could add or remove fields on the fly.

edit

Sure you can: just cast it to IDictionary<string, object>. Then you can use the indexer.

You use the same casting technique to iterate over the fields:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

foreach (var property in (IDictionary<string, object>)employee)
{
    Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33

The above code and more can be found by clicking on that link.

fatal error: iostream.h no such file or directory

Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)

#include <iostream>

int main()
{
    std::cout<<"Hello World!\n";
    return 0;
}

Is it possible to CONTINUE a loop from an exception?

The CONTINUE statement is a new feature in 11g.

Here is a related question: 'CONTINUE' keyword in Oracle 10g PL/SQL

Easiest way to mask characters in HTML(5) text input

Yes, according to HTML5 drafts you can use the pattern attribute to specify the allowed input using a regular expression. For some types of data, you can use special input fields like <input type=email>. But these features still widely lack support or have qualitatively poor support.

$on and $broadcast in angular

//Your broadcast in service

(function () { 
    angular.module('appModule').factory('AppService', function ($rootScope, $timeout) {

    function refreshData() {  
        $timeout(function() {         
            $rootScope.$broadcast('refreshData');
        }, 0, true);      
    }

    return {           
        RefreshData: refreshData
    };
}); }());

//Controller Implementation
 (function () {
    angular.module('appModule').controller('AppController', function ($rootScope, $scope, $timeout, AppService) {            

       //Removes Listeners before adding them 
       //This line will solve the problem for multiple broadcast call                             
       $scope.$$listeners['refreshData'] = [];

       $scope.$on('refreshData', function() {                                                    
          $scope.showData();             
       });

       $scope.onSaveDataComplete = function() { 
         AppService.RefreshData();
       };
    }); }());

How to make shadow on border-bottom?

Try:

_x000D_
_x000D_
div{_x000D_
-webkit-box-shadow:0px 1px 1px #de1dde;_x000D_
 -moz-box-shadow:0px 1px 1px #de1dde;_x000D_
 box-shadow:0px 1px 1px #de1dde;_x000D_
  }
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

It generally adds a 1px blurred shadow 1px from the bottom of the box

box-shadow: [horizontal offset] [vertical offset] [blur radius] [color];

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

Use "mutable" when for things that are LOGICALLY stateless to the user (and thus should have "const" getters in the public class' APIs) but are NOT stateless in the underlying IMPLEMENTATION (the code in your .cpp).

The cases I use it most frequently are lazy initialization of state-less "plain old data" members. Namely, it is ideal in the narrow cases when such members are expensive to either build (processor) or carry around (memory) and many users of the object will never ask for them. In that situation you want lazy construction on the back end for performance, since 90% of the objects built will never need to build them at all, yet you still need to present the correct stateless API for public consumption.

SQL WHERE.. IN clause multiple columns

select * from tab1 where (col1,col2) in (select col1,col2 from tab2)

Note:
Oracle ignores rows where one or more of the selected columns is NULL. In these cases you probably want to make use of the NVL-Funktion to map NULL to a special value (that should not be in the values);

select * from tab1
where (col1, NVL(col2, '---') in (select col1, NVL(col2, '---') from tab2)

Can you hide the controls of a YouTube embed without enabling autoplay?

Follow this https://developers.google.com/youtube/player_parameters for more info about video controls like:

<iframe id="video_iframe" width="660" height="415" src="http://www.youtube.com/v/{{course_url}}?start=7&autoplay=0&showinfo=0&iv_load_policy=3&rel=0"
                frameborder="0"
                allowfullscreen></iframe>

start=7&autoplay=0&showinfo=0&iv_load_policy=3&rel=0" frameborder="0"

all controls are described in there

How to run a bash script from C++ program

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

// ....


system("my_bash_script.sh");

How to create byte array from HttpPostedFile

BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

line 2 should be replaced with

byte[] binData = b.ReadBytes(file.ContentLength);

HTML5 Number Input - Always show 2 decimal places

If you landed here just wondering how to limit to 2 decimal places I have a native javascript solution:

Javascript:

function limitDecimalPlaces(e, count) {
  if (e.target.value.indexOf('.') == -1) { return; }
  if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
    e.target.value = parseFloat(e.target.value).toFixed(count);
  }
}

HTML:

<input type="number" oninput="limitDecimalPlaces(event, 2)" />

Note that this cannot AFAIK, defend against this chrome bug with the number input.

Using <style> tags in the <body> with other HTML

BREAKING BAD NEWS for "style in body" lovers: W3C has recently lost the HTML war against WHATWG, whose versionless HTML "Living Standard" has now become the official one, which, alas, does not allow STYLE in the BODY. The short-lived happy days are over. ;) The W3C validator also works by the WHATWG specs now. (Thanks @FrankConijn for the heads-up!)

(Note: this is the case "as of today", but since there's no versioning, links can become invalid at any moment without notice or control. Unless you're willing to link to its individual source commits at GitHub, you basically can no longer make stable references to the new official HTML standard, AFAIK. Please correct me if there's a canonical way of doing this properly.)

OBSOLETED GOOD NEWS:

Yay, STYLE is finally valid in BODY, as of HTML5.2! (And scoped is gone, too.)

From the W3C specs (relish the last line!):

4.2.6. The style element

...

Contexts in which this element can be used:

Where metadata content is expected.

In a noscript element that is a child of a head element.

In the body, where flow content is expected.


META SIDE-NOTE:

The mere fact that despite the damages of the "browser war" we still had to keep developing against two ridiculously competing "official" HTML "standards" (quotes for 1 standard + 1 standard < 1 standard) means that the "fallback to in-the-trenches common sense" approach to web development has never really ceased to apply.

This may finally change now, but citing the conventional wisdom: web authors/developers and thus, in turn, browsers should ultimately decide what should (and shouldn't) be in the specifications, when there's no good reason against what's already been done in reality. And most browsers have long supported STYLE in BODY (in one way or another; see e.g. the scoped attr.), despite its inherent performance (and possibly other) penalties (which we should decide to pay or not, not the specs.). So, for one, I'll keep betting on them, and not going to give up hope. ;) If WHATWG has the same respect for reality/authors as they claim, they may just end up doing here what the W3C did.

How to get $(this) selected option in jQuery?

var cur_value = $(this).find('option:selected').text();

Since option is likely to be immediate child of select you can also use:

var cur_value = $(this).children('option:selected').text();

http://api.jquery.com/find/

How can I resize an image dynamically with CSS as the browser width/height changes?

You can use CSS3 scale property to resize image with css:

.image:hover {
  -webkit-transform:scale(1.2); 
          transform:scale(1.2);
}
.image {
  -webkit-transition: all 0.7s ease; 
          transition: all 0.7s ease;
}

Further Reading:

Pipe to/from the clipboard in Bash script

For Mac only:

echo "Hello World" | pbcopy
pbpaste

These are located /usr/bin/pbcopy and /usr/bin/pbpaste.

What is the function of the push / pop instructions used on registers in x86 assembly?

Where is it pushed on?

esp - 4. More precisely:

  • esp gets subtracted by 4
  • the value is pushed to esp

pop reverses this.

The System V ABI tells Linux to make rsp point to a sensible stack location when the program starts running: What is default register state when program launches (asm, linux)? which is what you should usually use.

How can you push a register?

Minimal GNU GAS example:

.data
    /* .long takes 4 bytes each. */
    val1:
        /* Store bytes 0x 01 00 00 00 here. */
        .long 1
    val2:
        /* 0x 02 00 00 00 */
        .long 2
.text
    /* Make esp point to the address of val2.
     * Unusual, but totally possible. */
    mov $val2, %esp

    /* eax = 3 */
    mov $3, %ea 

    push %eax
    /*
    Outcome:
    - esp == val1
    - val1 == 3
    esp was changed to point to val1,
    and then val1 was modified.
    */

    pop %ebx
    /*
    Outcome:
    - esp == &val2
    - ebx == 3
    Inverses push: ebx gets the value of val1 (first)
    and then esp is increased back to point to val2.
    */

The above on GitHub with runnable assertions.

Why is this needed?

It is true that those instructions could be easily implemented via mov, add and sub.

They reason they exist, is that those combinations of instructions are so frequent, that Intel decided to provide them for us.

The reason why those combinations are so frequent, is that they make it easy to save and restore the values of registers to memory temporarily so they don't get overwritten.

To understand the problem, try compiling some C code by hand.

A major difficulty, is to decide where each variable will be stored.

Ideally, all variables would fit into registers, which is the fastest memory to access (currently about 100x faster than RAM).

But of course, we can easily have more variables than registers, specially for the arguments of nested functions, so the only solution is to write to memory.

We could write to any memory address, but since the local variables and arguments of function calls and returns fit into a nice stack pattern, which prevents memory fragmentation, that is the best way to deal with it. Compare that with the insanity of writing a heap allocator.

Then we let compilers optimize the register allocation for us, since that is NP complete, and one of the hardest parts of writing a compiler. This problem is called register allocation, and it is isomorphic to graph coloring.

When the compiler's allocator is forced to store things in memory instead of just registers, that is known as a spill.

Does this boil down to a single processor instruction or is it more complex?

All we know for sure is that Intel documents a push and a pop instruction, so they are one instruction in that sense.

Internally, it could be expanded to multiple microcodes, one to modify esp and one to do the memory IO, and take multiple cycles.

But it is also possible that a single push is faster than an equivalent combination of other instructions, since it is more specific.

This is mostly un(der)documented:

Apache Spark: map vs mapPartitions?

What's the difference between an RDD's map and mapPartitions method?

The method map converts each element of the source RDD into a single element of the result RDD by applying a function. mapPartitions converts each partition of the source RDD into multiple elements of the result (possibly none).

And does flatMap behave like map or like mapPartitions?

Neither, flatMap works on a single element (as map) and produces multiple elements of the result (as mapPartitions).

C# create simple xml file

You could use XDocument:

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

If the file you want to create is very big and cannot fit into memory you might use XmlWriter.

What is a callback in java

A callback is some code that you pass to a given method, so that it can be called at a later time.

In Java one obvious example is java.util.Comparator. You do not usually use a Comparator directly; rather, you pass it to some code that calls the Comparator at a later time:

Example:

class CodedString implements Comparable<CodedString> {
    private int code;
    private String text;

    ...

    @Override
    public boolean equals() {
        // member-wise equality
    }

    @Override
    public int hashCode() {
        // member-wise equality 
    }

    @Override
    public boolean compareTo(CodedString cs) {
        // Compare using "code" first, then
        // "text" if both codes are equal.
    }
}

...

public void sortCodedStringsByText(List<CodedString> codedStrings) {
    Comparator<CodedString> comparatorByText = new Comparator<CodedString>() {
        @Override
        public int compare(CodedString cs1, CodedString cs2) {
            // Compare cs1 and cs2 using just the "text" field
        }
    }

    // Here we pass the comparatorByText callback to Collections.sort(...)
    // Collections.sort(...) will then call this callback whenever it
    // needs to compare two items from the list being sorted.
    // As a result, we will get the list sorted by just the "text" field.
    // If we do not pass a callback, Collections.sort will use the default
    // comparison for the class (first by "code", then by "text").
    Collections.sort(codedStrings, comparatorByText);
}

Returning boolean if set is empty

"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True

:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
    return some_set == set()

How to add background image for input type="button"?

If this is a submit button, use <input type="image" src="..." ... />.

http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_IMAGE.html

If you want to specify the image with CSS, you'll have to use type="submit".

Unable to install packages in latest version of RStudio and R Version.3.1.1

Not 100% certain that you have the same problem, but I found out the hard way that my job blocks each mirror site option that was offered and I was getting errors like this:

Installing package into ‘/usr/lib64/R/library’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---
Error in download.file(url, destfile = f, quiet = TRUE) : 
  unsupported URL scheme
Warning: unable to access index for repository https://rweb.crmda.ku.edu/cran/src/contrib
Warning message:
package ‘ggplot2’ is not available (for R version 3.2.2)

Workaround (I am using CentOS)...

install.packages('package_name', dependencies=TRUE, repos='http://cran.rstudio.com/')

I hope this saves someone hours of frustration.

Connecting to remote URL which requires authentication using Java

You can set the default authenticator for http requests like this:

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});

Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)

How does the vim "write with sudo" trick work?

The accepted answer covers it all, so I'll just give another example of a shortcut that I use, for the record.

Add it to your etc/vim/vimrc (or ~/.vimrc):

  • cnoremap w!! execute 'silent! write !sudo tee % >/dev/null' <bar> edit!

Where:

  • cnoremap: tells vim that the following shortcut is to be associated in the command line.
  • w!!: the shortcut itself.
  • execute '...': a command that execute the following string.
  • silent!: run it silently
  • write !sudo tee % >/dev/null: the OP question, added a redirection of messages to NULL to make a clean command
  • <bar> edit!: this trick is the cherry of the cake: it calls also the edit command to reload the buffer and then avoid messages such as the buffer has changed. <bar> is how to write the pipe symbol to separate two commands here.

Hope it helps. See also for other problems:

Get all LI elements in array

QuerySelectorAll will get all the matching elements with defined selector. Here on the example I've used element's name(li tag) to get all of the li present inside the div with navbar element.

_x000D_
_x000D_
    let navbar = document_x000D_
      .getElementById("navbar")_x000D_
      .querySelectorAll('li');_x000D_
_x000D_
    navbar.forEach((item, index) => {_x000D_
      console.log({ index, item })_x000D_
    });
_x000D_
   _x000D_
<div id="navbar">_x000D_
 <ul>_x000D_
  <li id="navbar-One">One</li>_x000D_
  <li id="navbar-Two">Two</li>_x000D_
  <li id="navbar-Three">Three</li>_x000D_
  <li id="navbar-Four">Four</li>_x000D_
  <li id="navbar-Five">Five</li>_x000D_
 </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Apply multiple functions to multiple groupby columns

Ted's answer is amazing. I ended up using a smaller version of that in case anyone is interested. Useful when you are looking for one aggregation that depends on values from multiple columns:

create a dataframe

df=pd.DataFrame({'a': [1,2,3,4,5,6], 'b': [1,1,0,1,1,0], 'c': ['x','x','y','y','z','z']})


   a  b  c
0  1  1  x
1  2  1  x
2  3  0  y
3  4  1  y
4  5  1  z
5  6  0  z

grouping and aggregating with apply (using multiple columns)

df.groupby('c').apply(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

c
x    2.0
y    4.0
z    5.0

grouping and aggregating with aggregate (using multiple columns)

I like this approach since I can still use aggregate. Perhaps people will let me know why apply is needed for getting at multiple columns when doing aggregations on groups.

It seems obvious now, but as long as you don't select the column of interest directly after the groupby, you will have access to all the columns of the dataframe from within your aggregation function.

only access to the selected column

df.groupby('c')['a'].aggregate(lambda x: x[x>1].mean())

access to all columns since selection is after all the magic

df.groupby('c').aggregate(lambda x: x[(x['a']>1) & (x['b']==1)].mean())['a']

or similarly

df.groupby('c').aggregate(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

I hope this helps.

Select <a> which href ends with some string

   $('a[href$="ABC"]')...

Selector documentation can be found at http://docs.jquery.com/Selectors

For attributes:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

How to display a "busy" indicator with jQuery?

You can just show / hide a gif, but you can also embed that to ajaxSetup, so it's called on every ajax request.

$.ajaxSetup({
    beforeSend:function(){
        // show gif here, eg:
        $("#loading").show();
    },
    complete:function(){
        // hide gif here, eg:
        $("#loading").hide();
    }
});

One note is that if you want to do an specific ajax request without having the loading spinner, you can do it like this:

$.ajax({
   global: false,
   // stuff
});

That way the previous $.ajaxSetup we did will not affect the request with global: false.

More details available at: http://api.jquery.com/jQuery.ajaxSetup

Using python PIL to turn a RGB image into a pure black and white image

A PIL only solution for creating a bi-level (black and white) image with a custom threshold:

from PIL import Image
img = Image.open('mB96s.png')
thresh = 200
fn = lambda x : 255 if x > thresh else 0
r = img.convert('L').point(fn, mode='1')
r.save('foo.png')

With just

r = img.convert('1')
r.save('foo.png')

you get a dithered image.

From left to right the input image, the black and white conversion result and the dithered result:

Input Image Black and White Result Dithered Result

You can click on the images to view the unscaled versions.

how to modify the size of a column

This was done using Toad for Oracle 12.8.0.49

ALTER TABLE SCHEMA.TABLENAME 
    MODIFY (COLUMNNAME NEWDATATYPE(LENGTH)) ;

For example,

ALTER TABLE PAYROLL.EMPLOYEES 
    MODIFY (JOBTITLE VARCHAR2(12)) ;

How can I remove an element from a list?

Just wanted to quickly add (because I didn't see it in any of the answers) that, for a named list, you can also do l["name"] <- NULL. For example:

l <- list(a = 1, b = 2, cc = 3)
l['b'] <- NULL

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException: Connection reset by peer

The other side has abruptly aborted the connection in midst of a transaction. That can have many causes which are not controllable from the server side on. E.g. the enduser decided to shutdown the client or change the server abruptly while still interacting with your server, or the client program has crashed, or the enduser's internet connection went down, or the enduser's machine crashed, etc, etc.

Rewrite left outer join involving multiple tables from Informix to Oracle

I'm guessing that you want something like

SELECT tab1.a, tab2.b, tab3.c, tab4.d
  FROM table1 tab1 
       JOIN table2 tab2 ON (tab1.fg = tab2.fg)
       LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
       LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
       LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
                                       tab3.dd = tab5.dd)

App.Config change value

That worked for me in WPF application:

string configPath = Path.Combine(System.Environment.CurrentDirectory, "YourApplication.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
config.AppSettings.Settings["currentLanguage"].Value = "En";
config.Save();

change array size

Used this approach for array of bytes:

Initially:

byte[] bytes = new byte[0];

Whenever required (Need to provide original length for extending):

Array.Resize<byte>(ref bytes, bytes.Length + requiredSize);

Reset:

Array.Resize<byte>(ref bytes, 0);

Typed List Method

Initially:

List<byte> bytes = new List<byte>();

Whenever required:

bytes.AddRange(new byte[length]);

Release/Clear:

bytes.Clear()

Check if a specific value exists at a specific key in any subarray of a multidimensional array

I wrote the following function in order to determine if an multidimensional array partially contains a certain value.

function findKeyValue ($array, $needle, $value, $found = false){
    foreach ($array as $key => $item){
        // Navigate through the array completely.
        if (is_array($item)){
            $found = $this->findKeyValue($item, $needle, $value, $found);
        }

        // If the item is a node, verify if the value of the node contains
        // the given search parameter. E.G.: 'value' <=> 'This contains the value'
        if ( ! empty($key) && $key == $needle && strpos($item, $value) !== false){
            return true;
        }
    }

    return $found;
}

Call the function like this:

$this->findKeyValue($array, $key, $value);

Stored procedure - return identity as output parameter or scalar

Either as recordset or output parameter. The latter has less overhead and I'd tend to use that rather than a single column/row recordset.

If I expected to >1 row I'd use the OUTPUT clause and a recordset

Return values would normally be used for error handling.

How to open a URL in a new Tab using JavaScript or jQuery?

I know your question does not specify if you are trying to open all a tags in a new window or only the external links.

But in case you only want external links to open in a new tab you can do this:

$( 'a[href^="http://"]' ).attr( 'target','_blank' )
$( 'a[href^="https://"]' ).attr( 'target','_blank' )