Programs & Examples On #Tabwidget

Android: Tabs at the BOTTOM

Yes, see: link, but he used xml layouts, not activities to create new tab, so put his xml code (set paddingTop for FrameLayout - 0px) and then write the code:

public class SomeActivity extends ActivityGroup {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

    TabHost tab_host = (TabHost) findViewById(R.id.edit_item_tab_host); 

    tab_host.setup(this.getLocalActivityManager());

    TabSpec ts1 = tab_host.newTabSpec("TAB_DATE"); 
    ts1.setIndicator("tab1"); 
    ts1.setContent(new Intent(this, Registration.class)); 
    tab_host.addTab(ts1); 

    TabSpec ts2 = tab_host.newTabSpec("TAB_GEO"); 
    ts2.setIndicator("tab2"); 
    ts2.setContent(new Intent(this, Login.class)); 
    tab_host.addTab(ts2); 

    TabSpec ts3 = tab_host.newTabSpec("TAB_TEXT"); 
    ts3.setIndicator("tab3"); 
    ts3.setContent(new Intent(this, Registration.class)); 
    tab_host.addTab(ts3); 

    tab_host.setCurrentTab(0);      


}

}

Google Maps API v3: How do I dynamically change the marker icon?

This thread might be dead, but StyledMarker is available for API v3. Just bind the color change you want to the correct DOM event using the addDomListener() method. This example is pretty close to what you want to do. If you look at the page source, change:

google.maps.event.addDomListener(document.getElementById("changeButton"),"click",function() {
  styleIcon.set("color","#00ff00");
  styleIcon.set("text","Go");
});

to something like:

google.maps.event.addDomListener("mouseover",function() {
  styleIcon.set("color","#00ff00");
  styleIcon.set("text","Go");
});

That should be enough to get you moving along.

The Wikipedia page on DOM Events will also help you target the event that you want to capture on the client-side.

Good luck (if you still need it)

Adding to a vector of pair

As many people suggested, you could use std::make_pair.

But I would like to point out another method of doing the same:

revenue.push_back({"string",map[i].second});

push_back() accepts a single parameter, so you could use "{}" to achieve this!

Storing an object in state of a React component?

  1. this.setState({ abc.xyz: 'new value' }); syntax is not allowed. You have to pass the whole object.

    this.setState({abc: {xyz: 'new value'}});
    

    If you have other variables in abc

    var abc = this.state.abc;
    abc.xyz = 'new value';
    this.setState({abc: abc});
    
  2. You can have ordinary variables, if they don't rely on this.props and this.state.

HashMap with multiple values under the same key

Yes and no. The solution is to build a Wrapper clas for your values that contains the 2 (3, or more) values that correspond to your key.

running php script (php function) in linux bash

From the command line, enter this:

php -f filename.php

Make sure that filename.php both includes and executes the function you want to test. Anything you echo out will appear in the console, including errors.

Be wary that often the php.ini for Apache PHP is different from CLI PHP (command line interface).

Reference: https://secure.php.net/manual/en/features.commandline.usage.php

ValueError: Wrong number of items passed - Meaning and suggestions?

for i in range(100):
try:
  #Your code here
  break
except:
  continue

This one worked for me.

Are table names in MySQL case sensitive?

  1. Locate the file at /etc/mysql/my.cnf

  2. Edit the file by adding the following lines:

     [mysqld]
    
     lower_case_table_names=1
    
  3. sudo /etc/init.d/mysql restart

  4. Run mysqladmin -u root -p variables | grep table to check that lower_case_table_names is 1 now

You might need to recreate these tables to make it work.

Node.js/Express.js App Only Works on Port 3000

Refer to this link.

Try to locate the bin>www location and try to change the port number...

Android: show/hide a view using an animation

First of all get the height of the view yo want to saw and make a boolean to save if the view is showing:

int heigth=0;
boolean showing=false;
LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout);

        proDetailsLL.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // gets called after layout has been done but before display
                // so we can get the height then hide the view

                proHeight = proDetailsLL.getHeight(); // Ahaha!  Gotcha

                proDetailsLL.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                proDetailsLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0));
            }
        });

Then call the method for showing hide the view, and change the value of the boolean:

slideInOutAnimation(showing, heigth, layout);
proShowing = !proShowing;

The method:

/**
     * Method to slide in out the layout
     * 
     * @param isShowing
     *            if the layout is showing
     * @param height
     *            the height to slide
     * @param slideLL
     *            the container to show
     */
private void slideInOutAnimation(boolean isShowing, int height, final LinearLayout slideLL, final ImageView arroIV) {

        if (!isShowing) {
        Animation animIn = new Animation() {
        protected void applyTransformation(float interpolatedTime, Transformation t) {
                    super.applyTransformation(interpolatedTime, t);
        // Do relevant calculations here using the interpolatedTime that runs from 0 to 1
        slideLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int) (heigth * interpolatedTime)));

                }
            };
            animIn.setDuration(500);
            slideLL.startAnimation(animIn);
        } else {

            Animation animOut = new Animation() {
                protected void applyTransformation(float interpolatedTime, Transformation t) {
                    super.applyTransformation(interpolatedTime, t);
                    // Do relevant calculations here using the interpolatedTime that runs from 0 to 1


                        slideLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                                (int) (heigth * (1 - interpolatedTime))));

                }
            };
            animOut.setDuration(500);
            slideLL.startAnimation(animOut);


        }

    }

Differences between Oracle JDK and OpenJDK

Also for Java 8 an interesting performance benchmark for reactive (non-blocking) Spring Boot REST application being hosted on various JVMs by AMIS Technology Blog has been published in Nov 2018 showing that, among other differences:

  • OpenJDK has higher CPU usage than OracleJDK,
  • OpenJDK has slightly lower response time than OracleJDK,
  • OpenJDK has higher memory usage than OracleJDK,

For details please see the source article.

Of course YMMV, this is just one of the benchmarks.

How to return part of string before a certain character?

In General a function to return string after substring is

_x000D_
_x000D_
function getStringAfterSubstring(parentString, substring) {_x000D_
    return parentString.substring(parentString.indexOf(substring) + substring.length)_x000D_
}_x000D_
_x000D_
function getStringBeforeSubstring(parentString, substring) {_x000D_
    return parentString.substring(0, parentString.indexOf(substring))_x000D_
}_x000D_
console.log(getStringAfterSubstring('abcxyz123uvw', '123'))_x000D_
console.log(getStringBeforeSubstring('abcxyz123uvw', '123'))
_x000D_
_x000D_
_x000D_

How to center buttons in Twitter Bootstrap 3?

I had this problem. I used

<div class = "col-xs-8 text-center">

On my div containing a few h3 lines, a couple h4 lines and a Bootstrap button. Everything besides the button jumped to the center after I used text-center so I went into my CSS sheet overriding Bootstrap and gave the button a

margin: auto;

which seems to have solved the problem.

REST API - file (ie images) processing - best practices

OP here (I am answering this question after two years, the post made by Daniel Cerecedo was not bad at a time, but the web services are developing very fast)

After three years of full-time software development (with focus also on software architecture, project management and microservice architecture) I definitely choose the second way (but with one general endpoint) as the best one.

If you have a special endpoint for images, it gives you much more power over handling those images.

We have the same REST API (Node.js) for both - mobile apps (iOS/android) and frontend (using React). This is 2017, therefore you don't want to store images locally, you want to upload them to some cloud storage (Google cloud, s3, cloudinary, ...), therefore you want some general handling over them.

Our typical flow is, that as soon as you select an image, it starts uploading on background (usually POST on /images endpoint), returning you the ID after uploading. This is really user-friendly, because user choose an image and then typically proceed with some other fields (i.e. address, name, ...), therefore when he hits "send" button, the image is usually already uploaded. He does not wait and watching the screen saying "uploading...".

The same goes for getting images. Especially thanks to mobile phones and limited mobile data, you don't want to send original images, you want to send resized images, so they do not take that much bandwidth (and to make your mobile apps faster, you often don't want to resize it at all, you want the image that fits perfectly into your view). For this reason, good apps are using something like cloudinary (or we do have our own image server for resizing).

Also, if the data are not private, then you send back to app/frontend just URL and it downloads it from cloud storage directly, which is huge saving of bandwidth and processing time for your server. In our bigger apps there are a lot of terabytes downloaded every month, you don't want to handle that directly on each of your REST API server, which is focused on CRUD operation. You want to handle that at one place (our Imageserver, which have caching etc.) or let cloud services handle all of it.


Cons : The only "cons" which you should think of is "not assigned images". User select images and continue with filling other fields, but then he says "nah" and turn off the app or tab, but meanwhile you successfully uploaded the image. This means you have uploaded an image which is not assigned anywhere.

There are several ways of handling this. The most easiest one is "I don't care", which is a relevant one, if this is not happening very often or you even have desire to store every image user send you (for any reason) and you don't want any deletion.

Another one is easy too - you have CRON and i.e. every week and you delete all unassigned images older than one week.

Redirect parent window from an iframe action

target="_parent" worked great for me. easy and hassle free!

How to Enable ActiveX in Chrome?

anyone who says activex is less secure then NPAPI is crazy. They both allow the exact same access. Yes I've written both. The only reason people think activeX is insecure is because 10+ years ago IE had default settings that allowed a remote site to auto download the plugin.

Declaration of Methods should be Compatible with Parent Methods in PHP

if you wanna keep OOP form without turning any error off, you can also:

class A
{
    public function foo() {
        ;
    }
}
class B extends A
{
    /*instead of : 
    public function foo($a, $b, $c) {*/
    public function foo() {
        list($a, $b, $c) = func_get_args();
        // ...

    }
}

integrating barcode scanner into php application?

If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.

How to dynamically load a Python class

If you're using Django you can use this. Yes i'm aware OP did not ask for django, but i ran across this question looking for a Django solution, didn't find one, and put it here for the next boy/gal that looks for it.

# It's available for v1.7+
# https://github.com/django/django/blob/stable/1.7.x/django/utils/module_loading.py
from django.utils.module_loading import import_string

Klass = import_string('path.to.module.Klass')
func = import_string('path.to.module.func')
var = import_string('path.to.module.var')

Keep in mind, if you want to import something that doesn't have a ., like re or argparse use:

re = __import__('re')

count distinct values in spreadsheet

=iferror(counta(unique(A1:A100))) counts number of unique cells from A1 to A100

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

For me, this error was happening on localhost, but it disappeared when routing it through ngrok and was replaced with a MUCH more helpful error (net::ERR_INCOMPLETE_CHUNKED_ENCODING) that led me here:

https://stackoverflow.com/a/29969400

Basically, the Kestrel server I was using was saying it was chunked output, but not terminating it properly. I double checked it with Fiddler which confirmed the error.

javascript cell number validation

If you type:

if { number.value.length!= 10}...     

It will sure work because the value is the quantity which will be driven from the object.

Check for special characters (/*-+_@&$#%) in a string?

String test_string = "tesintg#$234524@#";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
  // Good-to-go
}

An example can be found here: http://ideone.com/B1HxA

How to keep a VMWare VM's clock in sync?

I added the following job to crontab. It is hacky but i think should work.

*/5 * * * * service ntpd stop && ntpdate pool.ntp.org && service ntpd start

It stops ntpd service updates from service and starts ntpd again

Cannot install packages inside docker Ubuntu image

I found that mounting a local volume over /tmp can cause permission issues when the "apt-get update" runs, which prevents the package cache from being populated. Hopefully, this isn't something most people do, but it's something else to look for if you see this issue.

JSON.Net Self referencing loop detected

You must set Preserving Object References:

var jsonSerializerSettings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};

Then call your query var q = (from a in db.Events where a.Active select a).ToList(); like

string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(q, jsonSerializerSettings);

See: https://www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm

How to search for rows containing a substring?

Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%" - but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.

It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.

To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%".

Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.

Updated answer to reflect question update:

I say that doing a WHERE field LIKE "%value%" is slower than WHERE field LIKE "value%" if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:

1/ If you do SELECT field FROM table WHERE field LIKE "%value%", MySQL will scan the entire table, and only send the fields containing "value".

2/ If you do SELECT field FROM table and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.

Solution: Please do use the WHERE clause, and use EXPLAIN to see the performance.

jQuery Set Cursor Position in Text Area

I found a solution that works for me:

$.fn.setCursorPosition = function(position){
    if(this.length == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    if(this.length == 0) return this;
    var input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
}

$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
            return this;
}

Now you can move the focus to the end of any element by calling:

$(element).focusEnd();

Or you specify the position.

$(element).setCursorPosition(3); // This will focus on the third character.

JWT (JSON Web Token) library for Java

This library seems to work well: https://code.google.com/p/jsontoken/ .

It depends on Google Guava. Here are the Maven artifacts:

<dependency>
    <groupId>com.googlecode.jsontoken</groupId>
    <artifactId>jsontoken</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>

The library is in fact used by Google Wallet.

Here is how to create a jwt, and to verify it and deserialize it:

import java.security.InvalidKeyException;
import java.security.SignatureException;
import java.util.Calendar;
import java.util.List;

import net.oauth.jsontoken.JsonToken;
import net.oauth.jsontoken.JsonTokenParser;
import net.oauth.jsontoken.crypto.HmacSHA256Signer;
import net.oauth.jsontoken.crypto.HmacSHA256Verifier;
import net.oauth.jsontoken.crypto.SignatureAlgorithm;
import net.oauth.jsontoken.crypto.Verifier;
import net.oauth.jsontoken.discovery.VerifierProvider;
import net.oauth.jsontoken.discovery.VerifierProviders;

import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;

import com.google.common.collect.Lists;
import com.google.gson.JsonObject;


/**
 * Provides static methods for creating and verifying access tokens and such. 
 * @author davidm
 *
 */
public class AuthHelper {

    private static final String AUDIENCE = "NotReallyImportant";

    private static final String ISSUER = "YourCompanyOrAppNameHere";

    private static final String SIGNING_KEY = "LongAndHardToGuessValueWithSpecialCharacters@^($%*$%";

    /**
     * Creates a json web token which is a digitally signed token that contains a payload (e.g. userId to identify 
     * the user). The signing key is secret. That ensures that the token is authentic and has not been modified.
     * Using a jwt eliminates the need to store authentication session information in a database.
     * @param userId
     * @param durationDays
     * @return
     */
    public static String createJsonWebToken(String userId, Long durationDays)    {
        //Current time and signing algorithm
        Calendar cal = Calendar.getInstance();
        HmacSHA256Signer signer;
        try {
            signer = new HmacSHA256Signer(ISSUER, null, SIGNING_KEY.getBytes());
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }

        //Configure JSON token
        JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
        token.setAudience(AUDIENCE);
        token.setIssuedAt(new org.joda.time.Instant(cal.getTimeInMillis()));
        token.setExpiration(new org.joda.time.Instant(cal.getTimeInMillis() + 1000L * 60L * 60L * 24L * durationDays));

        //Configure request object, which provides information of the item
        JsonObject request = new JsonObject();
        request.addProperty("userId", userId);

        JsonObject payload = token.getPayloadAsJsonObject();
        payload.add("info", request);

        try {
            return token.serializeAndSign();
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Verifies a json web token's validity and extracts the user id and other information from it. 
     * @param token
     * @return
     * @throws SignatureException
     * @throws InvalidKeyException
     */
    public static TokenInfo verifyToken(String token)  
    {
        try {
            final Verifier hmacVerifier = new HmacSHA256Verifier(SIGNING_KEY.getBytes());

            VerifierProvider hmacLocator = new VerifierProvider() {

                @Override
                public List<Verifier> findVerifier(String id, String key){
                    return Lists.newArrayList(hmacVerifier);
                }
            };
            VerifierProviders locators = new VerifierProviders();
            locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator);
            net.oauth.jsontoken.Checker checker = new net.oauth.jsontoken.Checker(){

                @Override
                public void check(JsonObject payload) throws SignatureException {
                    // don't throw - allow anything
                }

            };
            //Ignore Audience does not mean that the Signature is ignored
            JsonTokenParser parser = new JsonTokenParser(locators,
                    checker);
            JsonToken jt;
            try {
                jt = parser.verifyAndDeserialize(token);
            } catch (SignatureException e) {
                throw new RuntimeException(e);
            }
            JsonObject payload = jt.getPayloadAsJsonObject();
            TokenInfo t = new TokenInfo();
            String issuer = payload.getAsJsonPrimitive("iss").getAsString();
            String userIdString =  payload.getAsJsonObject("info").getAsJsonPrimitive("userId").getAsString();
            if (issuer.equals(ISSUER) && !StringUtils.isBlank(userIdString))
            {
                t.setUserId(new ObjectId(userIdString));
                t.setIssued(new DateTime(payload.getAsJsonPrimitive("iat").getAsLong()));
                t.setExpires(new DateTime(payload.getAsJsonPrimitive("exp").getAsLong()));
                return t;
            }
            else
            {
                return null;
            }
        } catch (InvalidKeyException e1) {
            throw new RuntimeException(e1);
        }
    }


}

public class TokenInfo {
    private ObjectId userId;
    private DateTime issued;
    private DateTime expires;
    public ObjectId getUserId() {
        return userId;
    }
    public void setUserId(ObjectId userId) {
        this.userId = userId;
    }
    public DateTime getIssued() {
        return issued;
    }
    public void setIssued(DateTime issued) {
        this.issued = issued;
    }
    public DateTime getExpires() {
        return expires;
    }
    public void setExpires(DateTime expires) {
        this.expires = expires;
    }
}

This is based on code here: https://developers.google.com/wallet/instant-buy/about-jwts And Here: https://code.google.com/p/wallet-online-sample-java/source/browse/src/com/google/wallet/online/jwt/util/WalletOnlineService.java?r=08b3333bd7260b20846d7d96d3cf15be8a128dfa

Windows task scheduler error 101 launch failure code 2147943785

I have the same today on Win7.x64, this solve it.

Right Click MyComputer > Manage > Local Users and Groups > Groups > Administrators double click > your name should be there, if not press add...

List of ANSI color escape sequences

It's related absolutely to your terminal. VTE doesn't support blink, If you use gnome-terminal, tilda, guake, terminator, xfce4-terminal and so on according to VTE, you won't have blink.
If you use or want to use blink on VTE, you have to use xterm.
You can use infocmp command with terminal name:

#infocmp vt100
#infocmp xterm
#infocmp vte

For example :

# infocmp vte
#   Reconstructed via infocmp from file: /usr/share/terminfo/v/vte
vte|VTE aka GNOME Terminal,
    am, bce, mir, msgr, xenl,
    colors#8, cols#80, it#8, lines#24, ncv#16, pairs#64,
    acsc=``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~,
    bel=^G, bold=\E[1m, civis=\E[?25l, clear=\E[H\E[2J,
    cnorm=\E[?25h, cr=^M, csr=\E[%i%p1%d;%p2%dr,
    cub=\E[%p1%dD, cub1=^H, cud=\E[%p1%dB, cud1=^J,
    cuf=\E[%p1%dC, cuf1=\E[C, cup=\E[%i%p1%d;%p2%dH,
    cuu=\E[%p1%dA, cuu1=\E[A, dch=\E[%p1%dP, dch1=\E[P,
    dim=\E[2m, dl=\E[%p1%dM, dl1=\E[M, ech=\E[%p1%dX, ed=\E[J,
    el=\E[K, enacs=\E)0, home=\E[H, hpa=\E[%i%p1%dG, ht=^I,
    hts=\EH, il=\E[%p1%dL, il1=\E[L, ind=^J, invis=\E[8m,
    is2=\E[m\E[?7h\E[4l\E>\E7\E[r\E[?1;3;4;6l\E8,
    kDC=\E[3;2~, kEND=\E[1;2F, kHOM=\E[1;2H, kIC=\E[2;2~,
    kLFT=\E[1;2D, kNXT=\E[6;2~, kPRV=\E[5;2~, kRIT=\E[1;2C,
    kb2=\E[E, kbs=\177, kcbt=\E[Z, kcub1=\EOD, kcud1=\EOB,
    kcuf1=\EOC, kcuu1=\EOA, kdch1=\E[3~, kend=\EOF, kf1=\EOP,
    kf10=\E[21~, kf11=\E[23~, kf12=\E[24~, kf13=\E[1;2P,
    kf14=\E[1;2Q, kf15=\E[1;2R, kf16=\E[1;2S, kf17=\E[15;2~,
    kf18=\E[17;2~, kf19=\E[18;2~, kf2=\EOQ, kf20=\E[19;2~,
    kf21=\E[20;2~, kf22=\E[21;2~, kf23=\E[23;2~,
    kf24=\E[24;2~, kf25=\E[1;5P, kf26=\E[1;5Q, kf27=\E[1;5R,
    kf28=\E[1;5S, kf29=\E[15;5~, kf3=\EOR, kf30=\E[17;5~,
    kf31=\E[18;5~, kf32=\E[19;5~, kf33=\E[20;5~,
    kf34=\E[21;5~, kf35=\E[23;5~, kf36=\E[24;5~,
    kf37=\E[1;6P, kf38=\E[1;6Q, kf39=\E[1;6R, kf4=\EOS,
    kf40=\E[1;6S, kf41=\E[15;6~, kf42=\E[17;6~,
    kf43=\E[18;6~, kf44=\E[19;6~, kf45=\E[20;6~,
    kf46=\E[21;6~, kf47=\E[23;6~, kf48=\E[24;6~,
    kf49=\E[1;3P, kf5=\E[15~, kf50=\E[1;3Q, kf51=\E[1;3R,
    kf52=\E[1;3S, kf53=\E[15;3~, kf54=\E[17;3~,
    kf55=\E[18;3~, kf56=\E[19;3~, kf57=\E[20;3~,
    kf58=\E[21;3~, kf59=\E[23;3~, kf6=\E[17~, kf60=\E[24;3~,
    kf61=\E[1;4P, kf62=\E[1;4Q, kf63=\E[1;4R, kf7=\E[18~,
    kf8=\E[19~, kf9=\E[20~, kfnd=\E[1~, khome=\EOH,
    kich1=\E[2~, kind=\E[1;2B, kmous=\E[M, knp=\E[6~,
    kpp=\E[5~, kri=\E[1;2A, kslt=\E[4~, meml=\El, memu=\Em,
    op=\E[39;49m, rc=\E8, rev=\E[7m, ri=\EM, ritm=\E[23m,
    rmacs=^O, rmam=\E[?7l, rmcup=\E[2J\E[?47l\E8, rmir=\E[4l,
    rmkx=\E[?1l\E>, rmso=\E[m, rmul=\E[m, rs1=\Ec,
    rs2=\E7\E[r\E8\E[m\E[?7h\E[!p\E[?1;3;4;6l\E[4l\E>\E[?1000l\E[?25h,
    sc=\E7, setab=\E[4%p1%dm, setaf=\E[3%p1%dm,
    sgr=\E[0%?%p6%t;1%;%?%p2%t;4%;%?%p5%t;2%;%?%p7%t;8%;%?%p1%p3%|%t;7%;m%?%p9%t\016%e\017%;,
    sgr0=\E[0m\017, sitm=\E[3m, smacs=^N, smam=\E[?7h,
    smcup=\E7\E[?47h, smir=\E[4h, smkx=\E[?1h\E=, smso=\E[7m,
    smul=\E[4m, tbc=\E[3g, u6=\E[%i%d;%dR, u7=\E[6n,
    u8=\E[?%[;0123456789]c, u9=\E[c, vpa=\E[%i%p1%dd,

Oracle 11g Express Edition for Windows 64bit?

This is a very useful question. It has 5 different helpful answers that say quite different but complementary things (surprising, eh?). This answer combines those answers into a more useful form as well as adding two more solutions.

There is no Oracle Express Edition for 64 bit Windows. See this official [but unanswered] forum thread. Therefore, these are the classes of solutions:

  • Pay. The paid versions of Oracle (Standard/Enterprise) support 64-bit Windows.
  • Hack. Many people have successfully installed the 32 bit Oracle XE software on 64 bit Windows. This blog post seems to be the one most often cited as helpful. This is unsupported, of course, and session trace is known to fail. But for many folks this is a good solution.
  • VM. If your goal is simply to run Oracle on a 64 bit Windows machine, then running Oracle in a Virtual Machine may be a good solution. VirtualBox is a natural choice because it's free and Oracle provides pre-configured VMs with Oracle DB installed. VMWare or other virtualization systems work equally well.
  • Develop only. Many users want Oracle XE just to learn Oracle or to test an application with Oracle. If that's your requirement, then Oracle Enterprise Edition (including support for 64-bit Windows) is free "only for the purpose of developing, testing, prototyping and demonstrating your application".

How to render a DateTime object in a Twig template

Although you can use the

{{ game.gameDate|date('Y-m-d') }}

approach, keep in mind that this version does not honor the user locale, which should not be a problem with a site used by only users of one nationality. International users should display the game date totally different, like extending the \DateTime class, and adding a __toString() method to it that checks the locale and acts accordingly.

Edit:

As pointed out by @Nic in a comment, if you use the Intl extension of Twig, you will have a localizeddate filter available, which shows the date in the user’s locale. This way you can drop my previous idea of extending \DateTime.

How can I split a string with a string delimiter?

.Split(new string[] { "is Marco and" }, StringSplitOptions.None)

Consider the spaces surronding "is Marco and". Do you want to include the spaces in your result, or do you want them removed? It's quite possible that you want to use " is Marco and " as separator...

Where should my npm modules be installed on Mac OS X?

/usr/local/lib/node_modules is the correct directory for globally installed node modules.

/usr/local/share/npm/lib/node_modules makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:

/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules

The latter seems to be node modules that came with Node, e.g., lodash, when the former is Node modules that I installed using npm.

When should I use h:outputLink instead of h:commandLink?

I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink

What is __init__.py for?

One thing __init__.py allows is converting a module to a package without breaking the API or creating extraneous nested namespaces or private modules*. This helps when I want to extend a namespace.

If I have a file util.py containing

def foo():
    ...

then users will access foo with

from util import foo

If I then want to add utility functions for database interaction, and I want them to have their own namespace under util, I'll need a new directory**, and to keep API compatibility (so that from util import foo still works), I'll call it util/. I could move util.py into util/ like so,

util/
  __init__.py
  util.py
  db.py

and in util/__init__.py do

from util import *

but this is redundant. Instead of having a util/util.py file, we can just put the util.py contents in __init__.py and the user can now

from util import foo
from util.db import check_schema

I think this nicely highlights how a util package's __init__.py acts in a similar way to a util module

* this is hinted at in the other answers, but I want to highlight it here
** short of employing import gymnastics. Note it won't work to create a new package with the same name as the file, see this

Location Services not working in iOS 8

This is issue with ios 8 Add this to your code

if (IS_OS_8_OR_LATER)
{
    [locationmanager requestWhenInUseAuthorization];

    [locationmanager requestAlwaysAuthorization];
}

and to info.plist:

 <key>NSLocationUsageDescription</key>
 <string>I need location</string>
 <key>NSLocationAlwaysUsageDescription</key>
 <string>I need location</string>
 <key>NSLocationWhenInUseUsageDescription</key>
 <string>I need location</string>

Node.js: what is ENOSPC error and how to solve?

If your /tmp mount on a linux filesystem is mounted as overflow (often sized at 1MB), this is likely due to you not specifying /tmp as its own partition and your root filesystem filled up and /tmp was remounted as a fallback.

To fix this after you’ve cleared space, just unmount the fallback and it should remount at its original point:

sudo umount overflow

Php - testing if a radio button is selected and get the value

It's pretty simple, take a look at the code below:

The form:

<form action="result.php" method="post">
  Answer 1 <input type="radio" name="ans" value="ans1" /><br />
  Answer 2 <input type="radio" name="ans" value="ans2"  /><br />
  Answer 3 <input type="radio" name="ans" value="ans3"  /><br />
  Answer 4 <input type="radio" name="ans" value="ans4"  /><br />
  <input type="submit" value="submit" />
</form>

PHP code:

<?php 

$answer = $_POST['ans'];  
if ($answer == "ans1") {          
    echo 'Correct';      
}
else {
    echo 'Incorrect';
}          
?>

Is there a query language for JSON?

I'll second the notion of just using your own javascript, but for something a bit more sophisticated you might look at dojo data. Haven't used it but it looks like it gives you roughly the kind of query interface you're looking for.

Creating the Singleton design pattern in PHP5

All this complexity ("late static binding" ... harumph) is, to me, simply a sign of PHP's broken object/class model. If class objects were first-class objects (see Python), then "$_instance" would be a class instance variable -- a member of the class object, as opposed to a member/property of its instances, and also as opposed to shared by its descendants. In the Smalltalk world, this is the difference between a "class variable" and a "class instance variable".

In PHP, it looks to me as though we need to take to heart the guidance that patterns are a guide towards writing code -- we might perhaps think about a Singleton template, but trying to write code that inherits from an actual "Singleton" class looks misguided for PHP (though I supposed some enterprising soul could create a suitable SVN keyword).

I will continue to just code each singleton separately, using a shared template.

Notice that I'm absolutely staying OUT of the singletons-are-evil discussion, life is too short.

Jenkins: Can comments be added to a Jenkinsfile?

The official Jenkins documentation only mentions single line commands like the following:

// Declarative //

and (see)

pipeline {
    /* insert Declarative Pipeline here */
}

The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:

/* a standalone multiline comment
   spanning two lines */
println "hello" /* a multiline comment starting
                   at the end of a statement */
println 1 /* one */ + 2 /* two */

or

/**
 * such a nice comment
 */

How to tell if a <script> tag failed to load

It was proposed to set a timeout and then assume load failure after a timeout.

setTimeout(fireCustomOnerror, 4000);

The problem with that approach is that the assumption is based on chance. After your timeout expires, the request is still pending. The request for the pending script may load, even after the programmer assumed that load won't happen.

If the request could be canceled, then the program could wait for a period, then cancel the request.

How to get first item from a java.util.Set?

Vector has some handy features:

Vector<String> siteIdVector = new Vector<>(siteIdSet);
String first = siteIdVector.firstElement();
String last = siteIdVector.lastElement();

But I do agree - this may have unintended consequences, since the underling set is not guaranteed to be ordered.

How to place Text and an Image next to each other in HTML?

img {
    float:left;
}
h3 {
    float:right;
}

jsFiddle example

Note that you will probably want to use the style clear:both on whatever elements comes after the code you provided so that it doesn't slide up directly beneath the floated elements.

How to show PIL Image in ipython notebook

A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

pil_im = Image.open('image.jpg')
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()

Class is not abstract and does not override abstract method

Both classes Rectangle and Ellipse need to override both of the abstract methods.

To work around this, you have 3 options:

  • Add the two methods
  • Make each class that extends Shape abstract
  • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

    abstract class Shape {
        // ...
        void draw(Graphics g);
    }
    

And

    class Rectangle extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

Finally

    class Ellipse extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

And you can switch in between them, like so:

    Shape shape = new Ellipse();
    shape.draw(/* ... */);

    shape = new Rectangle();
    shape.draw(/* ... */);

Again, just an example.

how to print a string to console in c++

yes it's possible to print a string to the console.

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string strMytestString("hello world");
    cout << strMytestString;
    return 0;
}

stdafx.h isn't pertinent to the solution, everything else is.

#pragma once vs include guards?

There's an related question to which I answered:

#pragma once does have one drawback (other than being non-standard) and that is if you have the same file in different locations (we have this because our build system copies files around) then the compiler will think these are different files.

I'm adding the answer here too in case someone stumbles over this question and not the other.

What REALLY happens when you don't free after malloc?

You are absolutely correct in that respect. In small trivial programs where a variable must exist until the death of the program, there is no real benefit to deallocating the memory.

In fact, I had once been involved in a project where each execution of the program was very complex but relatively short-lived, and the decision was to just keep memory allocated and not destabilize the project by making mistakes deallocating it.

That being said, in most programs this is not really an option, or it can lead you to run out of memory.

Discard all and get clean copy of latest revision?

Those steps should be able to be shortened down to:

hg pull
hg update -r MY_BRANCH -C

The -C flag tells the update command to discard all local changes before updating.

However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge extension for that:

hg pull
hg update -r MY_BRANCH -C
hg purge

In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.

How can I read command line parameters from an R script?

A few points:

  1. Command-line parameters are accessible via commandArgs(), so see help(commandArgs) for an overview.

  2. You can use Rscript.exe on all platforms, including Windows. It will support commandArgs(). littler could be ported to Windows but lives right now only on OS X and Linux.

  3. There are two add-on packages on CRAN -- getopt and optparse -- which were both written for command-line parsing.

Edit in Nov 2015: New alternatives have appeared and I wholeheartedly recommend docopt.

How do I make a JSON object with multiple arrays?

Using below method pass any value which is any array:

Input parameter: url, like Example: "/node/[any int value of array]/anyKeyWhichInArray" Example: "cars/Nissan/[0]/model"

It can be used for any response:

    public String getResponseParameterThroughUrl(Response r, String url) throws JsonProcessingException, IOException {
    String value = "";
    String[] xpathOrder = url.split("/");
    ObjectMapper objectMapper = new ObjectMapper();
    String responseData = r.getBody().asString();       
    JSONObject jsonObject = new JSONObject(responseData);
    byte[] jsonData = jsonObject.toString().getBytes();
    JsonNode rootNode = objectMapper.readTree(jsonData);
    JsonNode node = null;
    for(int i=1;i<xpathOrder.length;i++) {
        if(node==null)
            node = rootNode;
        if(xpathOrder[i].contains("[")){
            xpathOrder[i] = xpathOrder[i].replace("[", "");
            xpathOrder[i] = xpathOrder[i].replace("]", "");
            node = node.get(Integer.parseInt(xpathOrder[i]));
        }
        else
            node = node.path(xpathOrder[i]);
    }
    value = node.asText();
    return value;
}

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

Is either GET or POST more secure than the other?

Post is the most secured along with SSL installed because its transmitted in the message body.

But all of these methods are insecure because the 7 bit protocol it uses underneath it is hack-able with escapement. Even through a level 4 web application firewall.

Sockets are no guarantee either... Even though its more secure in certain ways.

How to extract week number in sql

Use 'dd-mon-yyyy' if you are using the 2nd date format specified in your answer. Ex:

to_date(<column name>,'dd-mon-yyyy')

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Well, I can think of a CSS hack that will resolve this issue.

You could add the following line in your CSS file:

* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; } 

The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.

Add back button to action bar

this one worked for me:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_your_activity);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // ... other stuff
}

@Override
public boolean onSupportNavigateUp(){
    finish();
    return true;
}

The method onSupportNavigateUp() is called when you use the back button in the SupportActionBar.

Calling multiple JavaScript functions on a button click

At times it gives syntax error that "return is not a function" so in that case just remove return and it will work fine :) as shown below

OnClientClick="var b = validateView(); if(b) var b = ShowDiv1(); b;"

All ASP.NET Web API controllers return 404

WebApiConfig.Register(GlobalConfiguration.Configuration);

Should be first in App_start event. I have tried it at last position in APP_start event, but that did not work.

How can I properly handle 404 in ASP.NET MVC?

Posting an answer since my comment was too long...

It's both a comment and questions to the unicorn post/answer:

https://stackoverflow.com/a/7499406/687549

I prefer this answer over the others for it's simplicity and the fact that apparently some folks at Microsoft were consulted. I got three questions however and if they can be answered then I will call this answer the holy grail of all 404/500 error answers on the interwebs for an ASP.NET MVC (x) app.

@Pure.Krome

  1. Can you update your answer with the SEO stuff from the comments pointed out by GWB (there was never any mentioning of this in your answer) - <customErrors mode="On" redirectMode="ResponseRewrite"> and <httpErrors errorMode="Custom" existingResponse="Replace">?

  2. Can you ask your ASP.NET team friends if it is okay to do it like that - would be nice to have some confirmation - maybe it's a big no-no to change redirectMode and existingResponse in this way to be able to play nicely with SEO?!

  3. Can you add some clarification surrounding all that stuff (customErrors redirectMode="ResponseRewrite", customErrors redirectMode="ResponseRedirect", httpErrors errorMode="Custom" existingResponse="Replace", REMOVE customErrors COMPLETELY as someone suggested) after talking to your friends at Microsoft?

As I was saying; it would be supernice if we could make your answer more complete as this seem to be a fairly popular question with 54 000+ views.

Update: Unicorn answer does a 302 Found and a 200 OK and cannot be changed to only return 404 using a route. It has to be a physical file which is not very MVC:ish. So moving on to another solution. Too bad because this seemed to be the ultimate MVC:ish answer this far.

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

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

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

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

Exploits of a Mom

(xkcd)

Getting the class name of an instance?

Apart from grabbing the special __name__ attribute, you might find yourself in need of the qualified name for a given class/function. This is done by grabbing the types __qualname__.

In most cases, these will be exactly the same, but, when dealing with nested classes/methods these differ in the output you get. For example:

class Spam:
    def meth(self):
        pass
    class Bar:
        pass

>>> s = Spam()
>>> type(s).__name__ 
'Spam'
>>> type(s).__qualname__
'Spam'
>>> type(s).Bar.__name__       # type not needed here
'Bar'
>>> type(s).Bar.__qualname__   # type not needed here 
'Spam.Bar'
>>> type(s).meth.__name__
'meth'
>>> type(s).meth.__qualname__
'Spam.meth'

Since introspection is what you're after, this is always you might want to consider.

PHP Echo text Color

If it echoing out to a browser, you should use CSS. This would require also having the comment wrapped in an HTML tag. Something like:

echo '<p style="color: red; text-align: center">
      Request has been sent. Please wait for my reply!
      </p>';

How to apply CSS to iframe?

When you say "doc.open()" it means you can write whatever HTML tag inside the iframe, so you should write all the basic tags for the HTML page and if you want to have a CSS link in your iframe head just write an iframe with CSS link in it. I give you an example:

doc.open();

doc.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><meta http-quiv="Content-Type" content="text/html; charset=utf-8"/><title>Print Frame</title><link rel="stylesheet" type="text/css" href="/css/print.css"/></head><body><table id="' + gridId + 'Printable' + '" class="print" >' + out + '</table></body></html>');

doc.close();

Java Hashmap: How to get key from value?

try this:

static String getKeyFromValue(LinkedHashMap<String, String> map,String value) {
    for (int x=0;x<map.size();x++){
        if( String.valueOf( (new ArrayList<String>(map.values())).get(x) ).equals(value))
            return String.valueOf((new ArrayList<String>(map.keySet())).get(x));
    }
    return null;
}

How to add element in List while iterating in java?

You can't use a foreach statement for that. The foreach is using internally an iterator:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

(From ArrayList javadoc)

In the foreach statement you don't have access to the iterator's add method and in any case that's still not the type of add that you want because it does not append at the end. You'll need to traverse the list manually:

int listSize = list.size();
for(int i = 0; i < listSize; ++i)
  list.add("whatever");

Note that this is only efficient for Lists that allow random access. You can check for this feature by checking whether the list implements the RandomAccess marker interface. An ArrayList has random access. A linked list does not.

Type safety: Unchecked cast

The problem is that a cast is a runtime check - but due to type erasure, at runtime there's actually no difference between a HashMap<String,String> and HashMap<Foo,Bar> for any other Foo and Bar.

Use @SuppressWarnings("unchecked") and hold your nose. Oh, and campaign for reified generics in Java :)

VBA error 1004 - select method of range class failed

You can't select a range without having first selected the sheet it is in. Try to select the sheet first and see if you still get the problem:

sourceSheetSum.Select
sourceSheetSum.Range("C3").Select

Yarn install command error No such file or directory: 'install'

For Ubuntu 18.04.4 LTS I just followed the official instructions: https://classic.yarnpkg.com/en/docs/install#debian-stable

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt update && sudo apt install yarn

No need to do:

sudo apt remove cmdtest

That is only necessary on Ubuntu 17.04.* I think.

I hope it helps!

How to allow http content within an iframe on a https site

Using Google as the SSL proxy is not working currently,

Why?

If you opened any page from google, you will find there is a x-frame-options field in the header. Google response header

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe> or <object>. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

(Quote from MDN)

One of the solution

Below is my work around for this problem:

Upload the content to AWS S3, and it will create a https link for the resource.
Notice: set the permission to the html file for allowing everyone view it.

After that, we can using it as the src of iframe in the https websites. AWS

How to find the kafka version in linux

Not sure if there's a convenient way, but you can just inspect your kafka/libs folder. You should see files like kafka_2.10-0.8.2-beta.jar, where 2.10 is Scala version and 0.8.2-beta is Kafka version.

'LIKE ('%this%' OR '%that%') and something=else' not working

Do you have something against splitting it up?

...FROM <blah> 
   WHERE 
     (fieldA LIKE '%THIS%' OR fieldA LIKE '%THAT%') 
     AND something = else

How do you remove the title text from the Android ActionBar?

I am new to Android so maybe I am wrong...but to solve this problem cant we just go to the manifest and remove the activity label

<activity
        android:name=".Bcft"
        android:screenOrientation="portrait"

        **android:label="" >**

Worked for me....

Why does the C++ STL not provide any "tree" containers?

Reading through the answers here the common named reasons are that one cannot iterate through the tree or that the tree does not assume the similar interface to other STL containers and one could not use STL algorithms with such tree structure.

Having that in mind I tried to design my own tree data structure which will provide STL-like interface and will be usable with existing STL algorthims as much as possible.

My idea was that the tree must be based on the existing STL containers and that it must not hide the container, so that it will be accessible to use with STL algorithms.

The other important feature the tree must provide is the traversing iterators.

Here is what I was able to come up with: https://github.com/cppfw/utki/blob/master/src/utki/tree.hpp

And here are the tests: https://github.com/cppfw/utki/blob/master/tests/tree/tests.cpp

Redirect pages in JSP?

<%
    String redirectURL = "http://whatever.com/myJSPFile.jsp";
    response.sendRedirect(redirectURL);
%>

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.

Set new id with jQuery

EDIT: based on your comment and assuming that this is the element that is cloned.

 $(this).clone()
        .attr( 'id', this.id + '_' + new_id )
        .attr( 'name', this.name + '_' + new_id )
        .val( 'test' )
        .appendTo('#someElement');

Full Example

 <script type="text/javascript">
    var new_id = 0;
    $(document).ready( function() {
       $('#container > input[type=button]').click( function() {
            var oldinp = $('input#inp')[0];
            var newinp = $(oldinp).clone()
                                  .attr('id',oldinp.id + new_id )
                                  .attr('name',oldinp.name + new_id )
                                  .val('test')
                                  .appendTo($('#container'));
            $('#container').append('<br>');
            new_id++;
        });
     });
 </script>


 <div id="container">
 <input type="button" value="Clone" /><br/>
 <input id="inp" name="inp" type="text" value="hmmm" /><br/>
 </div>

Remove style attribute from HTML tags

You could handle it client side, the easiest would be with jQuery. Something like:

$("#tinyMce p").removeAttr("style");

How do I find out which process is locking a file using .NET?

This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.

C#:

using System.Management; 
using System.IO;   

static class Module1 
{ 
static internal ArrayList myProcessArray = new ArrayList(); 
private static Process myProcess; 

public static void Main() 
{ 

    string strFile = "c:\\windows\\system32\\msi.dll"; 
    ArrayList a = getFileProcesses(strFile); 
    foreach (Process p in a) { 
        Debug.Print(p.ProcessName); 
    } 
} 


private static ArrayList getFileProcesses(string strFile) 
{ 
    myProcessArray.Clear(); 
    Process[] processes = Process.GetProcesses; 
    int i = 0; 
    for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) { 
        myProcess = processes(i); 
        if (!myProcess.HasExited) { 
            try { 
                ProcessModuleCollection modules = myProcess.Modules; 
                int j = 0; 
                for (j = 0; j <= modules.Count - 1; j++) { 
                    if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) { 
                        myProcessArray.Add(myProcess); 
                        break; // TODO: might not be correct. Was : Exit For 
                    } 
                } 
            } 
            catch (Exception exception) { 
            } 
            //MsgBox(("Error : " & exception.Message)) 
        } 
    } 
    return myProcessArray; 
} 
} 

VB.Net:

Imports System.Management
Imports System.IO

Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process

Sub Main()

    Dim strFile As String = "c:\windows\system32\msi.dll"
    Dim a As ArrayList = getFileProcesses(strFile)
    For Each p As Process In a
        Debug.Print(p.ProcessName)
    Next
End Sub


Private Function getFileProcesses(ByVal strFile As String) As ArrayList
    myProcessArray.Clear()
    Dim processes As Process() = Process.GetProcesses
    Dim i As Integer
    For i = 0 To processes.GetUpperBound(0) - 1
        myProcess = processes(i)
        If Not myProcess.HasExited Then
            Try
                Dim modules As ProcessModuleCollection = myProcess.Modules
                Dim j As Integer
                For j = 0 To modules.Count - 1
                    If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
                        myProcessArray.Add(myProcess)
                        Exit For
                    End If
                Next j
            Catch exception As Exception
                'MsgBox(("Error : " & exception.Message))
            End Try
        End If
    Next i
    Return myProcessArray
End Function
End Module

How to set Spinner Default by its Value instead of Position?

You can do it easily like this.

String cls=student.getStudentClass();
class_spinner.setSelection(classArray.indexOf(cls),true);

HTML5 <video> element on Android

I've just done some experimentation with this, and from what I can tell you need three things:

  1. You must not use the type attribute when calling the video.
  2. You must manually call video.play()
  3. The video must be encoded to some quite strict parameters; using the iPhone setting on Handbrake with the 'Web Optimized' button checked usually does the trick.

Have a look at the demo on this page: http://broken-links.com/tests/video/

This works, AFAIK, in all video-enabled desktop browsers, iPhone and Android.

Here's the markup:

<video id="video" autobuffer height="240" width="360">
<source src="BigBuck.m4v">
<source src="BigBuck.webm" type="video/webm">
<source src="BigBuck.theora.ogv" type="video/ogg">
</video>

And I have this in the JS:

var video = document.getElementById('video');
video.addEventListener('click',function(){
  video.play();
},false);

I tested this on a Samsung Galaxy S and it works fine.

git discard all changes and pull from upstream

You can do it in a single command:

git fetch --all && git reset --hard origin/master

Or in a pair of commands:

git fetch --all
git reset --hard origin/master

Note than you will lose ALL your local changes

Factorial in numpy and scipy

    from numpy import prod

    def factorial(n):
        print prod(range(1,n+1))

or with mul from operator:

    from operator import mul

    def factorial(n):
        print reduce(mul,range(1,n+1))

or completely without help:

    def factorial(n):
        print reduce((lambda x,y: x*y),range(1,n+1))

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

How do I timestamp every ping result?

You can create a function in your ~/.bashrc file, so you get a ping command ping-t on your console:

function ping-t { ping "$1" | while read pong; do echo "$(date): $pong"; done; }

Now you can call this on the console:

ping-t example.com

Sa 31. Mär 12:58:31 CEST 2018: PING example.com (93.184.216.34) 56(84) bytes of data.
Sa 31. Mär 12:58:31 CEST 2018: 64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=1 ttl=48 time=208 ms
Sa 31. Mär 12:58:32 CEST 2018: 64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=2 ttl=48 time=233 ms

Font Awesome not working, icons showing as squares

If you are using the version 5.* or greater, then you have to use the

all.css or all.min.css

Including the fontawesome.css does not work as it has no reference to the webfonts folder and there is no reference to the @font-face or font-family

You can inspect this by searching the code for the font-family property in fontawesome.css or fontawesome.min.css

How to build splash screen in windows forms application?

I wanted a splash screen that would display until the main program form was ready to be displayed, so timers etc were no use to me. I also wanted to keep it as simple as possible. My application starts with (abbreviated):

static void Main()
{
    Splash frmSplash = new Splash();
    frmSplash.Show();
    Application.Run(new ReportExplorer(frmSplash));
}

Then, ReportExplorer has the following:

public ReportExplorer(Splash frmSplash)
{
    this.frmSplash = frmSplash;
    InitializeComponent();
}

Finally, after all the initialisation is complete:

if (frmSplash != null) 
{
     frmSplash.Close();
     frmSplash = null;
}

Maybe I'm missing something, but this seems a lot easier than mucking about with threads and timers.

HTML/Javascript change div content

you can use following helper function:

function content(divSelector, value) {
    document.querySelector(divSelector).innerHTML = value;
}

content('#content',"whatever");

Where #content must be valid CSS selector

Here is working example.


Additionaly - today (2018.07.01) I made speed comparison for jquery and pure js solutions ( MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):

document.getElementById("content").innerHTML = "whatever"; // pure JS
$('#content').html('whatever');                            // jQuery

enter image description here

The jquery solution was slower than pure js solution: 69% on firefox, 61% on safari, 56% on chrome. The fastest browser for pure js was firefox with 560M operations per second, the second was safari 426M, and slowest was chrome 122M.

So the winners are pure js and firefox (3x faster than chrome!)

You can test it in your machine: https://jsperf.com/js-jquery-html-content-change

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.

location / {
    root /path/to/root/of/static/files;
    try_files $uri $uri/ @apachesite;

    expires max;
    access_log off;
}

location @apachesite {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.

Communication between tabs or windows

Edit 2018: You may better use BroadcastChannel for this purpose, see other answers below. Yet if you still prefer to use localstorage for communication between tabs, do it this way:

In order to get notified when a tab sends a message to other tabs, you simply need to bind on 'storage' event. In all tabs, do this:

$(window).on('storage', message_receive);

The function message_receive will be called every time you set any value of localStorage in any other tab. The event listener contains also the data newly set to localStorage, so you don't even need to parse localStorage object itself. This is very handy because you can reset the value just right after it was set, to effectively clean up any traces. Here are functions for messaging:

// use local storage for messaging. Set message in local storage and clear it right away
// This is a safe way how to communicate with other tabs while not leaving any traces
//
function message_broadcast(message)
{
    localStorage.setItem('message',JSON.stringify(message));
    localStorage.removeItem('message');
}


// receive message
//
function message_receive(ev)
{
    if (ev.originalEvent.key!='message') return; // ignore other keys
    var message=JSON.parse(ev.originalEvent.newValue);
    if (!message) return; // ignore empty msg or msg reset

    // here you act on messages.
    // you can send objects like { 'command': 'doit', 'data': 'abcd' }
    if (message.command == 'doit') alert(message.data);

    // etc.
}

So now once your tabs bind on the onstorage event, and you have these two functions implemented, you can simply broadcast a message to other tabs calling, for example:

message_broadcast({'command':'reset'})

Remember that sending the exact same message twice will be propagated only once, so if you need to repeat messages, add some unique identifier to them, like

message_broadcast({'command':'reset', 'uid': (new Date).getTime()+Math.random()})

Also remember that the current tab which broadcasts the message doesn't actually receive it, only other tabs or windows on the same domain.

You may ask what happens if the user loads a different webpage or closes his tab just after the setItem() call before the removeItem(). Well, from my own testing the browser puts unloading on hold until the entire function message_broadcast() is finished. I tested to put inthere some very long for() cycle and it still waited for the cycle to finish before closing. If the user kills the tab just inbetween, then the browser won't have enough time to save the message to disk, thus this approach seems to me like safe way how to send messages without any traces. Comments welcome.

How do I include image files in Django templates?

I have spent two solid days working on this so I just thought I'd share my solution as well. As of 26/11/10 the current branch is 1.2.X so that means you'll have to have the following in you settings.py:

MEDIA_ROOT = "<path_to_files>" (i.e. /home/project/django/app/templates/static)
MEDIA_URL = "http://localhost:8000/static/"

*(remember that MEDIA_ROOT is where the files are and MEDIA_URL is a constant that you use in your templates.)*

Then in you url.py place the following:

import settings

# stuff

(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),

Then in your html you can use:

<img src="{{ MEDIA_URL }}foo.jpg">

The way django works (as far as I can figure is:

  1. In the html file it replaces MEDIA_URL with the MEDIA_URL path found in setting.py
  2. It looks in url.py to find any matches for the MEDIA_URL and then if it finds a match (like r'^static/(?P.)$'* relates to http://localhost:8000/static/) it searches for the file in the MEDIA_ROOT and then loads it

View the change history of a file using Git versioning

If you want to see the whole history of a file, including on all other branches use:

gitk --all <filename>

How do I drop a foreign key in SQL Server?

You can also Right Click on the table, choose modify, then go to the attribute, right click on it, and choose drop primary key.

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

HTML event handler code behaves like the body of a JavaScript function. Many languages such as C or Perl implicitly return the value of the last expression evaluated in the function body. JavaScript doesn't, it discards it and returns undefined unless you write an explicit returnEXPR.

Common xlabel/ylabel for matplotlib subplots

Since the command:

fig,ax = plt.subplots(5,2,sharex=True,sharey=True,figsize=fig_size)

you used returns a tuple consisting of the figure and a list of the axes instances, it is already sufficient to do something like (mind that I've changed fig,axto fig,axes):

fig,axes = plt.subplots(5,2,sharex=True,sharey=True,figsize=fig_size)

for ax in axes:
    ax.set_xlabel('Common x-label')
    ax.set_ylabel('Common y-label')

If you happen to want to change some details on a specific subplot, you can access it via axes[i] where i iterates over your subplots.

It might also be very helpful to include a

fig.tight_layout()

at the end of the file, before the plt.show(), in order to avoid overlapping labels.

Why is there no Constant feature in Java?

There is a way to create "const" variables in Java, but only for specific classes. Just define a class with final properties and subclass it. Then use the base class where you would want to use "const". Likewise, if you need to use "const" methods, add them to the base class. The compiler will not allow you to modify what it thinks is the final methods of the base class, but it will read and call methods on the subclass.

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

How can I format a number into a string with leading zeros?

If you like to keep it fixed width, for example 10 digits, do it like this

Key = i.ToString("0000000000");

Replace with as many digits as you like.

i = 123 will then result in Key = "0000000123".

Where does Console.WriteLine go in ASP.NET?

This is confusing for everyone when it comes IISExpress. There is nothing to read console messages. So for example, in the ASPCORE MVC apps it configures using appsettings.json which does nothing if you are using IISExpress.

For right now you can just add loggerFactory.AddDebug(LogLevel.Debug); in your Configure section and it will at least show you your logs in the Debug Output window.

Good news CORE 2.0 this will all be changing: https://github.com/aspnet/Announcements/issues/255

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

Pure datetime solution, does not depend on language or DATEFORMAT, no strings

SELECT
    DATEADD(year, [year]-1900, DATEADD(month, [month]-1, DATEADD(day, [day]-1, 0)))
FROM
    dbo.Table

Tracing XML request/responses with JAX-WS

I had been trying to find some framework library to log the web service soap request and response for a couple days. The code below fixed the issue for me:

System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
        System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");

Git keeps prompting me for a password

I feel like the answer provided by static_rtti is hacky in some sense. I don't know if this was available earlier, but Git tools now provide credential storage.

Cache Mode

$ git config --global credential.helper cache

Use the “cache” mode to keep credentials in memory for a certain period of time. None of the passwords are ever stored on disk, and they are purged from the cache after 15 minutes.

Store Mode

$ git config --global credential.helper 'store --file ~/.my-credentials'

Use the “store” mode to save the credentials to a plain-text file on disk, and they never expire.

I personally used the store mode. I deleted my repository, cloned it, and then had to enter my credentials once.

Reference: 7.14 Git Tools - Credential Storage

How to get package name from anywhere?

You can get your package name like so:

$ /path/to/adb shell 'pm list packages -f myapp'
package:/data/app/mycompany.myapp-2.apk=mycompany.myapp

Here are the options:

$ adb
Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android

 -a                            - directs adb to listen on all interfaces for a connection
 -d                            - directs command to the only connected USB device
                                 returns an error if more than one USB device is present.
 -e                            - directs command to the only running emulator.
                                 returns an error if more than one emulator is running.
 -s <specific device>          - directs command to the device or emulator with the given
                                 serial number or qualifier. Overrides ANDROID_SERIAL
                                 environment variable.
 -p <product name or path>     - simple product name like 'sooner', or
                                 a relative/absolute path to a product
                                 out directory like 'out/target/product/sooner'.
                                 If -p is not specified, the ANDROID_PRODUCT_OUT
                                 environment variable is used, which must
                                 be an absolute path.
 -H                            - Name of adb server host (default: localhost)
 -P                            - Port of adb server (default: 5037)
 devices [-l]                  - list all connected devices
                                 ('-l' will also list device qualifiers)
 connect <host>[:<port>]       - connect to a device via TCP/IP
                                 Port 5555 is used by default if no port number is specified.
 disconnect [<host>[:<port>]]  - disconnect from a TCP/IP device.
                                 Port 5555 is used by default if no port number is specified.
                                 Using this command with no additional arguments
                                 will disconnect from all connected TCP/IP devices.

device commands:
  adb push [-p] <local> <remote>
                               - copy file/dir to device
                                 ('-p' to display the transfer progress)
  adb pull [-p] [-a] <remote> [<local>]
                               - copy file/dir from device
                                 ('-p' to display the transfer progress)
                                 ('-a' means copy timestamp and mode)
  adb sync [ <directory> ]     - copy host->device only if changed
                                 (-l means list but don't copy)
  adb shell                    - run remote shell interactively
  adb shell <command>          - run remote shell command
  adb emu <command>            - run emulator console command
  adb logcat [ <filter-spec> ] - View device log
  adb forward --list           - list all forward socket connections.
                                 the format is a list of lines with the following format:
                                    <serial> " " <local> " " <remote> "\n"
  adb forward <local> <remote> - forward socket connections
                                 forward specs are one of:
                                   tcp:<port>
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
                                   dev:<character device name>
                                   jdwp:<process pid> (remote only)
  adb forward --no-rebind <local> <remote>
                               - same as 'adb forward <local> <remote>' but fails
                                 if <local> is already forwarded
  adb forward --remove <local> - remove a specific forward socket connection
  adb forward --remove-all     - remove all forward socket connections
  adb reverse --list           - list all reverse socket connections from device
  adb reverse <remote> <local> - reverse socket connections
                                 reverse specs are one of:
                                   tcp:<port>
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
  adb reverse --norebind <remote> <local>
                               - same as 'adb reverse <remote> <local>' but fails
                                 if <remote> is already reversed.
  adb reverse --remove <remote>
                               - remove a specific reversed socket connection
  adb reverse --remove-all     - remove all reversed socket connections from device
  adb jdwp                     - list PIDs of processes hosting a JDWP transport
  adb install [-lrtsdg] <file>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-g: grant all runtime permissions)
  adb install-multiple [-lrtsdpg] <file...>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-p: partial application install)
                                 (-g: grant all runtime permissions)
  adb uninstall [-k] <package> - remove this app package from the device
                                 ('-k' means keep the data and cache directories)
  adb bugreport                - return all information from the device
                                 that should be included in a bug report.

  adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]
                               - write an archive of the device's data to <file>.
                                 If no -f option is supplied then the data is written
                                 to "backup.ab" in the current directory.
                                 (-apk|-noapk enable/disable backup of the .apks themselves
                                    in the archive; the default is noapk.)
                                 (-obb|-noobb enable/disable backup of any installed apk expansion
                                    (aka .obb) files associated with each application; the default
                                    is noobb.)
                                 (-shared|-noshared enable/disable backup of the device's
                                    shared storage / SD card contents; the default is noshared.)
                                 (-all means to back up all installed applications)
                                 (-system|-nosystem toggles whether -all automatically includes
                                    system applications; the default is to include system apps)
                                 (<packages...> is the list of applications to be backed up.  If
                                    the -all or -shared flags are passed, then the package
                                    list is optional.  Applications explicitly given on the
                                    command line will be included even if -nosystem would
                                    ordinarily cause them to be omitted.)

  adb restore <file>           - restore device contents from the <file> backup archive

  adb disable-verity           - disable dm-verity checking on USERDEBUG builds
  adb enable-verity            - re-enable dm-verity checking on USERDEBUG builds
  adb keygen <file>            - generate adb public/private key. The private key is stored in <file>,
                                 and the public key is stored in <file>.pub. Any existing files
                                 are overwritten.
  adb help                     - show this help message
  adb version                  - show version num

scripting:
  adb wait-for-device          - block until device is online
  adb start-server             - ensure that there is a server running
  adb kill-server              - kill the server if it is running
  adb get-state                - prints: offline | bootloader | device
  adb get-serialno             - prints: <serial-number>
  adb get-devpath              - prints: <device-path>
  adb remount                  - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write
  adb reboot [bootloader|recovery]
                               - reboots the device, optionally into the bootloader or recovery program.
  adb reboot sideload          - reboots the device into the sideload mode in recovery program (adb root required).
  adb reboot sideload-auto-reboot
                               - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.
  adb sideload <file>          - sideloads the given package
  adb root                     - restarts the adbd daemon with root permissions
  adb unroot                   - restarts the adbd daemon without root permissions
  adb usb                      - restarts the adbd daemon listening on USB
  adb tcpip <port>             - restarts the adbd daemon listening on TCP on the specified port

networking:
  adb ppp <tty> [parameters]   - Run PPP over USB.
 Note: you should not automatically start a PPP connection.
 <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
 [parameters] - Eg. defaultroute debug dump local notty usepeerdns

adb sync notes: adb sync [ <directory> ]
  <localdir> can be interpreted in several ways:

  - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.

  - If it is "system", "vendor", "oem" or "data", only the corresponding partition
    is updated.

environment variables:
  ADB_TRACE                    - Print debug information. A comma separated list of the following values
                                 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp
  ANDROID_SERIAL               - The serial number to connect to. -s takes priority over this if given.
  ANDROID_LOG_TAGS             - When used with the logcat option, only these debug tags are printed.

How do I get the number of elements in a list?

And for completeness (primarily educational), it is possible without using the len() function. I would not condone this as a good option DO NOT PROGRAM LIKE THIS IN PYTHON, but it serves a purpose for learning algorithms.

def count(list):
    item_count = 0
    for item in list[:]:
        item_count += 1
    return item_count

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

(The colon in list[:] is implicit and is therefore also optional.)

The lesson here for new programmers is: You can’t get the number of items in a list without counting them at some point. The question becomes: when is a good time to count them? For example, high-performance code like the connect system call for sockets (written in C) connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);, does not calculate the length of elements (giving that responsibility to the calling code). Notice that the length of the address is passed along to save the step of counting the length first? Another option: computationally, it might make sense to keep track of the number of items as you add them within the object that you pass. Mind that this takes up more space in memory. See Naftuli Kay‘s answer.

Example of keeping track of the length to improve performance while taking up more space in memory. Note that I never use the len() function because the length is tracked:

class MyList(object):
    def __init__(self):
        self._data = []
        self.length = 0 # length tracker that takes up memory but makes length op O(1) time


        # the implicit iterator in a list class
    def __iter__(self):
        for elem in self._data:
            yield elem

    def add(self, elem):
        self._data.append(elem)
        self.length += 1

    def remove(self, elem):
        self._data.remove(elem)
        self.length -= 1

mylist = MyList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
print(mylist.length) # 3
mylist.remove(3)
print(mylist.length) # 2

Default SecurityProtocol in .NET 4.5

The default System.Net.ServicePointManager.SecurityProtocol in both .NET 4.0/4.5 is SecurityProtocolType.Tls|SecurityProtocolType.Ssl3.

.NET 4.0 supports up to TLS 1.0 while .NET 4.5 supports up to TLS 1.2

However, an application targeting .NET 4.0 can still support up to TLS 1.2 if .NET 4.5 is installed in the same environment. .NET 4.5 installs on top of .NET 4.0, replacing System.dll.

I've verified this by observing the correct security protocol set in traffic with fiddler4 and by manually setting the enumerated values in a .NET 4.0 project:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 |
(SecurityProtocolType)768 | (SecurityProtocolType)3072;

Reference:

namespace System.Net
{
    [System.Flags]
    public enum SecurityProtocolType
    {
       Ssl3 = 48,
       Tls = 192,
       Tls11 = 768,
       Tls12 = 3072,
    }
}

If you attempt the hack on an environment with ONLY .NET 4.0 installed, you will get the exception:

Unhandled Exception: System.NotSupportedException: The requested security protocol is not supported. at System.Net.ServicePointManager.set_SecurityProtocol(SecurityProtocolType v alue)

However, I wouldn't recommend this "hack" since a future patch, etc. may break it.*

Therefore, I've decided the best route to remove support for SSLv3 is to:

  1. Upgrade all applications to .NET 4.5
  2. Add the following to boostrapping code to override the default and future proof it:

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

*Someone correct me if this hack is wrong, but initial tests I see it works

iOS: Compare two dates

I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.

Something like this should work as a category for NSDate:

- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
    NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
    NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];

    NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
    NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
    return [selfDateOnly compare:otherDateOnly];
}

Get value from JToken that may not exist (best practices)

TYPE variable = jsonbody["key"]?.Value<TYPE>() ?? DEFAULT_VALUE;

e.g.

bool attachMap = jsonbody["map"]?.Value<bool>() ?? false;

How can I use Python to get the system hostname?

From at least python >= 3.3:

You can use the field nodename and avoid using array indexing:

os.uname().nodename

Although, even the documentation of os.uname suggests using socket.gethostname()

How to exit from the application and show the home screen?

System.exit(0);

Is probably what you are looking for. It will close the entire application and take you to the home Screen.

How to set a Fragment tag by code?

This is the best way I have found :

   public class MainActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
          // Let's first dynamically add a fragment into a frame container
          getSupportFragmentManager().beginTransaction(). 
              replace(R.id.flContainer, new DemoFragment(), "SOMETAG").
              commit();
          // Now later we can lookup the fragment by tag
          DemoFragment fragmentDemo = (DemoFragment) 
              getSupportFragmentManager().findFragmentByTag("SOMETAG");
        }
    }
}

Generate a random letter in Python

Another way, for completeness:

>>> chr(random.randrange(97, 97 + 26))

Use the fact that ascii 'a' is 97, and there are 26 letters in the alphabet.

When determining the upper and lower bound of the random.randrange() function call, remember that random.randrange() is exclusive on its upper bound, meaning it will only ever generate an integer up to 1 unit less that the provided value.

Passing arguments forward to another javascript function

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.

Example without using the apply method:

_x000D_
_x000D_
function a(...args){_x000D_
  b(...args);_x000D_
  b(6, ...args, 8) // You can even add more elements_x000D_
}_x000D_
function b(){_x000D_
  console.log(arguments)_x000D_
}_x000D_
_x000D_
a(1, 2, 3)
_x000D_
_x000D_
_x000D_

Note This snippet returns a syntax error if your browser still uses ES5.

Editor's note: Since the snippet uses console.log(), you must open your browser's JS console to see the result - there will be no in-page result.

It will display this result:

Image of Spread operator arguments example

In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters

How to select a specific node with LINQ-to-XML

I'd use something like:

dim customer = (from c in xmldoc...<Customer> 
                where c.<ID>.Value=22 
                select c).SingleOrDefault 

Edit:

missed the c# tag, sorry......the example is in VB.NET

XSLT equivalent for JSON

Yate (https://github.com/pasaran/yate) is specifically designed after XSLT, features JPath (a natural XPath equivalent for JS), compiles to JavaScript and has quite a history of production use. It’s practically undocumented, but reading through samples and tests should be enough.

How to use MD5 in javascript to transmit a password

crypto-js is a rich javascript library containing many cryptography algorithms.

All you have to do is just call CryptoJS.MD5(password)

$.post(
  'includes/login.php', 
  { user: username, pass: CryptoJS.MD5(password) },
  onLogin, 
  'json' );

How to make the first option of <select> selected with jQuery

$("#target").val(null);

worked fine in chrome

Get the name of an object's type

The closest you can get is typeof, but it only returns "object" for any sort of custom type. For those, see Jason Bunting.

Edit, Jason's deleted his post for some reason, so just use Object's constructor property.

Using ResourceManager

The quick and dirty way to check what string you need it to look at the generated .resources files.

Your .resources are generated in the resources projects obj/Debug directory. (if not right click on .resx file in solution explorer and hit 'Run Custom Tool' to generate the .resources files)

Navigate to this directory and have a look at the filenames. You should see a file ending in XYZ.resources. Copy that filename and remove the trailing .resources and that is the file you should be loading.

For example in my obj/Bin directory I have the file:

MyLocalisation.Properties.Resources.resources

If the resource files are in the same Class library/Application I would use the following C#

ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", Assembly.GetExecutingAssembly());

However, as it sounds like you are using the resources file from a separate Class library/Application you probably want

Assembly localisationAssembly = Assembly.Load("MyLocalisation");
ResourceManager RM =  new ResourceManager("MyLocalisation.Properties.Resources", localisationAssembly);

Importing class/java files in Eclipse

I had the same problem. But What I did is I imported the .java files and then I went to Search->File-> and then changed the package name to whatever package it should belong in this way I fixed a lot of java files which otherwise would require to go to every file and change them manually.

Downloading all maven dependencies to a directory NOT in repository?

Please check if you have some config files in ${MAVEN_HOME}/conf directory like settings.xml. Those files overrides settings from .m2 folder and because of that, repository folder from .m2 might not be visible or discarded.

Why is it OK to return a 'vector' from a function?

Can we guarantee it will not die?

As long there is no reference returned, it's perfectly fine to do so. words will be moved to the variable receiving the result.

The local variable will go out of scope. after it was moved (or copied).

Best way to check if object exists in Entity Framework?

Why not do it?

var result= ctx.table.Where(x => x.UserName == "Value").FirstOrDefault();

if(result?.field == value)
{
  // Match!
}

Converting byte array to String (Java)

You can try this.

String s = new String(bytearray);

TypeError: 'builtin_function_or_method' object is not subscriptable

Mad a similar error, easy to fix:

    TypeError Traceback (most recent call last) <ipython-input-2-1eb12bfdc7db> in <module>
  3 mylist = [10,20,30] ----> 4 arr = np.array[(10,20,30)] 5 d = {'a':10, 'b':20, 'c':30} TypeError: 'builtin_function_or_method' object is not subscriptable

but I should have written it as:

arr = np.array([10,20,30])

Very fixable, rookie/dumb mistake.

How to allocate aligned memory only using the standard library?

Three slightly different answers depending how you look at the question:

1) Good enough for the exact question asked is Jonathan Leffler's solution, except that to round up to 16-aligned, you only need 15 extra bytes, not 16.

A:

/* allocate a buffer with room to add 0-15 bytes to ensure 16-alignment */
void *mem = malloc(1024+15);
ASSERT(mem); // some kind of error-handling code
/* round up to multiple of 16: add 15 and then round down by masking */
void *ptr = ((char*)mem+15) & ~ (size_t)0x0F;

B:

free(mem);

2) For a more generic memory allocation function, the caller doesn't want to have to keep track of two pointers (one to use and one to free). So you store a pointer to the 'real' buffer below the aligned buffer.

A:

void *mem = malloc(1024+15+sizeof(void*));
if (!mem) return mem;
void *ptr = ((char*)mem+sizeof(void*)+15) & ~ (size_t)0x0F;
((void**)ptr)[-1] = mem;
return ptr;

B:

if (ptr) free(((void**)ptr)[-1]);

Note that unlike (1), where only 15 bytes were added to mem, this code could actually reduce the alignment if your implementation happens to guarantee 32-byte alignment from malloc (unlikely, but in theory a C implementation could have a 32-byte aligned type). That doesn't matter if all you do is call memset_16aligned, but if you use the memory for a struct then it could matter.

I'm not sure off-hand what a good fix is for this (other than to warn the user that the buffer returned is not necessarily suitable for arbitrary structs) since there's no way to determine programatically what the implementation-specific alignment guarantee is. I guess at startup you could allocate two or more 1-byte buffers, and assume that the worst alignment you see is the guaranteed alignment. If you're wrong, you waste memory. Anyone with a better idea, please say so...

[Added: The 'standard' trick is to create a union of 'likely to be maximally aligned types' to determine the requisite alignment. The maximally aligned types are likely to be (in C99) 'long long', 'long double', 'void *', or 'void (*)(void)'; if you include <stdint.h>, you could presumably use 'intmax_t' in place of long long (and, on Power 6 (AIX) machines, intmax_t would give you a 128-bit integer type). The alignment requirements for that union can be determined by embedding it into a struct with a single char followed by the union:

struct alignment
{
    char     c;
    union
    {
        intmax_t      imax;
        long double   ldbl;
        void         *vptr;
        void        (*fptr)(void);
    }        u;
} align_data;
size_t align = (char *)&align_data.u.imax - &align_data.c;

You would then use the larger of the requested alignment (in the example, 16) and the align value calculated above.

On (64-bit) Solaris 10, it appears that the basic alignment for the result from malloc() is a multiple of 32 bytes.
]

In practice, aligned allocators often take a parameter for the alignment rather than it being hardwired. So the user will pass in the size of the struct they care about (or the least power of 2 greater than or equal to that) and all will be well.

3) Use what your platform provides: posix_memalign for POSIX, _aligned_malloc on Windows.

4) If you use C11, then the cleanest - portable and concise - option is to use the standard library function aligned_alloc that was introduced in this version of the language specification.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

Here's what I did, for stamping the AssemblyFileVersion attribute.

Removed the AssemblyFileVersion from AssemblyInfo.cs

Add a new, empty, file called AssemblyFileInfo.cs to the project.

Install the MSBuild community tasks toolset on the hudson build machine or as a NuGet dependency in your project.

Edit the project (csproj) file , it's just an msbuild file, and add the following.

Somewhere there'll be a <PropertyGroup> stating the version. Change that so it reads e.g.

 <Major>1</Major>
 <Minor>0</Minor>
 <!--Hudson sets BUILD_NUMBER and SVN_REVISION -->
 <Build>$(BUILD_NUMBER)</Build>
 <Revision>$(SVN_REVISION)</Revision>

Hudson provides those env variables you see there when the project is built on hudson (assuming it's fetched from subversion).

At the bottom of the project file, add

 <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')" />
  <Target Name="BeforeBuild" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')">
    <Message Text="Version: $(Major).$(Minor).$(Build).$(Revision)" />
    <AssemblyInfo CodeLanguage="CS" OutputFile="AssemblyFileInfo.cs" AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)" AssemblyConfiguration="$(Configuration)" Condition="$(Revision) != '' " />
  </Target>

This uses the MSBuildCommunityTasks to generate the AssemblyFileVersion.cs to include an AssemblyFileVersion attribute before the project is built. You could do this for any/all of the version attributes if you want.

The result is, whenever you issue a hudson build, the resulting assembly gets an AssemblyFileVersion of 1.0.HUDSON_BUILD_NR.SVN_REVISION e.g. 1.0.6.2632 , which means the 6'th build # in hudson, buit from the subversion revision 2632.

Rounding a double value to x number of decimal places in swift

This is a sort of a long workaround, which may come in handy if your needs are a little more complex. You can use a number formatter in Swift.

let numberFormatter: NSNumberFormatter = {
    let nf = NSNumberFormatter()
    nf.numberStyle = .DecimalStyle
    nf.minimumFractionDigits = 0
    nf.maximumFractionDigits = 1
    return nf
}()

Suppose your variable you want to print is

var printVar = 3.567

This will make sure it is returned in the desired format:

numberFormatter.StringFromNumber(printVar)

The result here will thus be "3.6" (rounded). While this is not the most economic solution, I give it because the OP mentioned printing (in which case a String is not undesirable), and because this class allows for multiple parameters to be set.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

As pointed out here you must use the script in the UMD subdirectory, in my case

        bundles.Add(new ScriptBundle("~/bundles/projectbundle").Include(
            "~/Scripts/umd/popper.js",
            "~/Scripts/bootstrap.js",
            "~/Scripts/respond.js",
            "~/Scripts/summernote-bs4.js"));

Specifically this: "~/Scripts/umd/popper.js",

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

You have the wrong table set on the command. You should use the following on your setup:

ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;

Where do I configure log4j in a JUnit test class?

I use system properties in log4j.xml:

...
<param name="File" value="${catalina.home}/logs/root.log"/>
...

and start tests with:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <systemProperties>
            <property>
                <name>catalina.home</name>
                <value>${project.build.directory}</value>
            </property>
        </systemProperties>
    </configuration>
</plugin>

Where are the Android icon drawables within the SDK?

In android.R.drawable, read more here : http://docs.since2006.com/android/2.1-drawables.php


Simple resource usage :

android:icon="@android:drawable/ic_menu_save"

Simple Java usage :

myMenuItem.setIcon(android.R.drawable.ic_menu_save);

How do I display a ratio in Excel in the format A:B?

The second formula on that page uses the GCD function of the Analysis ToolPak, you can add it from Tools > Add-Ins.

=A1/GCD(A1,B1)&":"&B1/GCD(A1,B1)

This is a more mathematical formula rather than a text manipulation based on.

Unfortunately Launcher3 has stopped working error in android studio?

I had a similar problem with a physical device. The problem was related with the fact that the google app ( the search bar for google on top ) was disabled. After the first reboot launcher3 began failing. No matter how many cache/data cleaning I did, it kept failing. I reenabled it and launched it, so it appeared again on the screen and from that moment on, launcher3 was back to life.

I guess there mmust be some kind of dependency with this app.

Referenced Project gets "lost" at Compile Time

Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework

Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type

Finally, Rebuild the solution.

How to import keras from tf.keras in Tensorflow?

To make it simple I will take the two versions of the code in keras and tf.keras. The example here is a simple Neural Network Model with different layers in it.

In Keras (v2.1.5)

from keras.models import Sequential
from keras.layers import Dense

def get_model(n_x, n_h1, n_h2):
    model = Sequential()
    model.add(Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(Dense(n_h2, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4, activation='softmax'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())
    return model

In tf.keras (v1.9)

import tensorflow as tf

def get_model(n_x, n_h1, n_h2):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(tf.keras.layers.Dense(n_h2, activation='relu'))
    model.add(tf.keras.layers.Dropout(0.5))
    model.add(tf.keras.layers.Dense(4, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())

    return model

or it can be imported the following way instead of the above-mentioned way

from tensorflow.keras.layers import Dense

The official documentation of tf.keras

Note: TensorFlow Version is 1.9

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

I got this problem when I updated the Gradle plugin from version 1.2.3 to 1.5.0 as Android Studio suggested. In its web page, 1.5.0 appears to be a beta version.

Honestly, I don't know what advantages the version 1.5.0 has, but I'd rather wait until there's a stable version.

Of course, going back to 1.2.3 solved the issue.

css to make bootstrap navbar transparent

This works for 4.0.

<nav class="navbar navbar-expand-sm fixed-top navbar-light">
or
<nav class="navbar navbar-expand-lg fixed-top navbar-dark">

key item is fixed-top, otherwise, white or default page background is displayed even if there is a image top. navbar-light gives dark letters, navbar-dark shows light text.

'str' object has no attribute 'decode'. Python 3 error?

This worked for me:

html.replace("\\/", "/").encode().decode('unicode_escape', 'surrogatepass')

This is similar to json.loads(html) behaviour

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

For people using Tomee or Tomcat and can't get it working, try to create context.xml in META-INF and add allowCasualMultipartParsing="true"

<?xml version="1.0" encoding="UTF-8"?>
<Context allowCasualMultipartParsing="true">
  <!-- empty or not depending your project -->
</Context>

Convert array to JSON string in swift

SWIFT 2.0

var tempJson : NSString = ""
do {
    let arrJson = try NSJSONSerialization.dataWithJSONObject(arrInvitationList, options: NSJSONWritingOptions.PrettyPrinted)
    let string = NSString(data: arrJson, encoding: NSUTF8StringEncoding)
    tempJson = string! as NSString
}catch let error as NSError{
    print(error.description)
}

NOTE:- use tempJson variable when you want to use.

How to leave a message for a github.com user

Github said on April 3rd 2012 :

Today we're removing two features. They've been gathering dust for a while and it's time to throw them out : Fork Queue & Private Messaging

Source

NoClassDefFoundError for code in an Java library on Android

I met NoClassDefFoundError for a class that exists in my project (not a library class). The class exists but i got NoClassDefFoundError. In my case, the problem was multidex support. The problem and solution is here: Android Multidex and support libraries

You get this error for Android versions lower than 5.0.

Is there a simple way to remove multiple spaces in a string?

Similar to the previous solutions, but more specific: replace two or more spaces with one:

>>> import re
>>> s = "The   fox jumped   over    the log."
>>> re.sub('\s{2,}', ' ', s)
'The fox jumped over the log.'

What's the complete range for Chinese characters in Unicode?

May be you would find a complete list through the CJK Unicode FAQ (which does include "Chinese, Japanese, and Korean" characters)

The "East Asian Script" document does mention:

Blocks Containing Han Ideographs

Han ideographic characters are found in five main blocks of the Unicode Standard, as shown in Table 12-2

Table 12-2. Blocks Containing Han Ideographs

Block                                   Range       Comment
CJK Unified Ideographs                  4E00-9FFF   Common
CJK Unified Ideographs Extension A      3400-4DBF   Rare
CJK Unified Ideographs Extension B      20000-2A6DF Rare, historic
CJK Unified Ideographs Extension C      2A700–2B73F Rare, historic
CJK Unified Ideographs Extension D      2B740–2B81F Uncommon, some in current use
CJK Unified Ideographs Extension E      2B820–2CEAF Rare, historic
CJK Compatibility Ideographs            F900-FAFF   Duplicates, unifiable variants, corporate characters
CJK Compatibility Ideographs Supplement 2F800-2FA1F Unifiable variants

Note: the block ranges can evolve over time: latest is in CJK Unified Ideographs.

See also Wikipedia:

Checking if a string is empty or null in Java

This way you check if the string is not null and not empty, also considering the empty spaces:

boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
    // handle the validation
}

How to make an input type=button act like a hyperlink and redirect using a get request?

Do not do it. I might want to run my car on monkey blood. I have my reasons, but sometimes it's better to stick with using things the way they were designed even if it doesn't "absolutely perfectly" match the exact look you are driving for.

To back up my argument I submit the following.

  • See how this image lacks the status bar at the bottom. This link is using the onclick="location.href" model. (This is a real-life production example from my predecessor) This can make users hesitant to click on the link, since they have no idea where it is taking them, for starters.

Image

You are also making Search engine optimization more difficult IMO as well as making the debugging and reading of your code/HTML more complex. A submit button should submit a form. Why should you(the development community) try to create a non-standard UI?

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

Media Player called in state 0, error (-38,0)

I am new in android programming and i had same error as this one. so i simply redefined the mp.createmediaPlayer = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI). It may not the true way to do it but it worked fined for me:

try {
  mp = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI);
} catch (Exception e) {
  e.printStackTrace();
}

mp.start();

How do you migrate an IIS 7 site to another server?

MSDeploy can migrate all content, config, etc. that is what the IIS team recommends. http://www.iis.net/extensions/WebDeploymentTool

To create a package, run the following command (replace Default Web Site with your web site name):

msdeploy.exe -verb:sync -source:apphostconfig="Default Web Site" -dest:package=c:\dws.zip > DWSpackage7.log

To restore the package, run the following command:

msdeploy.exe -verb:sync -source:package=c:\dws.zip -dest:apphostconfig="Default Web Site" > DWSpackage7.log

VSCode: How to Split Editor Vertically

Press CMD + SHIFT + P (MAC) and search for Toggle Editor Group

collapse cell in jupyter notebook

You don't need to do much except to enable the extensions:

http://localhost:8888/nbextensions?nbextension=collapsible_headings
http://localhost:8888/nbextensions?nbextension=codefolding/main

enter image description here

Most probable you will find all your extensions in here:

http://localhost:8888/nbextensions

enter image description here

How to call a PHP file from HTML or Javascript

I just want to have a button on my website make a PHP file run

<form action="my.php" method="post">
    <input type="submit">
</form>

Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.

<a href="my.php">run php</a>

(Although you should use link text that describes what happens from the user's point of view, not the servers)


I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

This is tricker.

First, you do need to use a form and POST (since you are sending data to be stored).

Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.

Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.

<a href="showBlogEntry.php?entry_id=123">...</a>

Make sure you also read up on SQL injection and XSS.

Maven error: Not authorized, ReasonPhrase:Unauthorized

The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.

CASE statement in SQLite query

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

or

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

Check out the documentation (The CASE expression):

http://www.sqlite.org/lang_expr.html

Convert to/from DateTime and Time in Ruby

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

MongoDB logging all queries

I made a command line tool to activate the profiler activity and see the logs in a "tail"able way: "mongotail".

But the more interesting feature (also like tail) is to see the changes in "real time" with the -f option, and occasionally filter the result with grep to find a particular operation.

See documentation and installation instructions in: https://github.com/mrsarm/mongotail

How to enumerate an enum with String type?

Xcode 10 with Swift 4.2

enum Filter: String, CaseIterable {

    case salary = "Salary"
    case experience = "Experience"
    case technology = "Technology"
    case unutilized = "Unutilized"
    case unutilizedHV = "Unutilized High Value"

    static let allValues = Filter.allCases.map { $0.rawValue }
}

Call it

print(Filter.allValues)

Prints:

["Salary", "Experience", "Technology", "Unutilized", "Unutilized High Value"]


Older versions

For enum representing Int

enum Filter: Int {
    case salary
    case experience
    case technology
    case unutilized
    case unutilizedHV
    
    static let allRawValues = salary.rawValue...unutilizedHV.rawValue  // First to last case
    static let allValues = allRawValues.map { Filter(rawValue: $0)!.rawValue }
}

Call it like this:

print(Filter.allValues)

Prints:

[0, 1, 2, 3, 4]


For enum representing String

enum Filter: Int {
    case salary
    case experience
    case technology
    case unutilized
    case unutilizedHV
    
    static let allRawValues = salary.rawValue...unutilizedHV.rawValue  // First to last case
    static let allValues = allRawValues.map { Filter(rawValue: $0)!.description }
}

extension Filter: CustomStringConvertible {
    var description: String {
        switch self {
        case .salary: return "Salary"
        case .experience: return "Experience"
        case .technology: return "Technology"
        case .unutilized: return "Unutilized"
        case .unutilizedHV: return "Unutilized High Value"
        }
    }
}

Call it

print(Filter.allValues)

Prints:

["Salary", "Experience", "Technology", "Unutilized", "Unutilized High Value"]

Establish a VPN connection in cmd

Is Powershell an option?

Start Powershell:

powershell

Create the VPN Connection: Add-VpnConnection

Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm] 

Edit VPN connections: Set-VpnConnection

Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]

Lookup VPN Connections: Get-VpnConnection

Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]

Connect: rasdial [connectionName]

rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]

You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial.

The results of Get-VpnConnection can be a little verbose. This can be simplified with a simple Select-Object filter:

Get-VpnConnection | Select-Object -Property Name

More information can be found here:

Java - Abstract class to contain variables?

Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class

Array of structs example

Given an instance of the struct, you set the values.

    student thisStudent;
    Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
    thisStudent.s_id = int.Parse(Console.ReadLine());
    thisStudent.s_name = Console.ReadLine();
    thisStudent.c_name = Console.ReadLine();
    thisStudent.s_dob = Console.ReadLine();

Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.

How to capture UIView to UIImage without loss of quality on retina display

Add this to method to UIView Category

- (UIImage*) capture {
    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

How do I generate random integers within a specific range in Java?

here's a function that returns exactly one integer random number in a range defined by lowerBoundIncluded and upperBoundIncluded, as requested by user42155

SplittableRandom splittableRandom = new SplittableRandom();

BiFunction<Integer,Integer,Integer> randomInt = (lowerBoundIncluded, upperBoundIncluded)
    -> splittableRandom.nextInt( lowerBoundIncluded, upperBoundIncluded + 1 );

randomInt.apply( …, … ); // gets the random number


…or shorter for the one-time generation of a random number

new SplittableRandom().nextInt( lowerBoundIncluded, upperBoundIncluded + 1 );

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

In previous answers a few registry keys that might not exist are missed. They are SchUseStrongCrypto that must exist to allow to TLS protocols work properly.

After the registry keys have been imported to registry it should not be required to make changes in code like

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

Below there are all registry keys and values that are needed for x64 windows OS. If you have 32bit OS (x86) just remove the last 2 lines. TLS 1.0 will be disabled by the registry script. Restarting OS is required.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"DisabledByDefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\server]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\ssl 3.0]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\ssl 3.0\client]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\ssl 3.0\server]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.0]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.0\client]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.0\server]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.1]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.1\client]
"disabledbydefault"=dword:00000000
"enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.1\server]
"disabledbydefault"=dword:00000000
"enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.2]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.2\client]
"disabledbydefault"=dword:00000000
"enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.2\server]
"disabledbydefault"=dword:00000000
"enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

Reason: no suitable image found

It occurred on my side when building an app in the command line via xcodebuild and xcrun PackageApplication, signing the app with an enterprise profile. On our CI build servers, the certificate was set to "Always Trust" in the keychain (select certificate -> Get Info -> Trust -> "Use System Default" can be changed to "Always Trust"). I had to set it back to "Use System Default" in order to make this work. Initially we set this to "Always Trust" to work-around the keychain dialogs that appear after software updates and certificate updates.

How to implement swipe gestures for mobile devices?

The simplest solution I've found that doesn't require a plugin:

document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null;                                                        
var yDown = null;  

function handleTouchStart(evt) {                                         
    xDown = evt.touches[0].clientX;                                      
    yDown = evt.touches[0].clientY;                                      
}; 

function handleTouchMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }
    var xUp = evt.touches[0].clientX;                                    
    var yUp = evt.touches[0].clientY;
    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
        /* left swipe */ 
        } else {
        /* right swipe */
        }                       
    } else {
        if ( yDiff > 0 ) {
        /* up swipe */ 
        } else { 
        /* down swipe */
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;                                             
};

'console' is undefined error for Internet Explorer

In IE9, if console is not opened, this code:

alert(typeof console);

will show "object", but this code

alert(typeof console.log);

will throw TypeError exception, but not return undefined value;

So, guaranteed version of code will look similar to this:

try {
    if (window.console && window.console.log) {
        my_console_log = window.console.log;
    }
} catch (e) {
    my_console_log = function() {};
}

Why shouldn't I use "Hungarian Notation"?

Joel Spolsky wrote a good blog post about this. http://www.joelonsoftware.com/articles/Wrong.html Basically it comes down to not making your code harder to read when a decent IDE will tell you want type the variable is if you can't remember. Also, if you make your code compartmentalized enough, you don't have to remember what a variable was declared as three pages up.

What is the difference between const and readonly in C#?

There is a small gotcha with readonly. A readonly field can be set multiple times within the constructor(s). Even if the value is set in two different chained constructors it is still allowed.

public class Sample {
    private readonly string ro;

    public Sample() {
        ro = "set";
    }

    public Sample(string value) : this() {
        ro = value; // this works even though it was set in the no-arg ctor
    }
}

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

How can I pause setInterval() functions?

Why not use a simpler approach? Add a class!

Simply add a class that tells the interval not to do anything. For example: on hover.

_x000D_
_x000D_
var i = 0;_x000D_
this.setInterval(function() {_x000D_
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
    console.log('Counting...');_x000D_
    $('#counter').html(i++); //just for explaining and showing_x000D_
  } else {_x000D_
    console.log('Stopped counting');_x000D_
  }_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
    $(this).addClass('pauseInterval');_x000D_
  },function() { //mouse leave_x000D_
    $(this).removeClass('pauseInterval');_x000D_
  }_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
  $('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
  background-color: #eee;_x000D_
  font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
  width: 50%;_x000D_
  background: #ddd;_x000D_
  border: 2px solid #009afd;_x000D_
  border-radius: 5px;_x000D_
  padding: 5px;_x000D_
  text-align: center;_x000D_
  transition: .3s;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
  border-color: red;  _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter">&nbsp;</p>_x000D_
<button id="pauseInterval">Pause</button></p>
_x000D_
_x000D_
_x000D_

I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

Yes, I know I'm late to this party but it might help others.

The servlet container chooses the mapping based on the longest path that matches. So you can put this mapping in for your JSPs and it will be chosen over the /* mapping.

<servlet-mapping>
  <servlet-name>jsp</servlet-name>
  <url-pattern>/WEB-INF/pages/*</url-pattern>
 </servlet-mapping>

Actually for Tomcat that's all you'll need since jsp is a servlet that exists out of the box. For other containers you either need to find out the name of the JSP servlet or add a servlet definition like:

<servlet>
  <servlet-name>jsp</servlet-name>
  <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>

How to acces external json file objects in vue.js app

I have recently started working on a project using Vue JS, JSON Schema. I am trying to access nested JSON Objects from a JSON Schema file in the Vue app. I tried the below code and now I can load different JSON objects inside different Vue template tags. In the script tag add the below code

import  {JsonObject1name, JsonObject2name} from 'your Json file path';

Now you can access JsonObject1,2 names in data section of export default part as below:

data: () => ({ 
  
  schema: JsonObject1name,
  schema1: JsonObject2name,   
  
  model: {} 
}),

Now you can load the schema, schema1 data inside Vue template according to your requirement. See below code for example :

      <SchemaForm id="unique name representing your Json object1" class="form"  v-model="model" :schema="schema" :components="components">
      </SchemaForm>  

      <SchemaForm id="unique name representing your Json object2" class="form" v-model="model" :schema="schema1" :components="components">
      </SchemaForm>

SchemaForm is the local variable name for @formSchema/native library. I have implemented the data of different JSON objects through forms in different CSS tabs.

I hope this answer helps someone. I can help if there are any questions.

How can I delete an item from an array in VB.NET?

If the array is a string array you are able to then do the following:

AlphaSplit = "a\b\c".Split("\")
MaxIndex   = AlphaSplit.GetUpperBound(0)
AlphaSplit = AlphaSplit.Where(Function(item, index) index <> MaxIndex).ToArray
AlphaJoin  = String.Join("\", PublishRouteSplit)

Device not detected in Eclipse when connected with USB cable

Do following steps to detect your device in eclipse : -

On Mobile Side:- For Connect USB sync, your Android device needs to have USB Debugging enabled.

To enable Android USB Debugging Mode do following steps :-

Android 2.x - 3.x devices:

Go to Settings > Application > Development > USB Debugging.

Android 4.x devices:

Go to Settings > Developer Options > USB Debugging.

For devices running Android 4.2.2 or later, you may need to unlock Developer Options before it is available within the Menu:

  1. Go to Android home screen.
  2. Pull down the notification bar.
  3. Tap "Settings"
  4. Tap "About Device"
  5. Tap on the "Build Number" button about 7 times.
  6. Developer Mode should now be unlocked and available in Settings > More > Developer Options or in Settings > Developer Options

On PC side

  1. Connect your device to the PC with USB cable.
  2. Download Google USB Driver
  3. Extract/Unzip “latest_usb_driver_windows.zip” file on your computer (using 7-zip free software, preferably)
  4. Open device manager on your PC
    • Windows 7 & 8 users ? search for Device Manager from Start (or Start screen) and click to open.
    • Windows XP users ? Google it
  5. You will see list of all devices attached to your computer in the device manager. Just find your device (it’ll most probably be in the Other devices list with a yellow exclamation mark by the name of ADB devices), then Right-click on it and select Update Driver Software.
  6. Select “Browse my computer for driver software” in the next window
  7. Now click the “Browse…” button and select the “usb_driver” folder that we extracted in Step 3 from “latest_usb_driver_windows.zip” file.
  8. Do NOT select the zip file, select the folder where the contents of the zip file are extracted. And keep the Include subfolders box checked
  9. During the installation (as a security check) Windows may ask your permission to install the drivers, click “Install”
  10. Once the installation is complete you’ll see a refreshed list of devices on the Device manager screen showing your phone’s driver installed successfully.

Now in eclipse do following steps to install your app in your device:-

  1. Go to Run > Run Configurations > Target tab.
  2. Check option "Always prompt to pick device". And then running the application from Eclipse,the prompt window finally showed your device.

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

tl;dr the "standards" are a hodge-podge mess; it depends who you ask!

Overall, there appears to be no MIME type image/jpg. Yet, in practice, nearly all software handles image files named "*.jpg" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg could be many different things.

For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.

These "complete lists" and RFC do not have MIME type image/jpg! But for MIME type image/jpeg some lists do have varying file name extensions (.jpeg, .jpg, …). Other lists do not mention image/jpeg.

Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.

Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf is preferred file extension for image/jpx but in IANA Media Types the name jpf is not present (and that IANA document references RFC 3745!).

Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.

Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?


The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg yet there exists the odd vnd.sealedmedia.softseal.jpg. File extension.JPEG is only known as a video type while file extension .jpeg is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000 is type video yet RFC 3745 considers JPEG 2000 an image type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg).


In summary...

Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.



Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".

Create PostgreSQL ROLE (user) if it doesn't exist

The accepted answer suffers from a race condition if two such scripts are executed concurrently on the same Postgres cluster (DB server), as is common in continuous-integration environments.

It's generally safer to try to create the role and gracefully deal with problems when creating it:

DO $$
BEGIN
  CREATE ROLE my_role WITH NOLOGIN;
  EXCEPTION WHEN DUPLICATE_OBJECT THEN
  RAISE NOTICE 'not creating role my_role -- it already exists';
END
$$;

How to display .svg image using swift

You can add New Symbol Image Set in .xcassets, then you can add SVG file in it

and use it same like image.

enter image description here

Note: This doesn't work on all SVG. You can have a look at the apple documentation

Truncating Text in PHP?

The obvious thing to do is read the documentation.

But to help: substr($str, $start, $end);

$str is your text

$start is the character index to begin at. In your case, it is likely 0 which means the very beginning.

$end is where to truncate at. Suppose you wanted to end at 15 characters, for example. You would write it like this:

<?php

$text = "long text that should be truncated";
echo substr($text, 0, 15);

?>

and you would get this:

long text that 

makes sense?

EDIT

The link you gave is a function to find the last white space after chopping text to a desired length so you don't cut off in the middle of a word. However, it is missing one important thing - the desired length to be passed to the function instead of always assuming you want it to be 25 characters. So here's the updated version:

function truncate($text, $chars = 25) {
    if (strlen($text) <= $chars) {
        return $text;
    }
    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

So in your case you would paste this function into the functions.php file and call it like this in your page:

$post = the_post();
echo truncate($post, 100);

This will chop your post down to the last occurrence of a white space before or equal to 100 characters. Obviously you can pass any number instead of 100. Whatever you need.

Check if an element is a child of a parent

Ended up using .closest() instead.

$(document).on("click", function (event) {
    if($(event.target).closest(".CustomControllerMainDiv").length == 1)
    alert('element is a child of the custom controller')
});

Android dex gives a BufferOverflowException when building

Right click on Project>>Properties>>Android and select API Level greater than 15

OR

Add google-play-services_lib to your project by right clicking on project and selecting Project>>Properties>>Android>>Add

What is a correct MIME type for .docx, .pptx, etc.?

Here is the (almost) complete file extensions's MIME in a JSON format. Just do example: MIME["ppt"], MIME["docx"], etc

{"x3d": "application/vnd.hzn-3d-crossword", "3gp": "video/3gpp", "3g2": "video/3gpp2", "mseq": "application/vnd.mseq", "pwn": "application/vnd.3m.post-it-notes", "plb": "application/vnd.3gpp.pic-bw-large", "psb": "application/vnd.3gpp.pic-bw-small", "pvb": "application/vnd.3gpp.pic-bw-var", "tcap": "application/vnd.3gpp2.tcap", "7z": "application/x-7z-compressed", "abw": "application/x-abiword", "ace": "application/x-ace-compressed", "acc": "application/vnd.americandynamics.acc", "acu": "application/vnd.acucobol", "atc": "application/vnd.acucorp", "adp": "audio/adpcm", "aab": "application/x-authorware-bin", "aam": "application/x-authorware-map", "aas": "application/x-authorware-seg", "air": "application/vnd.adobe.air-application-installer-package+zip", "swf": "application/x-shockwave-flash", "fxp": "application/vnd.adobe.fxp", "pdf": "application/pdf", "ppd": "application/vnd.cups-ppd", "dir": "application/x-director", "xdp": "application/vnd.adobe.xdp+xml", "xfdf": "application/vnd.adobe.xfdf", "aac": "audio/x-aac", "ahead": "application/vnd.ahead.space", "azf": "application/vnd.airzip.filesecure.azf", "azs": "application/vnd.airzip.filesecure.azs", "azw": "application/vnd.amazon.ebook", "ami": "application/vnd.amiga.ami", "N/A": "application/andrew-inset", "apk": "application/vnd.android.package-archive", "cii": "application/vnd.anser-web-certificate-issue-initiation", "fti": "application/vnd.anser-web-funds-transfer-initiation", "atx": "application/vnd.antix.game-component", "dmg": "application/x-apple-diskimage", "mpkg": "application/vnd.apple.installer+xml", "aw": "application/applixware", "mp3": "audio/mpeg", "les": "application/vnd.hhe.lesson-player", "swi": "application/vnd.aristanetworks.swi", "s": "text/x-asm", "atomcat": "application/atomcat+xml", "atomsvc": "application/atomsvc+xml", "atom, .xml": "application/atom+xml", "ac": "application/pkix-attr-cert", "aif": "audio/x-aiff", "avi": "video/x-msvideo", "aep": "application/vnd.audiograph", "dxf": "image/vnd.dxf", "dwf": "model/vnd.dwf", "par": "text/plain-bas", "bcpio": "application/x-bcpio", "bin": "application/octet-stream", "bmp": "image/bmp", "torrent": "application/x-bittorrent", "cod": "application/vnd.rim.cod", "mpm": "application/vnd.blueice.multipass", "bmi": "application/vnd.bmi", "sh": "application/x-sh", "btif": "image/prs.btif", "rep": "application/vnd.businessobjects", "bz": "application/x-bzip", "bz2": "application/x-bzip2", "csh": "application/x-csh", "c": "text/x-c", "cdxml": "application/vnd.chemdraw+xml", "css": "text/css", "cdx": "chemical/x-cdx", "cml": "chemical/x-cml", "csml": "chemical/x-csml", "cdbcmsg": "application/vnd.contact.cmsg", "cla": "application/vnd.claymore", "c4g": "application/vnd.clonk.c4group", "sub": "image/vnd.dvb.subtitle", "cdmia": "application/cdmi-capability", "cdmic": "application/cdmi-container", "cdmid": "application/cdmi-domain", "cdmio": "application/cdmi-object", "cdmiq": "application/cdmi-queue", "c11amc": "application/vnd.cluetrust.cartomobile-config", "c11amz": "application/vnd.cluetrust.cartomobile-config-pkg", "ras": "image/x-cmu-raster", "dae": "model/vnd.collada+xml", "csv": "text/csv", "cpt": "application/mac-compactpro", "wmlc": "application/vnd.wap.wmlc", "cgm": "image/cgm", "ice": "x-conference/x-cooltalk", "cmx": "image/x-cmx", "xar": "application/vnd.xara", "cmc": "application/vnd.cosmocaller", "cpio": "application/x-cpio", "clkx": "application/vnd.crick.clicker", "clkk": "application/vnd.crick.clicker.keyboard", "clkp": "application/vnd.crick.clicker.palette", "clkt": "application/vnd.crick.clicker.template", "clkw": "application/vnd.crick.clicker.wordbank", "wbs": "application/vnd.criticaltools.wbs+xml", "cryptonote": "application/vnd.rig.cryptonote", "cif": "chemical/x-cif", "cmdf": "chemical/x-cmdf", "cu": "application/cu-seeme", "cww": "application/prs.cww", "curl": "text/vnd.curl", "dcurl": "text/vnd.curl.dcurl", "mcurl": "text/vnd.curl.mcurl", "scurl": "text/vnd.curl.scurl", "car": "application/vnd.curl.car", "pcurl": "application/vnd.curl.pcurl", "cmp": "application/vnd.yellowriver-custom-menu", "dssc": "application/dssc+der", "xdssc": "application/dssc+xml", "deb": "application/x-debian-package", "uva": "audio/vnd.dece.audio", "uvi": "image/vnd.dece.graphic", "uvh": "video/vnd.dece.hd", "uvm": "video/vnd.dece.mobile", "uvu": "video/vnd.uvvu.mp4", "uvp": "video/vnd.dece.pd", "uvs": "video/vnd.dece.sd", "uvv": "video/vnd.dece.video", "dvi": "application/x-dvi", "seed": "application/vnd.fdsn.seed", "dtb": "application/x-dtbook+xml", "res": "application/x-dtbresource+xml", "ait": "application/vnd.dvb.ait", "svc": "application/vnd.dvb.service", "eol": "audio/vnd.digital-winds", "djvu": "image/vnd.djvu", "dtd": "application/xml-dtd", "mlp": "application/vnd.dolby.mlp", "wad": "application/x-doom", "dpg": "application/vnd.dpgraph", "dra": "audio/vnd.dra", "dfac": "application/vnd.dreamfactory", "dts": "audio/vnd.dts", "dtshd": "audio/vnd.dts.hd", "dwg": "image/vnd.dwg", "geo": "application/vnd.dynageo", "es": "application/ecmascript", "mag": "application/vnd.ecowin.chart", "mmr": "image/vnd.fujixerox.edmics-mmr", "rlc": "image/vnd.fujixerox.edmics-rlc", "exi": "application/exi", "mgz": "application/vnd.proteus.magazine", "epub": "application/epub+zip", "eml": "message/rfc822", "nml": "application/vnd.enliven", "xpr": "application/vnd.is-xpr", "xif": "image/vnd.xiff", "xfdl": "application/vnd.xfdl", "emma": "application/emma+xml", "ez2": "application/vnd.ezpix-album", "ez3": "application/vnd.ezpix-package", "fst": "image/vnd.fst", "fvt": "video/vnd.fvt", "fbs": "image/vnd.fastbidsheet", "fe_launch": "application/vnd.denovo.fcselayout-link", "f4v": "video/x-f4v", "flv": "video/x-flv", "fpx": "image/vnd.fpx", "npx": "image/vnd.net-fpx", "flx": "text/vnd.fmi.flexstor", "fli": "video/x-fli", "ftc": "application/vnd.fluxtime.clip", "fdf": "application/vnd.fdf", "f": "text/x-fortran", "mif": "application/vnd.mif", "fm": "application/vnd.framemaker", "fh": "image/x-freehand", "fsc": "application/vnd.fsc.weblaunch", "fnc": "application/vnd.frogans.fnc", "ltf": "application/vnd.frogans.ltf", "ddd": "application/vnd.fujixerox.ddd", "xdw": "application/vnd.fujixerox.docuworks", "xbd": "application/vnd.fujixerox.docuworks.binder", "oas": "application/vnd.fujitsu.oasys", "oa2": "application/vnd.fujitsu.oasys2", "oa3": "application/vnd.fujitsu.oasys3", "fg5": "application/vnd.fujitsu.oasysgp", "bh2": "application/vnd.fujitsu.oasysprs", "spl": "application/x-futuresplash", "fzs": "application/vnd.fuzzysheet", "g3": "image/g3fax", "gmx": "application/vnd.gmx", "gtw": "model/vnd.gtw", "txd": "application/vnd.genomatix.tuxedo", "ggb": "application/vnd.geogebra.file", "ggt": "application/vnd.geogebra.tool", "gdl": "model/vnd.gdl", "gex": "application/vnd.geometry-explorer", "gxt": "application/vnd.geonext", "g2w": "application/vnd.geoplan", "g3w": "application/vnd.geospace", "gsf": "application/x-font-ghostscript", "bdf": "application/x-font-bdf", "gtar": "application/x-gtar", "texinfo": "application/x-texinfo", "gnumeric": "application/x-gnumeric", "kml": "application/vnd.google-earth.kml+xml", "kmz": "application/vnd.google-earth.kmz", "gqf": "application/vnd.grafeq", "gif": "image/gif", "gv": "text/vnd.graphviz", "gac": "application/vnd.groove-account", "ghf": "application/vnd.groove-help", "gim": "application/vnd.groove-identity-message", "grv": "application/vnd.groove-injector", "gtm": "application/vnd.groove-tool-message", "tpl": "application/vnd.groove-tool-template", "vcg": "application/vnd.groove-vcard", "h261": "video/h261", "h263": "video/h263", "h264": "video/h264", "hpid": "application/vnd.hp-hpid", "hps": "application/vnd.hp-hps", "hdf": "application/x-hdf", "rip": "audio/vnd.rip", "hbci": "application/vnd.hbci", "jlt": "application/vnd.hp-jlyt", "pcl": "application/vnd.hp-pcl", "hpgl": "application/vnd.hp-hpgl", "hvs": "application/vnd.yamaha.hv-script", "hvd": "application/vnd.yamaha.hv-dic", "hvp": "application/vnd.yamaha.hv-voice", "sfd-hdstx": "application/vnd.hydrostatix.sof-data", "stk": "application/hyperstudio", "hal": "application/vnd.hal+xml", "html": "text/html", "irm": "application/vnd.ibm.rights-management", "sc": "application/vnd.ibm.secure-container", "ics": "text/calendar", "icc": "application/vnd.iccprofile", "ico": "image/x-icon", "igl": "application/vnd.igloader", "ief": "image/ief", "ivp": "application/vnd.immervision-ivp", "ivu": "application/vnd.immervision-ivu", "rif": "application/reginfo+xml", "3dml": "text/vnd.in3d.3dml", "spot": "text/vnd.in3d.spot", "igs": "model/iges", "i2g": "application/vnd.intergeo", "cdy": "application/vnd.cinderella", "xpw": "application/vnd.intercon.formnet", "fcs": "application/vnd.isac.fcs", "ipfix": "application/ipfix", "cer": "application/pkix-cert", "pki": "application/pkixcmp", "crl": "application/pkix-crl", "pkipath": "application/pkix-pkipath", "igm": "application/vnd.insors.igm", "rcprofile": "application/vnd.ipunplugged.rcprofile", "irp": "application/vnd.irepository.package+xml", "jad": "text/vnd.sun.j2me.app-descriptor", "jar": "application/java-archive", "class": "application/java-vm", "jnlp": "application/x-java-jnlp-file", "ser": "application/java-serialized-object", "java": "text/x-java-source,java", "js": "application/javascript", "json": "application/json", "joda": "application/vnd.joost.joda-archive", "jpm": "video/jpm", "jpeg, .jpg": "image/x-citrix-jpeg", "pjpeg": "image/pjpeg", "jpgv": "video/jpeg", "ktz": "application/vnd.kahootz", "mmd": "application/vnd.chipnuts.karaoke-mmd", "karbon": "application/vnd.kde.karbon", "chrt": "application/vnd.kde.kchart", "kfo": "application/vnd.kde.kformula", "flw": "application/vnd.kde.kivio", "kon": "application/vnd.kde.kontour", "kpr": "application/vnd.kde.kpresenter", "ksp": "application/vnd.kde.kspread", "kwd": "application/vnd.kde.kword", "htke": "application/vnd.kenameaapp", "kia": "application/vnd.kidspiration", "kne": "application/vnd.kinar", "sse": "application/vnd.kodak-descriptor", "lasxml": "application/vnd.las.las+xml", "latex": "application/x-latex", "lbd": "application/vnd.llamagraphics.life-balance.desktop", "lbe": "application/vnd.llamagraphics.life-balance.exchange+xml", "jam": "application/vnd.jam", "123": "application/vnd.lotus-1-2-3", "apr": "application/vnd.lotus-approach", "pre": "application/vnd.lotus-freelance", "nsf": "application/vnd.lotus-notes", "org": "application/vnd.lotus-organizer", "scm": "application/vnd.lotus-screencam", "lwp": "application/vnd.lotus-wordpro", "lvp": "audio/vnd.lucent.voice", "m3u": "audio/x-mpegurl", "m4v": "video/x-m4v", "hqx": "application/mac-binhex40", "portpkg": "application/vnd.macports.portpkg", "mgp": "application/vnd.osgeo.mapguide.package", "mrc": "application/marc", "mrcx": "application/marcxml+xml", "mxf": "application/mxf", "nbp": "application/vnd.wolfram.player", "ma": "application/mathematica", "mathml": "application/mathml+xml", "mbox": "application/mbox", "mc1": "application/vnd.medcalcdata", "mscml": "application/mediaservercontrol+xml", "cdkey": "application/vnd.mediastation.cdkey", "mwf": "application/vnd.mfer", "mfm": "application/vnd.mfmp", "msh": "model/mesh", "mads": "application/mads+xml", "mets": "application/mets+xml", "mods": "application/mods+xml", "meta4": "application/metalink4+xml", "mcd": "application/vnd.mcd", "flo": "application/vnd.micrografx.flo", "igx": "application/vnd.micrografx.igx", "es3": "application/vnd.eszigno3+xml", "mdb": "application/x-msaccess", "asf": "video/x-ms-asf", "exe": "application/x-msdownload", "cil": "application/vnd.ms-artgalry", "cab": "application/vnd.ms-cab-compressed", "ims": "application/vnd.ms-ims", "application": "application/x-ms-application", "clp": "application/x-msclip", "mdi": "image/vnd.ms-modi", "eot": "application/vnd.ms-fontobject", "xls": "application/vnd.ms-excel", "xlam": "application/vnd.ms-excel.addin.macroenabled.12", "xlsb": "application/vnd.ms-excel.sheet.binary.macroenabled.12", "xltm": "application/vnd.ms-excel.template.macroenabled.12", "xlsm": "application/vnd.ms-excel.sheet.macroenabled.12", "chm": "application/vnd.ms-htmlhelp", "crd": "application/x-mscardfile", "lrm": "application/vnd.ms-lrm", "mvb": "application/x-msmediaview", "mny": "application/x-msmoney", "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide", "ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow", "potx": "application/vnd.openxmlformats-officedocument.presentationml.template", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template", "obd": "application/x-msbinder", "thmx": "application/vnd.ms-officetheme", "onetoc": "application/onenote", "pya": "audio/vnd.ms-playready.media.pya", "pyv": "video/vnd.ms-playready.media.pyv", "ppt": "application/vnd.ms-powerpoint", "ppam": "application/vnd.ms-powerpoint.addin.macroenabled.12", "sldm": "application/vnd.ms-powerpoint.slide.macroenabled.12", "pptm": "application/vnd.ms-powerpoint.presentation.macroenabled.12", "ppsm": "application/vnd.ms-powerpoint.slideshow.macroenabled.12", "potm": "application/vnd.ms-powerpoint.template.macroenabled.12", "mpp": "application/vnd.ms-project", "pub": "application/x-mspublisher", "scd": "application/x-msschedule", "xap": "application/x-silverlight-app", "stl": "application/vnd.ms-pki.stl", "cat": "application/vnd.ms-pki.seccat", "vsd": "application/vnd.visio", "vsdx": "application/vnd.visio2013", "wm": "video/x-ms-wm", "wma": "audio/x-ms-wma", "wax": "audio/x-ms-wax", "wmx": "video/x-ms-wmx", "wmd": "application/x-ms-wmd", "wpl": "application/vnd.ms-wpl", "wmz": "application/x-ms-wmz", "wmv": "video/x-ms-wmv", "wvx": "video/x-ms-wvx", "wmf": "application/x-msmetafile", "trm": "application/x-msterminal", "doc": "application/msword", "docm": "application/vnd.ms-word.document.macroenabled.12", "dotm": "application/vnd.ms-word.template.macroenabled.12", "wri": "application/x-mswrite", "wps": "application/vnd.ms-works", "xbap": "application/x-ms-xbap", "xps": "application/vnd.ms-xpsdocument", "mid": "audio/midi", "mpy": "application/vnd.ibm.minipay", "afp": "application/vnd.ibm.modcap", "rms": "application/vnd.jcp.javame.midlet-rms", "tmo": "application/vnd.tmobile-livetv", "prc": "application/x-mobipocket-ebook", "mbk": "application/vnd.mobius.mbk", "dis": "application/vnd.mobius.dis", "plc": "application/vnd.mobius.plc", "mqy": "application/vnd.mobius.mqy", "msl": "application/vnd.mobius.msl", "txf": "application/vnd.mobius.txf", "daf": "application/vnd.mobius.daf", "fly": "text/vnd.fly", "mpc": "application/vnd.mophun.certificate", "mpn": "application/vnd.mophun.application", "mj2": "video/mj2", "mpga": "audio/mpeg", "mxu": "video/vnd.mpegurl", "mpeg": "video/mpeg", "m21": "application/mp21", "mp4a": "audio/mp4", "mp4": "application/mp4", "m3u8": "application/vnd.apple.mpegurl", "mus": "application/vnd.musician", "msty": "application/vnd.muvee.style", "mxml": "application/xv+xml", "ngdat": "application/vnd.nokia.n-gage.data", "n-gage": "application/vnd.nokia.n-gage.symbian.install", "ncx": "application/x-dtbncx+xml", "nc": "application/x-netcdf", "nlu": "application/vnd.neurolanguage.nlu", "dna": "application/vnd.dna", "nnd": "application/vnd.noblenet-directory", "nns": "application/vnd.noblenet-sealer", "nnw": "application/vnd.noblenet-web", "rpst": "application/vnd.nokia.radio-preset", "rpss": "application/vnd.nokia.radio-presets", "n3": "text/n3", "edm": "application/vnd.novadigm.edm", "edx": "application/vnd.novadigm.edx", "ext": "application/vnd.novadigm.ext", "gph": "application/vnd.flographit", "ecelp4800": "audio/vnd.nuera.ecelp4800", "ecelp7470": "audio/vnd.nuera.ecelp7470", "ecelp9600": "audio/vnd.nuera.ecelp9600", "oda": "application/oda", "ogx": "application/ogg", "oga": "audio/ogg", "ogv": "video/ogg", "dd2": "application/vnd.oma.dd2+xml", "oth": "application/vnd.oasis.opendocument.text-web", "opf": "application/oebps-package+xml", "qbo": "application/vnd.intu.qbo", "oxt": "application/vnd.openofficeorg.extension", "osf": "application/vnd.yamaha.openscoreformat", "weba": "audio/webm", "webm": "video/webm", "odc": "application/vnd.oasis.opendocument.chart", "otc": "application/vnd.oasis.opendocument.chart-template", "odb": "application/vnd.oasis.opendocument.database", "odf": "application/vnd.oasis.opendocument.formula", "odft": "application/vnd.oasis.opendocument.formula-template", "odg": "application/vnd.oasis.opendocument.graphics", "otg": "application/vnd.oasis.opendocument.graphics-template", "odi": "application/vnd.oasis.opendocument.image", "oti": "application/vnd.oasis.opendocument.image-template", "odp": "application/vnd.oasis.opendocument.presentation", "otp": "application/vnd.oasis.opendocument.presentation-template", "ods": "application/vnd.oasis.opendocument.spreadsheet", "ots": "application/vnd.oasis.opendocument.spreadsheet-template", "odt": "application/vnd.oasis.opendocument.text", "odm": "application/vnd.oasis.opendocument.text-master", "ott": "application/vnd.oasis.opendocument.text-template", "ktx": "image/ktx", "sxc": "application/vnd.sun.xml.calc", "stc": "application/vnd.sun.xml.calc.template", "sxd": "application/vnd.sun.xml.draw", "std": "application/vnd.sun.xml.draw.template", "sxi": "application/vnd.sun.xml.impress", "sti": "application/vnd.sun.xml.impress.template", "sxm": "application/vnd.sun.xml.math", "sxw": "application/vnd.sun.xml.writer", "sxg": "application/vnd.sun.xml.writer.global", "stw": "application/vnd.sun.xml.writer.template", "otf": "application/x-font-otf", "osfpvg": "application/vnd.yamaha.openscoreformat.osfpvg+xml", "dp": "application/vnd.osgi.dp", "pdb": "application/vnd.palm", "p": "text/x-pascal", "paw": "application/vnd.pawaafile", "pclxl": "application/vnd.hp-pclxl", "efif": "application/vnd.picsel", "pcx": "image/x-pcx", "psd": "image/vnd.adobe.photoshop", "prf": "application/pics-rules", "pic": "image/x-pict", "chat": "application/x-chat", "p10": "application/pkcs10", "p12": "application/x-pkcs12", "p7m": "application/pkcs7-mime", "p7s": "application/pkcs7-signature", "p7r": "application/x-pkcs7-certreqresp", "p7b": "application/x-pkcs7-certificates", "p8": "application/pkcs8", "plf": "application/vnd.pocketlearn", "pnm": "image/x-portable-anymap", "pbm": "image/x-portable-bitmap", "pcf": "application/x-font-pcf", "pfr": "application/font-tdpfr", "pgn": "application/x-chess-pgn", "pgm": "image/x-portable-graymap", "png": "image/x-png", "ppm": "image/x-portable-pixmap", "pskcxml": "application/pskc+xml", "pml": "application/vnd.ctc-posml", "ai": "application/postscript", "pfa": "application/x-font-type1", "pbd": "application/vnd.powerbuilder6", "pgp": "application/pgp-signature", "box": "application/vnd.previewsystems.box", "ptid": "application/vnd.pvi.ptid1", "pls": "application/pls+xml", "str": "application/vnd.pg.format", "ei6": "application/vnd.pg.osasli", "dsc": "text/prs.lines.tag", "psf": "application/x-font-linux-psf", "qps": "application/vnd.publishare-delta-tree", "wg": "application/vnd.pmi.widget", "qxd": "application/vnd.quark.quarkxpress", "esf": "application/vnd.epson.esf", "msf": "application/vnd.epson.msf", "ssf": "application/vnd.epson.ssf", "qam": "application/vnd.epson.quickanime", "qfx": "application/vnd.intu.qfx", "qt": "video/quicktime", "rar": "application/x-rar-compressed", "ram": "audio/x-pn-realaudio", "rmp": "audio/x-pn-realaudio-plugin", "rsd": "application/rsd+xml", "rm": "application/vnd.rn-realmedia", "bed": "application/vnd.realvnc.bed", "mxl": "application/vnd.recordare.musicxml", "musicxml": "application/vnd.recordare.musicxml+xml", "rnc": "application/relax-ng-compact-syntax", "rdz": "application/vnd.data-vision.rdz", "rdf": "application/rdf+xml", "rp9": "application/vnd.cloanto.rp9", "jisp": "application/vnd.jisp", "rtf": "application/rtf", "rtx": "text/richtext", "link66": "application/vnd.route66.link66+xml", "rss, .xml": "application/rss+xml", "shf": "application/shf+xml", "st": "application/vnd.sailingtracker.track", "svg": "image/svg+xml", "sus": "application/vnd.sus-calendar", "sru": "application/sru+xml", "setpay": "application/set-payment-initiation", "setreg": "application/set-registration-initiation", "sema": "application/vnd.sema", "semd": "application/vnd.semd", "semf": "application/vnd.semf", "see": "application/vnd.seemail", "snf": "application/x-font-snf", "spq": "application/scvp-vp-request", "spp": "application/scvp-vp-response", "scq": "application/scvp-cv-request", "scs": "application/scvp-cv-response", "sdp": "application/sdp", "etx": "text/x-setext", "movie": "video/x-sgi-movie", "ifm": "application/vnd.shana.informed.formdata", "itp": "application/vnd.shana.informed.formtemplate", "iif": "application/vnd.shana.informed.interchange", "ipk": "application/vnd.shana.informed.package", "tfi": "application/thraud+xml", "shar": "application/x-shar", "rgb": "image/x-rgb", "slt": "application/vnd.epson.salt", "aso": "application/vnd.accpac.simply.aso", "imp": "application/vnd.accpac.simply.imp", "twd": "application/vnd.simtech-mindmapper", "csp": "application/vnd.commonspace", "saf": "application/vnd.yamaha.smaf-audio", "mmf": "application/vnd.smaf", "spf": "application/vnd.yamaha.smaf-phrase", "teacher": "application/vnd.smart.teacher", "svd": "application/vnd.svd", "rq": "application/sparql-query", "srx": "application/sparql-results+xml", "gram": "application/srgs", "grxml": "application/srgs+xml", "ssml": "application/ssml+xml", "skp": "application/vnd.koan", "sgml": "text/sgml", "sdc": "application/vnd.stardivision.calc", "sda": "application/vnd.stardivision.draw", "sdd": "application/vnd.stardivision.impress", "smf": "application/vnd.stardivision.math", "sdw": "application/vnd.stardivision.writer", "sgl": "application/vnd.stardivision.writer-global", "sm": "application/vnd.stepmania.stepchart", "sit": "application/x-stuffit", "sitx": "application/x-stuffitx", "sdkm": "application/vnd.solent.sdkm+xml", "xo": "application/vnd.olpc-sugar", "au": "audio/basic", "wqd": "application/vnd.wqd", "sis": "application/vnd.symbian.install", "smi": "application/smil+xml", "xsm": "application/vnd.syncml+xml", "bdm": "application/vnd.syncml.dm+wbxml", "xdm": "application/vnd.syncml.dm+xml", "sv4cpio": "application/x-sv4cpio", "sv4crc": "application/x-sv4crc", "sbml": "application/sbml+xml", "tsv": "text/tab-separated-values", "tiff": "image/tiff", "tao": "application/vnd.tao.intent-module-archive", "tar": "application/x-tar", "tcl": "application/x-tcl", "tex": "application/x-tex", "tfm": "application/x-tex-tfm", "tei": "application/tei+xml", "txt": "text/plain", "dxp": "application/vnd.spotfire.dxp", "sfs": "application/vnd.spotfire.sfs", "tsd": "application/timestamped-data", "tpt": "application/vnd.trid.tpt", "mxs": "application/vnd.triscape.mxs", "t": "text/troff", "tra": "application/vnd.trueapp", "ttf": "application/x-font-ttf", "ttl": "text/turtle", "umj": "application/vnd.umajin", "uoml": "application/vnd.uoml+xml", "unityweb": "application/vnd.unity", "ufd": "application/vnd.ufdl", "uri": "text/uri-list", "utz": "application/vnd.uiq.theme", "ustar": "application/x-ustar", "uu": "text/x-uuencode", "vcs": "text/x-vcalendar", "vcf": "text/x-vcard", "vcd": "application/x-cdlink", "vsf": "application/vnd.vsf", "wrl": "model/vrml", "vcx": "application/vnd.vcx", "mts": "model/vnd.mts", "vtu": "model/vnd.vtu", "vis": "application/vnd.visionary", "viv": "video/vnd.vivo", "ccxml": "application/ccxml+xml,", "vxml": "application/voicexml+xml", "src": "application/x-wais-source", "wbxml": "application/vnd.wap.wbxml", "wbmp": "image/vnd.wap.wbmp", "wav": "audio/x-wav", "davmount": "application/davmount+xml", "woff": "application/x-font-woff", "wspolicy": "application/wspolicy+xml", "webp": "image/webp", "wtb": "application/vnd.webturbo", "wgt": "application/widget", "hlp": "application/winhlp", "wml": "text/vnd.wap.wml", "wmls": "text/vnd.wap.wmlscript", "wmlsc": "application/vnd.wap.wmlscriptc", "wpd": "application/vnd.wordperfect", "stf": "application/vnd.wt.stf", "wsdl": "application/wsdl+xml", "xbm": "image/x-xbitmap", "xpm": "image/x-xpixmap", "xwd": "image/x-xwindowdump", "der": "application/x-x509-ca-cert", "fig": "application/x-xfig", "xhtml": "application/xhtml+xml", "xml": "application/xml", "xdf": "application/xcap-diff+xml", "xenc": "application/xenc+xml", "xer": "application/patch-ops-error+xml", "rl": "application/resource-lists+xml", "rs": "application/rls-services+xml", "rld": "application/resource-lists-diff+xml", "xslt": "application/xslt+xml", "xop": "application/xop+xml", "xpi": "application/x-xpinstall", "xspf": "application/xspf+xml", "xul": "application/vnd.mozilla.xul+xml", "xyz": "chemical/x-xyz", "yaml": "text/yaml", "yang": "application/yang", "yin": "application/yin+xml", "zir": "application/vnd.zul", "zip": "application/zip", "zmm": "application/vnd.handheld-entertainment+xml", "zaz": "application/vnd.zzazz.deck+xml"}

How to printf a 64-bit integer as hex?

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

Try using %lx or %llx. For more portability, include inttypes.h and use the PRIx64 macro.

For example: printf("val = 0x%" PRIx64 "\n", val); (note that it's string concatenation)

java Compare two dates

Try using this Function.It Will help You:-

public class Main {   
public static void main(String args[]) 
 {        
  Date today=new Date();                     
  Date myDate=new Date(today.getYear(),today.getMonth()-1,today.getDay());
  System.out.println("My Date is"+myDate);    
  System.out.println("Today Date is"+today);
  if(today.compareTo(myDate)<0)
     System.out.println("Today Date is Lesser than my Date");
  else if(today.compareTo(myDate)>0)
     System.out.println("Today Date is Greater than my date"); 
  else
     System.out.println("Both Dates are equal");      
  }
}

How exactly does __attribute__((constructor)) work?

Here is a "concrete" (and possibly useful) example of how, why, and when to use these handy, yet unsightly constructs...

Xcode uses a "global" "user default" to decide which XCTestObserver class spews it's heart out to the beleaguered console.

In this example... when I implicitly load this psuedo-library, let's call it... libdemure.a, via a flag in my test target á la..

OTHER_LDFLAGS = -ldemure

I want to..

  1. At load (ie. when XCTest loads my test bundle), override the "default" XCTest "observer" class... (via the constructor function) PS: As far as I can tell.. anything done here could be done with equivalent effect inside my class' + (void) load { ... } method.

  2. run my tests.... in this case, with less inane verbosity in the logs (implementation upon request)

  3. Return the "global" XCTestObserver class to it's pristine state.. so as not to foul up other XCTest runs which haven't gotten on the bandwagon (aka. linked to libdemure.a). I guess this historically was done in dealloc.. but I'm not about to start messing with that old hag.

So...

#define USER_DEFS NSUserDefaults.standardUserDefaults

@interface      DemureTestObserver : XCTestObserver @end
@implementation DemureTestObserver

__attribute__((constructor)) static void hijack_observer() {

/*! here I totally hijack the default logging, but you CAN
    use multiple observers, just CSV them, 
    i.e. "@"DemureTestObserverm,XCTestLog"
*/
  [USER_DEFS setObject:@"DemureTestObserver" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

__attribute__((destructor)) static void reset_observer()  {

  // Clean up, and it's as if we had never been here.
  [USER_DEFS setObject:@"XCTestLog" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

...
@end

Without the linker flag... (Fashion-police swarm Cupertino demanding retribution, yet Apple's default prevails, as is desired, here)

enter image description here

WITH the -ldemure.a linker flag... (Comprehensible results, gasp... "thanks constructor/destructor"... Crowd cheers) enter image description here

HTTP Content-Type Header and JSON

The Content-Type header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.

The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json then parse it as JSON.

This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-Type to detect what to do with it.

Get Line Number of certain phrase in file Python

def get_line_number(phrase, file_name):
    with open(file_name) as f:
        for i, line in enumerate(f, 1):
            if phrase in line:
                return i

How to set a class attribute to a Symfony2 form input

Like this:

{{ form_widget(form.description, { 'attr': {'class': 'form-control', 'rows': '5', 'style': 'resize:none;'} }) }}

program cant start because php5.dll is missing

I needed to change environment variable PATH and PHPRC. Also open new cmd.

I already had PHP installed and added EasyPHP when the problem came up. After I changed both variables to C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\binaries\php\php_runningversion it worked fine.

Cursor adapter and sqlite example

In Android, How to use a Cursor with a raw query in sqlite:

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
           "where Age > 10 LIMIT 5", null);

if (c != null ) {
    if  (c.moveToFirst()) {
        do {
            String firstName = c.getString(c.getColumnIndex("FirstName"));
            int age = c.getInt(c.getColumnIndex("Age"));
            results.add("" + firstName + ",Age: " + age);
        }while (c.moveToNext());
    }
}
c.close();

How to get text of an input text box during onKeyPress?

Handling the input event is a consistent solution: it is supported for textarea and input elements in all contemporary browsers and it fires exactly when you need it:

_x000D_
_x000D_
function edValueKeyPress() {
    var edValue = document.getElementById("edValue");
    var s = edValue.value;

    var lblValue = document.getElementById("lblValue");
    lblValue.innerText = "The text box contains: " + s;
}
_x000D_
<input id="edValue" type="text" onInput="edValueKeyPress()"><br>
<span id="lblValue">The text box contains: </span>
_x000D_
_x000D_
_x000D_

I'd rewrite this a bit, though:

_x000D_
_x000D_
function showCurrentValue(event)
{
    const value = event.target.value;
    document.getElementById("label").innerText = value;
}
_x000D_
<input type="text" onInput="showCurrentValue(event)"><br>
The text box contains: <span id="label"></span>
_x000D_
_x000D_
_x000D_

Extract digits from string - StringUtils Java

Just one line:

int value = Integer.parseInt(string.replaceAll("[^0-9]", ""));

Custom exception type

//create error object
var error = new Object();
error.reason="some reason!";

//business function
function exception(){
    try{
        throw error;
    }catch(err){
        err.reason;
    }
}

Now we set add the reason or whatever properties we want to the error object and retrieve it. By making the error more reasonable.

The conversion of the varchar value overflowed an int column

Just make rdg2.nPhoneNumber varchar everywhere instead of int !

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql_upgrade to fix the problem:

/usr/bin/mysql_upgrade -u root -p

Login as root:

mysql -u root -p

Run this commands:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
mysql> FLUSH PRIVILEGES;

How can I get a specific parameter from location.search?

It took me a while to find the answer to this question. Most people seem to be suggesting regex solutions. I strongly prefer to use code that is tried and tested as opposed to regex that I or someone else thought up on the fly.

I use the parseUri library available here: http://stevenlevithan.com/demo/parseuri/js/

It allows you to do exactly what you are asking for:

var uri = 'http://localhost/search.php?year=2008';
var year = uri.queryKey['year'];
// year = '2008'

Character Limit in HTML

There are 2 main solutions:

The pure HTML one:

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

The JavaScript one (attach it to a onKey Event):

function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.

What is the PHP syntax to check "is not null" or an empty string?

Null OR an empty string?

if (!empty($user)) {}

Use empty().


After realizing that $user ~= $_POST['user'] (thanks matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';