Programs & Examples On #Mud

MUDs (historically Multi-User Dungeon, with later variants including Multi-User Dimension and Multi-User Domain) are a broad category of multi-user virtual world systems -- usually text-based, usually games, usually accessed via the Telnet protocol, and usually free. They date to Roy Trubshaw and Richard Bartle's creation of MUD1 in 1978, and are the direct predecessor genre to the MMORPG.

error: resource android:attr/fontVariationSettings not found

Another fix for Ionic 3 devs is to create build-extras.gradle inside platforms/android and put following

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-v4:27.1.0'
    }
}

Note that build-extras.gradle is not the same as build.gradle

gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

Update Oct. 2016: issue 871 did mention "Signing stopped working in Git 2.9.3"

Git for Windows 2.10.1 released two days ago (Oct. 4th, 2016) has fixed Interactive GPG signing of commits and tag.

the recent gpg-sign change in git (which introduces no problem on Linux) exposes a problem in the way in which, on Windows, non-MSYS2-git interacts with MSYS2-gpg.


Original answer:

Reading "7.4 Git Tools - Signing Your Work", I assume you have your "user.signingkey" configuration set.

The last big refactoring (before Git 2.10) around gpg was in commit 2f47eae2a, here that error message was moved to gpg-interface.c

A log on that file reveals the recent change in commit af2b21e (Git 2.10)

gpg2 already uses the long format by default, but most distributions seem to still have "gpg" be the older 1.x version due to compatibility reasons. And older versions of gpg only show the 32-bit short ID, which is quite insecure.

This doesn't actually matter for the verification itself: if the verification passes, the pgp signature is good.
But if you don't actually have the key yet, and want to fetch it, or you want to check exactly which key was used for verification and want to check it, we should specify the key with more precision.

So check how you specified your user.signingkey configuration, and the version of gpg you are using (gpg1 or gpg2), to see if those have any effect on the error message.

There is also commit 0581b54 which changes the condition for the gpg failed to sign the data error message (in complement to commit 0d2b664):

We don't read from stderr at all currently. However, we will want to in a future patch, so this also prepares us there (and in that case gpg does write before reading all of the input, though again, it is unlikely that a key uid will fill up a pipe buffer).

Commit 4322353 shows gpg now uses a temporary file, so there could be right issues around that.

Let's convert to using a tempfile object, which handles the hard cases for us, and add the missing cleanup call.

Visual Studio Code always asking for git credentials

For windows 10 : go to control panel/Credential manager/ Windows Credential--> click on the git link, --> edit--> update to new password. That should work

How to unzip gz file using Python

It is very simple.. Here you go !!

import gzip

#path_to_file_to_be_extracted

ip = sample.gzip

#output file to be filled

op = open("output_file","w") 

with gzip.open(ip,"rb") as ip_byte:
    op.write(ip_byte.read().decode("utf-8")
    wf.close()

How to darken a background using CSS?

Just add this code to your image css

_x000D_
_x000D_
 body{
 background:
        /* top, transparent black, faked with gradient */ 
        linear-gradient(
          rgba(0, 0, 0, 0.7), 
          rgba(0, 0, 0, 0.7)
        ),
        /* bottom, image */
        url(https://images.unsplash.com/photo-1614030424754-24d0eebd46b2);
    }
_x000D_
_x000D_
_x000D_

Reference: linear-gradient() - CSS | MDN

UPDATE: Not all browsers support RGBa, so you should have a 'fallback color'. This color will be most likely be solid (fully opaque) ex:background:rgb(96, 96, 96). Refer to this blog for RGBa browser support.

Display an image into windows forms

There could be many reasons for this. A few that come up quickly to my mind:

  1. Did you call this routine AFTER InitializeComponent()?
  2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
  3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

Object not found! The requested URL was not found on this server. localhost

mostly this kind of error is caused by missing an .htaccess file in your root wordpress directory , however in order to check that , get in touch directly to the permalink structure and try to change your permalink and hit save , once you find the same error you should directly create an .htaccess file under wordpress root and make its first permissions to 777 , then refresh your site an click save change on your permalink , once your site continue to run correctly as you were expected , you should right away comeback to your .htaccess and change it to 644 in order to secure your site , i believe that this happened in most wordpress permalink settings , hopefully it would be helpful for anyone who meet this kind of issue .

RSA Public Key format

Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:

  • 00 00 00 07: four byte length prefix (7 bytes)
  • 73 73 68 2d 72 73 61: "ssh-rsa"
  • 00 00 00 01: four byte length prefix (1 byte)
  • 25: RSA Exponent (e): 25
  • 00 00 01 00: four byte length prefix (256 bytes)
  • RSA Modulus (n):

    7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
    d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46 
    dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9 
    cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32 
    70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60 
    1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1 
    90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d 
    3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0 
    e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb 
    d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b 
    ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d 
    e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8 
    76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1 
    fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f 
    5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b 
    60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
    

The closest validation of my theory i can find it from RFC 4253:

The "ssh-rsa" key format has the following specific encoding:

  string    "ssh-rsa"
  mpint     e
  mpint     n

Here the 'e' and 'n' parameters form the signature key blob.

But it doesn't explain the length prefixes.


Taking the random RSA PUBLIC KEY i found (in the question), and decoding the base64 into hex:

30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
63 02 03 01 00 01

From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:

A.1.1 RSA public key syntax

An RSA public key should be represented with the ASN.1 type RSAPublicKey:

  RSAPublicKey ::= SEQUENCE {
     modulus           INTEGER,  -- n
     publicExponent    INTEGER   -- e
  }

The fields of type RSAPublicKey have the following meanings:

  • modulus is the RSA modulus n.
  • publicExponent is the RSA public exponent e.

Using Microsoft's excellent (and the only real) ASN.1 documentation:

30 82 01 0a       ;SEQUENCE (0x010A bytes: 266 bytes)
|  02 82 01 01    ;INTEGER  (0x0101 bytes: 257 bytes)
|  |  00          ;leading zero because high-bit, but number is positive
|  |  fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
|  |  e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
|  |  11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
|  |  dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
|  |  fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
|  |  23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
|  |  9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
|  |  4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
|  |  41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
|  |  97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
|  |  fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
|  |  63 
|  02 03          ;INTEGER (3 bytes)
|     01 00 01

giving the public key modulus and exponent:

  • modulus = 0xfb1199ff0733f6e805a4fd3b36ca68...837a63
  • exponent = 65,537

Update: My expanded form of this answer in another question

Tomcat is not deploying my web project from Eclipse

I have the same problem, my solution is:

  • Install WTP Maven integration (don't know if this is necessary)
  • Project -> Run Configurations (Select your tomcat server) -> Run

For a few hours I tried to deploy and start application using Servers window but it didn't worked. My war was not placed in wptwebapps folder, manually deplying war to webapps worked.

Using Run Configurations made my app finally deployable...

Styling Form with Label above Inputs

I know this is an old one with an accepted answer, and that answer works great.. IF you are not styling the background and floating the final inputs left. If you are, then the form background will not include the floated input fields.

To avoid this make the divs with the smaller input fields inline-block rather than float left.

This:

<div style="display:inline-block;margin-right:20px;">
    <label for="name">Name</label>
    <input id="name" type="text" value="" name="name">
</div>

Rather than:

<div style="float:left;margin-right:20px;">
    <label for="name">Name</label>
    <input id="name" type="text" value="" name="name">
</div>

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Wpf control size to content?

If you are using the grid or alike component: In XAML, make sure that the elements in the grid have Grid.Row and Grid.Column defined, and ensure tha they don't have margins. If you used designer mode, or Expression Blend, it could have assigned margins relative to the whole grid instead of to particular cells. As for cell sizing, I add an extra cell that fills up the rest of the space:

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

Count number of occurences for each unique value

If you have multiple factors (= a multi-dimensional data frame), you can use the dplyr package to count unique values in each combination of factors:

library("dplyr")
data %>% group_by(factor1, factor2) %>% summarize(count=n())

It uses the pipe operator %>% to chain method calls on the data frame data.

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

I saw this error in combination with the PageSpeed module enabled. The PageSpeed module has a cache that can be gzip compressed. So apparently what can happen is that content gets double compressed.

In order to rewrite resources, PageSpeed must cache them server-side. Until 1.10.33.0, these resources had been stored uncompressed. To reduce disk usage, decrease server latency, support higher compression levels, and increase server throughput, the HTTPCache can automatically gzip compressable resources as they are stored in the cache. To configure cache compression, set HttpCacheCompressionLevel to values between -1 and 9, with 0 being off, -1 being gzip's default compression, and 9 being maximum compression. The default value is 9, maximum compression.

I solved it by adding this line to my PageSpeed config:

HttpCacheCompressionLevel 0

which disables the compression.

How do you get the magnitude of a vector in Numpy?

You can do this concisely using the toolbelt vg. It's a light layer on top of numpy and it supports single values and stacked vectors.

import numpy as np
import vg

x = np.array([1, 2, 3, 4, 5])
mag1 = np.linalg.norm(x)
mag2 = vg.magnitude(x)
print mag1 == mag2
# True

I created the library at my last startup, where it was motivated by uses like this: simple ideas which are far too verbose in NumPy.

How to get my project path?

Your program has no knowledge of where your VS project is, so see get path for my .exe and go ../.. to get your project's path.

Check whether a string matches a regex in JS

You can try this, it works for me.

 <input type="text"  onchange="CheckValidAmount(this.value)" name="amount" required>

 <script type="text/javascript">
    function CheckValidAmount(amount) {          
       var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
       if(amount.match(a)){
           alert("matches");
       }else{
        alert("does not match"); 
       }
    }
</script>

Checkout another branch when there are uncommitted changes on the current branch

The correct answer is

git checkout -m origin/master

It merges changes from the origin master branch with your local even uncommitted changes.

Ternary operators in JavaScript without an "else"

First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

This means several things:

  • use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
  • only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
  • each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)

In short - the 'correct' use of a ternary expression is

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

 condition && (x = true);

This is still an expression and might therefore not pass validation, so an even better approach would be

 void(condition && x = true);

The last one will pass validation.

But then again, if the expected value is a boolean, just use the result of the condition expression itself

var x = (condition); // var x = (foo == "bar");

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

AssertContains on strings in jUnit

It's too late, but just to update I got it done with below syntax

import org.hamcrest.core.StringContains;
import org.junit.Assert;

Assert.assertThat("this contains test", StringContains.containsString("test"));

What is PEP8's E128: continuation line under-indented for visual indent?

This goes also for statements like this (auto-formatted by PyCharm):

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

Which will give the same style-warning. In order to get rid of it I had to rewrite it to:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])

How to get the previous page URL using JavaScript?

<script type="text/javascript">
    document.write(document.referrer);
</script>

document.referrer serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.

It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.

How to round a number to significant figures in Python

The sigfig package/library covers this. After installing you can do the following:

>>> from sigfig import round
>>> round(1234, 1)
1000
>>> round(0.12, 1)
0.1
>>> round(0.012, 1)
0.01
>>> round(0.062, 1)
0.06
>>> round(6253, 1)
6000
>>> round(1999, 1)
2000

Convert Promise to Observable

try this:

import 'rxjs/add/observable/fromPromise';
import { Observable } from "rxjs/Observable";

const subscription = Observable.fromPromise(
    firebase.auth().createUserWithEmailAndPassword(email, password)
);
subscription.subscribe(firebaseUser => /* Do anything with data received */,
                       error => /* Handle error here */);

you can find complete reference to fromPromise operator here.

printing out a 2-D array in Matrix format

int[][] matrix = {
    {1,2,3},
    {4,5,6},
    {7,8,9},
    {10,11,12}
};

printMatrix(matrix);

public void printMatrix(int[][] m){
    try{
        int rows = m.length;
        int columns = m[0].length;
        String str = "|\t";

        for(int i=0;i<rows;i++){
            for(int j=0;j<columns;j++){
                str += m[i][j] + "\t";
            }

            System.out.println(str + "|");
            str = "|\t";
        }

    }catch(Exception e){System.out.println("Matrix is empty!!");}
}

Output:

|   1   2   3   |
|   4   5   6   |
|   7   8   9   |
|   10  11  12  |

How can I force a hard reload in Chrome for Android

Recent versions of Chrome cache very aggressively. Even cache-busting techniques such as "http://url?updated=datecode" stopped working. You must clear the cache or launch an incognito window every time (and make sure data-saver is off).

MVC Razor Hidden input and passing values

If you are using Razor, you cannot access the field directly, but you can manage its value.

The idea is that the first Microsoft approach drive the developers away from Web Development and make it easy for Desktop programmers (for example) to make web applications.

Meanwhile, the web developers, did not understand this tricky strange way of ASP.NET.

Actually this hidden input is rendered on client-side, and the ASP has no access to it (it never had). However, in time you will see its a piratical way and you may rely on it, when you get use with it. The web development differs from the Desktop or Mobile.

The model is your logical unit, and the hidden field (and the whole view page) is just a representative view of the data. So you can dedicate your work on the application or domain logic and the view simply just serves it to the consumer - which means you need no detailed access and "brainstorming" functionality in the view.

The controller actually does work you need for manage the hidden or general setup. The model serves specific logical unit properties and functionality and the view just renders it to the end user, simply said. Read more about MVC.

Model

public class MyClassModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string MyPropertyForHidden { get; set; }
}

This is the controller aciton

public ActionResult MyPageView()
{
    MyClassModel model = new MyClassModel(); // Single entity, strongly-typed
    // IList model = new List<MyClassModel>(); // or List, strongly-typed
    // ViewBag.MyHiddenInputValue = "Something to pass"; // ...or using ViewBag

    return View(model);
}

The view is below

//This will make a Model property of the View to be of MyClassModel
@model MyNamespace.Models.MyClassModel // strongly-typed view
// @model IList<MyNamespace.Models.MyClassModel> // list, strongly-typed view

// ... Some Other Code ...

@using(Html.BeginForm()) // Creates <form>
{
    // Renders hidden field for your model property (strongly-typed)
    // The field rendered to server your model property (Address, Phone, etc.)
    Html.HiddenFor(model => Model.MyPropertyForHidden); 

    // For list you may use foreach on Model
    // foreach(var item in Model) or foreach(MyClassModel item in Model)
}

// ... Some Other Code ...

The view with ViewBag:

// ... Some Other Code ...

@using(Html.BeginForm()) // Creates <form>
{
    Html.Hidden(
        "HiddenName",
        ViewBag.MyHiddenInputValue,
        new { @class = "hiddencss", maxlength = 255 /*, etc... */ }
    );
}

// ... Some Other Code ...

We are using Html Helper to render the Hidden field or we could write it by hand - <input name=".." id=".." value="ViewBag.MyHiddenInputValue"> also.

The ViewBag is some sort of data carrier to the view. It does not restrict you with model - you can place whatever you like.

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

Position a div container on the right side

  • Use float: right to.. float the second column to the.. right.
  • Use overflow: hidden to clear the floats so that the background color I just put in will be visible.

Live Demo

#wrapper{
    background:#000;
    overflow: hidden
}
#c1 {
   float:left;
   background:red;
}
#c2 {
    background:green;
    float: right
}

Finding duplicate values in a SQL table

You can use the SELECT DISTINCT keyword to get rid of duplicates. You can also filter by name and get everyone with that name on a table.

Handling identity columns in an "Insert Into TABLE Values()" statement?

Another "trick" for generating the column list is simply to drag the "Columns" node from Object Explorer onto a query window.

C# try catch continue execution

In your second function remove the e variable in the catch block then add throw.

This will carry over the generated exception the the final function and output it.

Its very common when you dont want your business logic code to throw exception but your UI.

What does the colon (:) operator do?

There is no "colon" operator, but the colon appears in two places:

1: In the ternary operator, e.g.:

int x = bigInt ? 10000 : 50;

In this case, the ternary operator acts as an 'if' for expressions. If bigInt is true, then x will get 10000 assigned to it. If not, 50. The colon here means "else".

2: In a for-each loop:

double[] vals = new double[100];
//fill x with values
for (double x : vals) {
    //do something with x
}

This sets x to each of the values in 'vals' in turn. So if vals contains [10, 20.3, 30, ...], then x will be 10 on the first iteration, 20.3 on the second, etc.

Note: I say it's not an operator because it's just syntax. It can't appear in any given expression by itself, and it's just chance that both the for-each and the ternary operator use a colon.

Android DialogFragment vs Dialog

May I suggest a little simplification of @ashishduh's answer:

public class AlertDialogFragment extends DialogFragment {
public static final String ARG_TITLE = "AlertDialog.Title";
public static final String ARG_MESSAGE = "AlertDialog.Message";

public static void showAlert(String title, String message, Fragment targetFragment) {
    DialogFragment dialog = new AlertDialogFragment();
    Bundle args = new Bundle();
    args.putString(ARG_TITLE, title);
    args.putString(ARG_MESSAGE, message);
    dialog.setArguments(args);
    dialog.setTargetFragment(targetFragment, 0);
    dialog.show(targetFragment.getFragmentManager(), "tag");
}

public AlertDialogFragment() {}

@NonNull
@Override
public AlertDialog onCreateDialog(Bundle savedInstanceState)
{
    Bundle args = getArguments();
    String title = args.getString(ARG_TITLE, "");
    String message = args.getString(ARG_MESSAGE, "");

    return new AlertDialog.Builder(getActivity())
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
                }
            })
            .create();
}

It removes the need for the user (of the class) to be familiar with the internals of the component and makes usage really simple:

AlertDialogFragment.showAlert(title, message, this);

P.S. In my case I needed a simple alert dialog so that's what I created. You can apply the approach to a Yes/No or any other type you need.

At runtime, find all classes in a Java application that extend a base class

Java dynamically loads classes, so your universe of classes would be only those that have already been loaded (and not yet unloaded). Perhaps you can do something with a custom class loader that could check the supertypes of each loaded class. I don't think there's an API to query the set of loaded classes.

Default value in an asp.net mvc view model

Create a base class for your ViewModels with the following constructor code which will apply the DefaultValueAttributeswhen any inheriting model is created.

public abstract class BaseViewModel
{
    protected BaseViewModel()
    {
        // apply any DefaultValueAttribute settings to their properties
        var propertyInfos = this.GetType().GetProperties();
        foreach (var propertyInfo in propertyInfos)
        {
            var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
            if (attributes.Any())
            {
                var attribute = (DefaultValueAttribute) attributes[0];
                propertyInfo.SetValue(this, attribute.Value, null);
            }
        }
    }
}

And inherit from this in your ViewModels:

public class SearchModel : BaseViewModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}

Ansible: get current target host's IP address

The following snippet will return the public ip of the remote machine and also default ip(i.e: LAN)

This will print ip's in quotes also to avoid confusion in using config files.

_x000D_
_x000D_
>> main.yml_x000D_
_x000D_
---_x000D_
- hosts: localhost_x000D_
  tasks:_x000D_
    - name: ipify_x000D_
      ipify_facts:_x000D_
    - debug: var=hostvars[inventory_hostname]['ipify_public_ip']_x000D_
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']_x000D_
    - name: template_x000D_
      template:_x000D_
        src: debug.j2_x000D_
        dest: /tmp/debug.ansible_x000D_
_x000D_
>> templates/debug.j2_x000D_
_x000D_
public_ip={{ hostvars[inventory_hostname]['ipify_public_ip'] }}_x000D_
public_ip_in_quotes="{{ hostvars[inventory_hostname]['ipify_public_ip'] }}"_x000D_
_x000D_
default_ipv4={{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}_x000D_
default_ipv4_in_quotes="{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"
_x000D_
_x000D_
_x000D_

Use cases for the 'setdefault' dict method

You could say defaultdict is useful for settings defaults before filling the dict and setdefault is useful for setting defaults while or after filling the dict.

Probably the most common use case: Grouping items (in unsorted data, else use itertools.groupby)

# really verbose
new = {}
for (key, value) in data:
    if key in new:
        new[key].append( value )
    else:
        new[key] = [value]


# easy with setdefault
new = {}
for (key, value) in data:
    group = new.setdefault(key, []) # key might exist already
    group.append( value )


# even simpler with defaultdict 
from collections import defaultdict
new = defaultdict(list)
for (key, value) in data:
    new[key].append( value ) # all keys have a default already

Sometimes you want to make sure that specific keys exist after creating a dict. defaultdict doesn't work in this case, because it only creates keys on explicit access. Think you use something HTTP-ish with many headers -- some are optional, but you want defaults for them:

headers = parse_headers( msg ) # parse the message, get a dict
# now add all the optional headers
for headername, defaultvalue in optional_headers:
    headers.setdefault( headername, defaultvalue )

Converting a Java Keystore into PEM Format

Converting a JKS KeyStore to a single PEM file can easily be accomplished using the following command:

keytool -list -rfc -keystore "myKeystore.jks" | sed -e "/-*BEGIN [A-Z]*-*/,/-*END [A-Z]-*/!d" >> "myKeystore.pem"

Explanation:

  1. keytool -list -rfc -keystore "myKeystore.jks" lists everything in the 'myKeyStore.jks' KeyStore in PEM format. However, it also prints extra information.
  2. | sed -e "/-*BEGIN [A-Z]*-*/,/-*END [A-Z]-*/!d" filters out everything we don't need. We are left with only the PEMs of everything in the KeyStore.
  3. >> "myKeystore.pem" write the PEMs to the file 'myKeyStore.pem'.

Is there a way to get a list of column names in sqlite?

You can get a list of column names by running:

SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name      
tbl_name  
rootpage  
sql

You can check if a certain column exists by running:

SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='sql';
1

Reference:

https://www.sqlite.org/pragma.html#pragfunc

How to read a .properties file which contains keys that have a period character using Shell script

@fork2x

I have tried like this .Please review and update me whether it is right approach or not.

#/bin/sh
function pause(){
   read -p "$*"
}

file="./apptest.properties"


if [ -f "$file" ]
then
    echo "$file found."

dbUser=`sed '/^\#/d' $file | grep 'db.uat.user'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
dbPass=`sed '/^\#/d' $file | grep 'db.uat.passwd'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`

echo database user = $dbUser
echo database pass = $dbPass

else
    echo "$file not found."
fi

How to check visibility of software keyboard in Android?

Here is a workaround to know if softkeyboard is visible.

  1. Check for running services on the system using ActivityManager.getRunningServices(max_count_of_services);
  2. From the returned ActivityManager.RunningServiceInfo instances, check clientCount value for soft keyboard service.
  3. The aforementioned clientCount will be incremented every time, the soft keyboard is shown. For example, if clientCount was initially 1, it would be 2 when the keyboard is shown.
  4. On keyboard dismissal, clientCount is decremented. In this case, it resets to 1.

Some of the popular keyboards have certain keywords in their classNames:

Google AOSP = IME
Swype = IME
Swiftkey = KeyboardService
Fleksy = keyboard
Adaptxt = IME (KPTAdaptxtIME)
Smart = Keyboard (SmartKeyboard)

From ActivityManager.RunningServiceInfo, check for the above patterns in ClassNames. Also, ActivityManager.RunningServiceInfo's clientPackage=android, indicating that the keyboard is bound to system.

The above mentioned information could be combined for a strict way to find out if soft keyboard is visible.

Hidden TextArea

Set CSS display to none for textarea

<textarea name="hide" style="display:none;"></textarea>

How do I get the serial key for Visual Studio Express?

I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.

Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".

Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.

How can I calculate the difference between two ArrayLists?

I have used Guava Sets.difference.

The parameters are sets and not general collections, but a handy way to create sets from any collection (with unique items) is Guava ImmutableSet.copyOf(Iterable).

(I first posted this on a related/dupe question, but I'm copying it here too since I feel it is a good option that is so far missing.)

How to decode jwt token in javascript without using a library?

If you use Node.JS, You can use the native Buffer module by doing :

const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImp0aSI6ImU3YjQ0Mjc4LTZlZDYtNDJlZC05MTZmLWFjZDQzNzhkM2U0YSIsImlhdCI6MTU5NTg3NzUxOCwiZXhwIjoxNTk1ODgxMTE4fQ.WXyDlDMMSJAjOFF9oAU9JrRHg2wio-WolWAkAaY3kg4';
const base64Url = token.split('.')[1];
const decoded = Buffer.from(base64Url, 'base64').toString();
console.log(decoded)

And you're good to go :-)

How to compare two dates in php

Using DateTime::createFromFormat:

$format = "d_m_y";
$date1  = \DateTime::createFromFormat($format, "03_01_12");
$date2  = \DateTime::createFromFormat($format, "31_12_11");

var_dump($date1 > $date2);

PHP error: "The zip extension and unzip command are both missing, skipping."

I'm Using Ubuntu and with the following command worked

apt-get install --yes zip unzip

How to hide a div after some time period?

In older versions of jquery you'll have to do it the "javascript way" using settimeout

setTimeout( function(){$('div').hide();} , 4000);

or

setTimeout( "$('div').hide();", 4000);

Recently with jquery 1.4 this solution has been added:

$("div").delay(4000).hide();

Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Combine several images horizontally with Python

You can do something like this:

import sys
from PIL import Image

images = [Image.open(x) for x in ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']]
widths, heights = zip(*(i.size for i in images))

total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
  new_im.paste(im, (x_offset,0))
  x_offset += im.size[0]

new_im.save('test.jpg')

Test1.jpg

Test1.jpg

Test2.jpg

Test2.jpg

Test3.jpg

Test3.jpg

test.jpg

enter image description here


The nested for for i in xrange(0,444,95): is pasting each image 5 times, staggered 95 pixels apart. Each outer loop iteration pasting over the previous.

for elem in list_im:
  for i in xrange(0,444,95):
    im=Image.open(elem)
    new_im.paste(im, (i,0))
  new_im.save('new_' + elem + '.jpg')

enter image description here enter image description here enter image description here

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

If you are using Primefaces, you should insert inside the the .xhtml file so it converts correctly to java integer. For example:

<p:selectCheckboxMenu 
    id="frameSelect"
    widgetVar="frameSelectBox"
    filter="true"
    filterMatchMode="contains"
    label="#{messages['frame']}"
    value="#{platform.frameBean.selectedFramesTypesList}"
    converter="javax.faces.Integer">
    <f:selectItems
        value="#{platform.frameBean.framesTypesList}"
        var="area"
        itemLabel="#{area}"
        itemValue="#{area}" />
</p:selectCheckboxMenu>

$("#form1").validate is not a function

I had the same issue, and yes I had my jquery included first followed by the jquery validate script. I had no idea what was wrong. Turns out I was using a validate url that had moved. I figured this out by doing the following:

  1. Open firefox
  2. Open firebug
  3. Click the NET tab in firebug. This will show you all the resources that get loaded.
  4. Load your page.
  5. Check the loaded resources and see if both your jquery & jquery.validate.js loaded.

In my situation I had a 403 Forbidden error when trying to obtain (http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js which is used in the example on http://rocketsquared.com/wiki/Plugins/Validation ).

Turns out the that link (http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js) had moved to http://view.jquery.com/trunk/plugins/validate/jquery.validate.js (Firebug told me this when I loaded the file locally as opposed to on my web server).

NOTE: I tried using microsoft's CDN link also but it failed when I tried to load the javascript file in the browser with the correct url, there was some odd issue going on with the CDN site.

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

PHP 7 simpleXML

For Alpine (in docker), you can use apk add php7-simplexml.

If that doesn't work for you, you can run apk add --no-cache php7-simplexml. This is in case you aren't updating the package index first.

How to remove all ListBox items?

while (listBox1.Items.Count > 0){ 
    listBox1.Items.Remove(0);
}

Python error "ImportError: No module named"

I had the same problem (Python 2.7 Linux), I have found the solution and i would like to share it. In my case i had the structure below:

Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py

In 'main.py' I had tried unsuccessfully all the combinations bellow:

from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...

The solution was much more simple than I thought. I renamed the folder "Booklet" into "booklet" and that's it. Now Python can import the class Question normally by using in 'main.py' the code:

from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass

From this I can conclude that Package-Names (folders) like 'booklet' must start from lower-case, else Python confuses it with Class names and Filenames.

Apparently, this was not your problem, but John Fouhy's answer is very good and this thread has almost anything that can cause this issue. So, this is one more thing and I hope that maybe this could help others.

How to access the GET parameters after "?" in Express?

In my case with the given code, I was able to parse the value of the passed parameter in this way.

_x000D_
_x000D_
const express = require('express');
const bodyParser = require('body-parser');

const app = express(); 
app.use(bodyParser.urlencoded({ extended: false }));
//url/par1=val1&par2=val2 
let val1= req.body.par1;
let val2 = req.body.par2;
_x000D_
_x000D_
_x000D_

Is there a way to do repetitive tasks at intervals?

The function time.NewTicker makes a channel that sends a periodic message, and provides a way to stop it. Use it something like this (untested):

ticker := time.NewTicker(5 * time.Second)
quit := make(chan struct{})
go func() {
    for {
       select {
        case <- ticker.C:
            // do stuff
        case <- quit:
            ticker.Stop()
            return
        }
    }
 }()

You can stop the worker by closing the quit channel: close(quit).

JDK on OSX 10.7 Lion

I have just ran into the same problem after updating. The JRE that is downloaded by OSX Lion is missing JavaRuntimeSupport.jar which will work but can wreck havoc on a lot of things. If you've updated, and you had a working JDK/JRE installed prior to that, do the following in Eclipse:

1) Project > Properties > Java Build Path > Select broken JRE/JDK > Edit

2) Select "Alternate JRE"

3) Click "Installed JREs..."

4) In the window that opens, click "Search..."

If all goes well, it will find your older JRE/JDK. Mine was in this location:

/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home

Regex empty string or email

The answers above work ($ for empty), but I just tried this and it also works to just leave empty like so:

/\A(INTENSE_EMAIL_REGEX|)\z/i

Same thing in reverse order

/\A(|INTENSE_EMAIL_REGEX)\z/i

Why does 'git commit' not save my changes?

As the message says:

no changes added to commit (use "git add" and/or "git commit -a")

Git has a "staging area" where files need to be added before being committed, you can read an explanation of it here.


For your specific example, you can use:

git commit -am "save arezzo files"

(note the extra a in the flags, can also be written as git commit -a -m "message" - both do the same thing)

Alternatively, if you want to be more selective about what you add to the commit, you use the git add command to add the appropriate files to the staging area, and git status to preview what is about to be added (remembering to pay attention to the wording used).

You can also find general documentation and tutorials for how to use git on the git documentation page which will give more detail about the concept of staging/adding files.


One other thing worth knowing about is interactive staging - this allows you to add parts of a file to the staging area, so if you've made three distinct code changes (for related but different functionality), you can use interactive mode to split the changes and add/commit each part in turn. Having smaller specific commits like this can be helpful.

What are Unwind segues for and how do you use them?

Unwind segues are used to "go back" to some view controller from which, through a number of segues, you got to the "current" view controller.

Imagine you have something a MyNavController with A as its root view controller. Now you use a push segue to B. Now the navigation controller has A and B in its viewControllers array, and B is visible. Now you present C modally.

With unwind segues, you could now unwind "back" from C to B (i.e. dismissing the modally presented view controller), basically "undoing" the modal segue. You could even unwind all the way back to the root view controller A, undoing both the modal segue and the push segue.

Unwind segues make it easy to backtrack. For example, before iOS 6, the best practice for dismissing presented view controllers was to set the presenting view controller as the presented view controller’s delegate, then call your custom delegate method, which then dismisses the presentedViewController. Sound cumbersome and complicated? It was. That’s why unwind segues are nice.

Executing Javascript code "on the spot" in Chrome?

You can use bookmarklets if you want run bigger scripts in more convenient way and run them automatically by one click.

Call int() function on every list element?

In Python 2.x another approach is to use map:

numbers = map(int, numbers)

Note: in Python 3.x map returns a map object which you can convert to a list if you want:

numbers = list(map(int, numbers))

MySQL my.ini location

You can find the my.ini file in windows at this location- C:\ProgramData\MySQL\MySQL Server 5.6

the ProgramData folder is a hidden folder, so make the according setting to see that folder. And open my.ini file as an administrator to edit and then save that.

Assigning variables with dynamic names in Java

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

A rough quick and dirty example is this:

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

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

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

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

How to preventDefault on anchor tags?

/* NG CLICK PREVENT DEFAULT */

app.directive('ngClick', function () {
    return {
        link: function (scope, element, attributes) {
            element.click(function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        }
    };
});

How to get the index of an item in a list in a single step?

For simple types you can use "IndexOf" :

List<string> arr = new List<string>();
arr.Add("aaa");
arr.Add("bbb");
arr.Add("ccc");
int i = arr.IndexOf("bbb"); // RETURNS 1.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

Java: how do I initialize an array size if it's unknown?

int i,largest = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of numbers in the list");
i = scan.nextInt();
int arr[] = new int[i];
System.out.println("Enter the list of numbers:");
for(int j=0;j<i;j++){
    arr[j] = scan.nextInt();
}

The above code works well. I have taken the input of the number of elements in the list and initialized the array accordingly.

What is the difference between __init__ and __call__?

Short and sweet answers are already provided above. I wanna provide some practical implementation as compared with Java.

 class test(object):
        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c
        def __call__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c


    instance1 = test(1, 2, 3)
    print(instance1.a) #prints 1

    #scenario 1
    #creating new instance instance1
    #instance1 = test(13, 3, 4)
    #print(instance1.a) #prints 13


    #scenario 2
    #modifying the already created instance **instance1**
    instance1(13,3,4)
    print(instance1.a)#prints 13

Note: scenario 1 and scenario 2 seems same in terms of result output. But in scenario1, we again create another new instance instance1. In scenario2, we simply modify already created instance1. __call__ is beneficial here as the system doesn't need to create new instance.

Equivalent in Java

public class Test {

    public static void main(String[] args) {
        Test.TestInnerClass testInnerClass = new Test(). new TestInnerClass(1, 2, 3);
        System.out.println(testInnerClass.a);

        //creating new instance **testInnerClass**
        testInnerClass = new Test().new TestInnerClass(13, 3, 4);
        System.out.println(testInnerClass.a);

        //modifying already created instance **testInnerClass**
        testInnerClass.a = 5;
        testInnerClass.b = 14;
        testInnerClass.c = 23;

        //in python, above three lines is done by testInnerClass(5, 14, 23). For this, we must define __call__ method

    }

    class TestInnerClass /* non-static inner class */{

        private int a, b,c;

        TestInnerClass(int a, int b, int c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }
    }
}

download csv file from web api in angular js

I had to implement this recently. Thought of sharing what I had figured out;

To make it work in Safari, I had to set target: '_self',. Don't worry about filename in Safari. Looks like it's not supported as mentioned here; https://github.com/konklone/json/issues/56 (http://caniuse.com/#search=download)

The below code works fine for me in Mozilla, Chrome & Safari;

  var anchor = angular.element('<a/>');
  anchor.css({display: 'none'});
  angular.element(document.body).append(anchor);
  anchor.attr({
    href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
    target: '_self',
    download: 'data.csv'
  })[0].click();
  anchor.remove();

Inserting a value into all possible locations in a list

Coming from JavaScript, this was something I was used to having "built-in" via Array.prototype.splice(), so I made a Python function that does the same:

def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    """
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed

Strict Standards: Only variables should be assigned by reference PHP 5.4

It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Python debugging tips

print statements

  • Some people recommend a debug_print function instead of print for easy disabling
  • The pprint module is invaluable for complex structures

Can't create handler inside thread that has not called Looper.prepare()

that's what i did.

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        Toast(...);
    }
});

Visual components are "locked" to changes from outside threads. So, since the toast shows stuff on the main screen that is managed by the main thread, you need to run this code on that thread. Hope that helps:)

How to concatenate text from multiple rows into a single text string in SQL server?

I don't have access to a SQL Server at home, so I'm guess at the syntax here, but it's more or less:

DECLARE @names VARCHAR(500)

SELECT @names = @names + ' ' + Name
FROM Names

Check if an array is empty or exists

If you want to test whether the image array variable had been defined you can do it like this

if(typeof image_array === 'undefined') {
    // it is not defined yet
} else if (image_array.length > 0) {
    // you have a greater than zero length array
}

How to scroll up or down the page to an anchor using jQuery?

Description

You can do this using jQuery.offset() and jQuery.animate().

Check out the jsFiddle Demonstration.

Sample

function scrollToAnchor(aid){
    var aTag = $("a[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

scrollToAnchor('id3');

More Information

Const in JavaScript: when to use it and is it necessary?

The semantics of var and let

var and let are a statement to the machine and to other programmers:

I intend that the value of this assignment change over the course of execution. Do not rely on the eventual value of this assignment.

Implications of using var and let

var and let force other programmers to read all the intervening code from the declaration to the eventual use, and reason about the value of the assignment at that point in the program's execution.

They weaken machine reasoning for ESLint and other language services to correctly detect mistyped variable names in later assignments and scope reuse of outer scope variable names where the inner scope forgets to declare.

They also cause runtimes to run many iterations over all codepaths to detect that they are actually, in fact, constants, before they can optimise them. Although this is less of a problem than bug detection and developer comprehensibility.

When to use const

If the value of the reference does not change over the course of execution, the correct syntax to express the programmer's intent is const. For objects, changing the value of the reference means pointing to another object, as the reference is immutable, but the object is not.

"const" objects

For object references, the pointer cannot be changed to another object, but the object that is created and assigned to a const declaration is mutable. You can add or remove items from a const referenced array, and mutate property keys on a const referenced object.

To achieve immutable objects (which again, make your code easier to reason about for humans and machines), you can Object.freeze the object at declaration/assignment/creation, like this:

const Options = Object.freeze(['YES', 'NO'])

Object.freeze does have an impact on performance, but your code is probably slow for other reasons. You want to profile it.

You can also encapsulate the mutable object in a state machine and return deep copies as values (this is how Redux and React state work). See Avoiding mutable global state in Browser JS for an example of how to build this from first principles.

When var and let are a good match

let and var represent mutable state. They should, in my opinion, only be used to model actual mutable state. Things like "is the connection alive?".

These are best encapsulated in testable state machines that expose constant values that represent "the current state of the connection", which is a constant at any point in time, and what the rest of your code is actually interested in.

Programming is already hard enough with composing side-effects and transforming data. Turning every function into an untestable state machine by creating mutable state with variables just piles on the complexity.

For a more nuanced explanation, see Shun the Mutant - The case for const.

cat, grep and cut - translated to python

For Translating the command to python refer below:-

1)Alternative of cat command is open refer this. Below is the sample

>>> f = open('workfile', 'r')
>>> print f

2)Alternative of grep command refer this

3)Alternative of Cut command refer this

How to convert String into Hashmap in java

try this out :)

public static HashMap HashMapFrom(String s){
    HashMap base = new HashMap(); //result
    int dismiss = 0; //dismiss tracker
    StringBuilder tmpVal = new StringBuilder(); //each val holder
    StringBuilder tmpKey = new StringBuilder(); //each key holder

    for (String next:s.split("")){ //each of vale
        if(dismiss==0){ //if not writing value
            if (next.equals("=")) //start writing value
                dismiss=1; //update tracker
            else
                tmpKey.append(next); //writing key
        } else {
            if (next.equals("{")) //if it's value so need to dismiss
                dismiss++;
            else if (next.equals("}")) //value closed so need to focus
                dismiss--;
            else if (next.equals(",") //declaration ends
                    && dismiss==1) {
                //by the way you have to create something to correct the type
                Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
                base.put(tmpKey.toString(),ObjVal);//declaring
                tmpKey = new StringBuilder();
                tmpVal = new StringBuilder();
                dismiss--;
                continue; //next :)
            }
            tmpVal.append(next); //writing value
        }
    }
    Object objVal = object.valueOf(tmpVal.toString()); //same as here
    base.put(tmpKey.toString(), objVal); //leftovers
    return base;
}

examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}

Select all text inside EditText when it gets focus

You can try in your main.xml file:

android:selectAllOnFocus="true"

Or, in Java, use

editText.setSelectAllOnFocus(true);

Write a number with two decimal places SQL Server

If you're fine with rounding the number instead of truncating it, then it's just:

ROUND(column_name,decimals)

How to change the current URL in javascript?

Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST

function nextImage (){
url = url + 1;  
location.href='http://mywebsite.com/' + url+'.html';
}

What does it mean to have an index to scalar variable error? python

exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

Did you mean to say:

L = identity(len(l))
for i in xrange(len(l)):
    L[i][i] = exponent[i]

or even

L = diag(exponent)

?

Forward host port to docker container

You could also create an ssh tunnel.

docker-compose.yml:

---

version: '2'

services:
  kibana:
    image: "kibana:4.5.1"
    links:
      - elasticsearch
    volumes:
      - ./config/kibana:/opt/kibana/config:ro

  elasticsearch:
    build:
      context: .
      dockerfile: ./docker/Dockerfile.tunnel
    entrypoint: ssh
    command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"

docker/Dockerfile.tunnel:

FROM buildpack-deps:jessie

RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive \
    apt-get -y install ssh && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
    chmod 600 /root/.ssh/config && \
    chown $USER:$USER -R /root/.ssh

config/ssh/config:

# Elasticsearch Server
Host elasticsearch
    HostName jump.host.czerasz.com
    User czerasz
    ForwardAgent yes
    IdentityFile ~/.ssh/id_rsa

This way the elasticsearch has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.

What are NR and FNR and what does "NR==FNR" imply?

There are awk built-in variables.

NR - It gives the total number of records processed.

FNR - It gives the total number of records for each input file.

Custom pagination view in Laravel 5

Maybe it is too late, but I would like to share another custom pagination template I made that creates a first/next and last/previous links. It also hides the links when the user is in the first/last page already.

(Optional) You can also determine the interval of links (the number of links before and after the current page)

Usage example:

 @include('pagination', ['paginator' => $users])

or

@include('pagination', ['paginator' => $users, 'interval' => 5])

Here is the gist: https://gist.github.com/carloscarucce/33f6082d009c20f77499252b89c35dea

And the code:

@if (isset($paginator) && $paginator->lastPage() > 1)

    <ul class="pagination">

        <?php
        $interval = isset($interval) ? abs(intval($interval)) : 3 ;
        $from = $paginator->currentPage() - $interval;
        if($from < 1){
            $from = 1;
        }

        $to = $paginator->currentPage() + $interval;
        if($to > $paginator->lastPage()){
            $to = $paginator->lastPage();
        }
        ?>

        <!-- first/previous -->
        @if($paginator->currentPage() > 1)
            <li>
                <a href="{{ $paginator->url(1) }}" aria-label="First">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>

            <li>
                <a href="{{ $paginator->url($paginator->currentPage() - 1) }}" aria-label="Previous">
                    <span aria-hidden="true">&lsaquo;</span>
                </a>
            </li>
        @endif

        <!-- links -->
        @for($i = $from; $i <= $to; $i++)
            <?php 
            $isCurrentPage = $paginator->currentPage() == $i;
            ?>
            <li class="{{ $isCurrentPage ? 'active' : '' }}">
                <a href="{{ !$isCurrentPage ? $paginator->url($i) : '#' }}">
                    {{ $i }}
                </a>
            </li>
        @endfor

        <!-- next/last -->
        @if($paginator->currentPage() < $paginator->lastPage())
            <li>
                <a href="{{ $paginator->url($paginator->currentPage() + 1) }}" aria-label="Next">
                    <span aria-hidden="true">&rsaquo;</span>
                </a>
            </li>

            <li>
                <a href="{{ $paginator->url($paginator->lastpage()) }}" aria-label="Last">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        @endif

    </ul>

@endif

Using HTML and Local Images Within UIWebView

Using relative paths or file: paths to refer to images does not work with UIWebView. Instead you have to load the HTML into the view with the correct baseURL:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];

You can then refer to your images like this:

<img src="myimage.png">

(from uiwebview revisited)

How to use sessions in an ASP.NET MVC 4 application?

You can store any kind of data in a session using:

Session["VariableName"]=value;

This variable will last 20 mins or so.

How can I declare a two dimensional string array?

There are 2 types of multidimensional arrays in C#, called Multidimensional and Jagged.

For multidimensional you can by:

string[,] multi = new string[3, 3];

For jagged array you have to write a bit more code:

string[][] jagged = new string[3][];
            for (int i = 0; i < jagged.Length; i++)
            {
                jagged[i] = new string[3];
            }

In short jagged array is both faster and has intuitive syntax. For more information see: this Stackoverflow question

Checking whether a variable is an integer or not

All proposed answers so far seem to miss the fact that a double (floats in python are actually doubles) can also be an integer (if it has nothing after the decimal point). I use the built-in is_integer() method on doubles to check this.

Example (to do something every xth time in a for loop):

for index in range(y): 
    # do something
    if (index/x.).is_integer():
        # do something special

Edit:

You can always convert to a float before calling this method. The three possibilities:

>>> float(5).is_integer()
True
>>> float(5.1).is_integer()
False
>>> float(5.0).is_integer()
True

Otherwise, you could check if it is an int first like Agostino said:

def is_int(val):
    if type(val) == int:
        return True
    else:
        if val.is_integer():
            return True
        else:
            return False

How to implement an android:background that doesn't stretch?

You should use ImageView if you don't want it to stretch. Background images will always stretch to fit the view. You need to set it as a Drawable to force the image aspect to the object.

Otherwise, if you are sticking with the Button idea, then you will need to force the scaling in the button to prevent the image from stretching.

Code:

onCreate(Bundle bundle) {
  // Set content layout, etc up here

  // Now adjust button sizes
  Button b = (Button) findViewById(R.id.somebutton);
  int someDimension = 50; //50pixels
  b.setWidth(someDimension);
  b.setHeight(someDimension);
}

How to close TCP and UDP ports via windows command line

If you know the port that you want to free you can sort your netstat list by looking for the specif port like this:

netstat -ano | findstr :8080

Then the pid will appear at the rigth which you can kill with taskkill.

enter image description here

taskkill/pid 11704 /F

Also you may want to look at this question which is specifically for localhost, but I think it is relevant:

How can I remove the extension of a filename in a shell script?

This one covers all possibilities! (dot in the path or not; with extension or no extension):

tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*});echo $filename_noextension

Notes:

  • It gives you the filename without any extension. So there is no path in the $filename_noextension variable.
  • You end up with two unwanted variables $tmp1 and $tmp2. Make sure you are not using them in your script.

examples to test:

filename=.bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=.bashrc.txt; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=.bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/.bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/.bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=bashrc.txt; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

LEFT JOIN in LINQ to entities?

You can use this not only in entities but also store procedure or other data source:

var customer = (from cus in _billingCommonservice.BillingUnit.CustomerRepository.GetAll()  
                          join man in _billingCommonservice.BillingUnit.FunctionRepository.ManagersCustomerValue()  
                          on cus.CustomerID equals man.CustomerID  
                          // start left join  
                          into a  
                          from b in a.DefaultIfEmpty(new DJBL_uspGetAllManagerCustomer_Result() )  
                          select new { cus.MobileNo1,b.ActiveStatus });  

How to convert number of minutes to hh:mm format in TSQL?

Thanks to A Ghazal, just what I needed. Here's a slightly cleaned up version of his(her) answer:

create FUNCTION [dbo].[fnMinutesToDuration]
(
    @minutes int 
)
RETURNS nvarchar(30)

-- Based on http://stackoverflow.com/questions/17733616/how-to-convert-number-of-minutes-to-hhmm-format-in-tsql

AS

BEGIN

return rtrim(isnull(cast(nullif((@minutes / 60)
                                , 0
                               ) as varchar
                        ) + 'h '
                    ,''
                   )
            + isnull(CAST(nullif((@minutes % 60)
                                 ,0
                                ) AS VARCHAR(2)
                         ) + 'm'
                     ,''
                    )
            )

end

Create a List of primitive int?

When you use Java for Android development, it is recommended to use SparseIntArray to prevent autoboxing between int and Integer.

You can finde more information to SparseIntArray in the Android Developers documentation and a good explanation for autoboxing on Android enter link description here

Render partial from different folder (not shared)

you should try this

~/Views/Shared/parts/UMFview.ascx

place the ~/Views/ before your code

Understanding the Linux oom-killer's logs

Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.

Short answer to your question: Yes there are other stuff included than whats in the list.

What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.

From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.

Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.

Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.

Checking whether the pip is installed?

$ which pip

or

 $ pip -V 

execute this command into your terminal. It should display the location of executable file eg. /usr/local/bin/pip and the second command will display the version if the pip is installed correctly.

How to get the part of a file after the first line that matches a regular expression?

If I understand your question correctly you do want the lines after TERMINATE, not including the TERMINATE-line. awk can do this in a simple way:

awk '{if(found) print} /TERMINATE/{found=1}' your_file

Explanation:

  1. Although not best practice you could rely on the fact that all vars defaults to 0 or the empty string if not defined. So the first expression (if(found) print) will not print anything to start off with.
  2. After the printing is done we check if the this is the starter-line (that should not be included).

This will print all lines after the TERMINATE-line.


Generalization:

  • You have a file with start- and end-lines and you want the lines between those lines excluding the start- and end-lines.
  • start- and end-lines could be defined by a regular expression matching the line.

Example:

$ cat ex_file.txt 
not this line
second line
START
A good line to include
And this line
Yep
END
Nope more
...
never ever
$ awk '/END/{found=0} {if(found) print} /START/{found=1}' ex_file.txt 
A good line to include
And this line
Yep
$

Explanation:

  1. If the end-line is found no printing should be done. Note that this check is done before the actual printing to exclude the end-line from the result.
  2. Print the current line if found is set.
  3. If the start-line is found then set found=1 so that the following lines are printed. Note that this check is done after the actual printing to exclude the start-line from the result.

Notes:

  • The code rely on the fact that all awk-vars defaults to 0 or the empty string if not defined. This is valid but may not be best practice so you could add a BEGIN{found=0} to the start of the awk-expression.
  • If multiple start-end-blocks is found they are all printed.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

(9.61 + "").replace('.',':')

Or if your 9.61 is already a string:

"9.61".replace('.',':')

Assign static IP to Docker container

This works for me.

Create a network with docker network create --subnet=172.17.0.0/16 selnet

Run docker image docker run --net selnet --ip 172.18.0.2 hub

At first, I got

docker: Error response from daemon: Invalid address 172.17.0.2: It does not belong to any of this network's subnets.
ERRO[0000] error waiting for container: context canceled

Solution: Increased the 2nd quadruple of the IP [.18. instead of .17.]

Cannot read property 'length' of null (javascript)

I tried this:

if(capital !== null){ 
//Capital has something 
}

in a "using" block is a SqlConnection closed on return or exception?

Yes to both questions. The using statement gets compiled into a try/finally block

using (SqlConnection connection = new SqlConnection(connectionString))
{
}

is the same as

SqlConnection connection = null;
try
{
    connection = new SqlConnection(connectionString);
}
finally
{
   if(connection != null)
        ((IDisposable)connection).Dispose();
}

Edit: Fixing the cast to Disposable http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Why would $_FILES be empty when uploading files to PHP?

I ran into the same issue and found that it was my IDE was part of the issue. I was launching the debugger directly from the IDE (PHPStorm) instead of just using the browser directly. The IDE spawned URL was like this:

"...localhost:63342/CB_Upload/index.php?_ijt=j2hcbacqepj87bvg66ncuohvne"

and just using:

"...localhost/CB_Upload/index.php"

worked just fine. My set up is PC / Windows 10 / WAMPSERVER 3.0.6 64bit

Storing and Retrieving ArrayList values from hashmap

for (Map.Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
 System.out.println( entry.getKey());     
 System.out.println( entry.getValue());//Returns the list of values
}

Using the last-child selector

If you are floating the elements you can reverse the order

i.e. float: right; instead of float: left;

And then use this method to select the first-child of a class.

/* 1: Apply style to ALL instances */
#header .some-class {
  padding-right: 0;
}
/* 2: Remove style from ALL instances except FIRST instance */
#header .some-class~.some-class {
  padding-right: 20px;
}

This is actually applying the class to the LAST instance only because it's now in reversed order.

Here is a working example for you:

<!doctype html>
<head><title>CSS Test</title>
<style type="text/css">
.some-class { margin: 0; padding: 0 20px; list-style-type: square; }
.lfloat { float: left; display: block; }
.rfloat { float: right; display: block; }
/* apply style to last instance only */
#header .some-class {
  border: 1px solid red;
  padding-right: 0;
}
#header .some-class~.some-class {
  border: 0;
  padding-right: 20px;
}
</style>
</head>
<body>
<div id="header">
  <img src="some_image" title="Logo" class="lfloat no-border"/>
  <ul class="some-class rfloat">
    <li>List 1-1</li>
    <li>List 1-2</li>
    <li>List 1-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 2-1</li>
    <li>List 2-2</li>
    <li>List 2-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 3-1</li>
    <li>List 3-2</li>
    <li>List 3-3</li>
  </ul>
  <img src="some_other_img" title="Icon" class="rfloat no-border"/>
</div>
</body>
</html>

Get a worksheet name using Excel VBA

You can use below code to get the Active Sheet name and change it to yours preferred name.

Sub ChangeSheetName()

Dim shName As String
Dim currentName As String
currentName = ActiveSheet.Name
shName = InputBox("What name you want to give for your sheet")
ThisWorkbook.Sheets(currentName).Name = shName

End Sub

Shift column in pandas dataframe up by one?

df.gdp = df.gdp.shift(-1) ## shift up
df.gdp.drop(df.gdp.shape[0] - 1,inplace = True) ## removing the last row

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

A slightly more efficient version of the bytes2String method is

private static final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String byteArray2Hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

Angular 2 - NgFor using numbers instead collections

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill().map((x,i)=>i); // [0,1,2,3,4]
    this.numbers = Array(5).fill(4); // [4,4,4,4,4]
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@Component({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@Component({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Can I redirect the stdout in python into some sort of string buffer?

There is contextlib.redirect_stdout() function in Python 3.4:

import io
from contextlib import redirect_stdout

with io.StringIO() as buf, redirect_stdout(buf):
    print('redirected')
    output = buf.getvalue()

Here's code example that shows how to implement it on older Python versions.

Fastest way to set all values of an array?

If you have another array of char, char[] b and you want to replace c with b, you can use c=b.clone();.

Angularjs on page load call function

you can use it directly with $scope instance

     $scope.init=function()
        {
            console.log("entered");
            data={};
            /*do whatever you want such as initialising scope variable,
              using $http instance etcc..*/
        }
       //simple call init function on controller
       $scope.init();

How to find a value in an array of objects in JavaScript?

jQuery has a built-in method jQuery.grep that works similarly to the ES5 filter function from @adamse's Answer and should work fine on older browsers.

Using adamse's example:

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

you can do the following

jQuery.grep(peoples, function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

Removing u in list

Please Use map() python function.

Input: In case of list of values

index = [u'CARBO1004' u'CARBO1006' u'CARBO1008' u'CARBO1009' u'CARBO1020']

encoded_string = map(str, index)

Output: ['CARBO1004', 'CARBO1006', 'CARBO1008', 'CARBO1009', 'CARBO1020']

For a Single string input:

index = u'CARBO1004'
# Use Any one of the encoding scheme.
index.encode("utf-8")  # To utf-8 encoding scheme
index.encode('ascii', 'ignore')  # To Ignore Encoding Errors and set to default scheme

Output: 'CARBO1004'

AngularJS - Find Element with attribute

You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

So, for this HTML:

<div ng-controller='MyCtrl'>
    <div>
        <div name='foo' class='myElementClass'>this one</div>
    </div>
</div>

This AngularJS code should work:

angular.module('MyClient').controller('MyCtrl', [
    '$scope',
    '$element',
    '$log',
    function ($scope, $element, $log) {

        // Find the element by its class attribute, within your controller's scope
        var myElements = $element.find('.myElementClass');

        // myElements is now an array of jQuery DOM elements

        if (myElements.length == 0) {
            // Not found. Are you sure you've included the full jQuery?
        } else {
            // There should only be one, and it will be element 0
            $log.debug(myElements[0].name); // "foo"
        }

    }
]);

Forbidden: You don't have permission to access / on this server, WAMP Error

Adding Allow from All didn't worked for me. Then I tried this and it worked.

OS: Windows 8.1
Wamp : 2.5

I added this in the file C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/wamp/www/"
    ServerName localhost
    ServerAlias localhost
    ErrorLog "logs/localhost-error.log"
    CustomLog "logs/localhost-access.log" common
</VirtualHost>

Change route params without reloading in Angular 2

As of RC6 you can do the following to change URL without change state and thereby keeping your route history

    import {OnInit} from '@angular/core';

    import {Location} from '@angular/common'; 
    // If you dont import this angular will import the wrong "Location"

    @Component({
        selector: 'example-component',
        templateUrl: 'xxx.html'
    })
    export class ExampleComponent implements OnInit {
        
        constructor( private location: Location )
        {}

        ngOnInit() {    
            this.location.replaceState("/some/newstate/");
        }
    }

How to drop all stored procedures at once in SQL Server database?

  1. Click on Stored Procedures Tab
  2. Press f7 to Display All Stored Procedures
  3. Select All Procedure By Ctrl + A except System Table
  4. Press Delete button and Click OK.

You can Delete Table as well as View in same manner.

How can I style a PHP echo text?

You cannot style a variable such as $ip['countryName']

You can only style elements like p,div, etc, or classes and ids.

If you want to style $ip['countryName'] there are several ways.

You can echo it within an element:

echo '<p id="style">'.$ip['countryName'].'</p>';
echo '<span id="style">'.$ip['countryName'].'</span>';
echo '<div id="style">'.$ip['countryName'].'</div>';

If you want to style both the variables the same style, then set a class like:

echo '<p class="style">'.$ip['cityName'].'</p>';
echo '<p class="style">'.$ip['countryName'].'</p>';

You could also embed the variables within your actual html rather than echoing them out within the code.

$city = $ip['cityName'];  
$country = $ip['countryName'];
?>
<div class="style"><?php echo $city ?></div>
<div class="style"><?php echo $country?></div>

jackson deserialization json to java-objects

 JsonNode node = mapper.readValue("[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"},"

 System.out.println("id : "+node.findValues("id").get(0).asText());

this also done the trick.

How to revert the last migration?

there is a good library to use its called djagno-nomad, although not directly related to the question asked, thought of sharing this,

scenario: most of the time when switching to project, we feel like it should revert our changes that we did on this current branch, that's what exactly this library does, checkout below

https://pypi.org/project/django-nomad/

Can you get a Windows (AD) username in PHP?

You can say getenv('USERNAME')

How do I enable C++11 in gcc?

If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.

{
    "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

    "variants":
    [
        {
            "name": "Run",
            "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
        }
    ]
}

What is __declspec and when do I need to use it?

I know it's been eight years but I wanted to share this piece of code found in MRuby that shows how __declspec() can bee used at the same level as the export keyword.

/** Declare a public MRuby API function. */
#if defined(MRB_BUILD_AS_DLL)
#if defined(MRB_CORE) || defined(MRB_LIB)
# define MRB_API __declspec(dllexport)
#else
# define MRB_API __declspec(dllimport)
#endif
#else
# define MRB_API extern
#endif

Dynamically access object property using variable

For anyone looking to set the value of a nested variable, here is how to do it:

const _ = require('lodash'); //import lodash module

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4

Documentation: https://lodash.com/docs/4.17.15#set

Also, documentation if you want to get a value: https://lodash.com/docs/4.17.15#get

how to run the command mvn eclipse:eclipse

Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.

enter image description here

TypeError: expected string or buffer

readlines() will return a list of all the lines in the file, so lines is a list. You probably want something like this:

for line in f.readlines(): # Iterates through every line and looks for a match
#or
#for line in f:
    match = re.findall('[A-Z]+', line)
    print match

Or, if the file isn't too large you can grab it as as single string:

lines = f.read() # Warning: reads the FULL FILE into memory. This can be bad.
match = re.findall('[A-Z]+', lines)
print match

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

Why am I getting a FileNotFoundError?

If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.

You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command

$ python script.py

In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.

In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

<div class="col d-none d-sm-block">
    <span class="vcard">
        …
    </span>
</div>
<div class="col d-none d-xl-block">
    <div class="d-none d-md-block">
                …
    </div>
    <div class="d-none d-sm-block">
                …
    </div>
</div>

class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

<span class="d-none d-sm-inline">hidden-xs</span>

<span class="d-none d-sm-inline-block">hidden-xs</span>

An example of Bootstrap 4 responsive utilities:

<div class="d-none d-sm-block"> hidden-xs           
  <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
    <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
      <div class="d-none d-xl-block"> visible-xl </div>
    </div>
  </div>
</div>

<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>

<div class="d-xl-none"> hidden-xl (visible-lg and down)         
  <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
    <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
      <div class="d-sm-none"> visible-xs </div>
    </div>
  </div>
</div>

Documentation

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

You can view which modules (compiled in) are available via terminal through php -m

Basic authentication for REST API using spring restTemplate

Taken from the example on this site, I think this would be the most natural way of doing it, by filling in the header value and passing the header to the template.

This is to fill in the header Authorization:

String plainCreds = "willie:p@ssword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

And this is to pass the header to the REST template:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();

How to loop in excel without VBA or macros?

Add more columns when you have variable loops that repeat at different rates. I'm not sure explicitly what you're trying to do, but I think I've done something that could apply.

Creating a single loop in Excel is prettty simple. It actually does the work for you. Try this on a new workbook

  1. Enter "1" in A1
  2. Enter "=A1+1" in A2

A3 will automatically be "=A2+1" as you drag down. The first steps don't have to be that explicit. Excel will automatically recognize the pattern and count if you just put "2" in A2, but if we want B1-B5 to be "100" and B5-B10 to be "200" (counting up the same way) you can see why knowing how to do it explicitly matters. In this scenario, You just enter:

  1. "100" in B1, drag through to B5 and
  2. "=B1+100" in B6

B7 will automatically be "=B2+100" etc. as you drag down, so basically it increases every 5 rows infinitely. To make a loop of numbers 1-5 in column A:

  1. Enter "=A1" in cell A6. As you drag down, it will automatically be "=A2" in cell A7, etc. because of the way that Excel does things.

So, now we have column A repeating numbers 1-5 while column B is increasing by 100 every 5 cells.You could make column B repeat, for instance, the numbers 100-900 in using the same method as you did with column A as a way to produce, for instance, each possible combination with multiple variables. Drag down the columns and they'll do it infinitely. I'm not explicitly addressing the scenario given, but if you follow the steps and understand them, the concept should give you an answer to the problem that involves adding more columns and concactinating or using them as your variables.

Simple way to find if two different lists contain exactly the same elements?

I posted a bunch of stuff in comments I think it warrants its own answer.

As everyone says here, using equals() depends on the order. If you don't care about order, you have 3 options.

Option 1

Use containsAll(). This option is not ideal, in my opinion, because it offers worst case performance, O(n^2).

Option 2

There are two variations to this:

2a) If you don't care about maintaining the order ofyour lists... use Collections.sort() on both list. Then use the equals(). This is O(nlogn), because you do two sorts, and then an O(n) comparison.

2b) If you need to maintain the lists' order, you can copy both lists first. THEN you can use solution 2a on both the copied lists. However this might be unattractive if copying is very expensive.

This leads to:

Option 3

If your requirements are the same as part 2b, but copying is too expensive. You can use a TreeSet to do the sorting for you. Dump each list into its own TreeSet. It will be sorted in the set, and the original lists will remain intact. Then perform an equals() comparison on both TreeSets. The TreeSetss can be built in O(nlogn) time, and the equals() is O(n).

Take your pick :-).

EDIT: I almost forgot the same caveat that Laurence Gonsalves points out. The TreeSet implementation will eliminate duplicates. If you care about duplicates, you will need some sort of sorted multiset.

How to navigate through a vector using iterators? (C++)

Typically, iterators are used to access elements of a container in linear fashion; however, with "random access iterators", it is possible to access any element in the same fashion as operator[].

To access arbitrary elements in a vector vec, you can use the following:

vec.begin()                  // 1st
vec.begin()+1                // 2nd
// ...
vec.begin()+(i-1)            // ith
// ...
vec.begin()+(vec.size()-1)   // last

The following is an example of a typical access pattern (earlier versions of C++):

int sum = 0;
using Iter = std::vector<int>::const_iterator;
for (Iter it = vec.begin(); it!=vec.end(); ++it) {
    sum += *it;
}

The advantage of using iterator is that you can apply the same pattern with other containers:

sum = 0;
for (Iter it = lst.begin(); it!=lst.end(); ++it) {
    sum += *it;
}

For this reason, it is really easy to create template code that will work the same regardless of the container type. Another advantage of iterators is that it doesn't assume the data is resident in memory; for example, one could create a forward iterator that can read data from an input stream, or that simply generates data on the fly (e.g. a range or random number generator).

Another option using std::for_each and lambdas:

sum = 0;
std::for_each(vec.begin(), vec.end(), [&sum](int i) { sum += i; });

Since C++11 you can use auto to avoid specifying a very long, complicated type name of the iterator as seen before (or even more complex):

sum = 0;
for (auto it = vec.begin(); it!=vec.end(); ++it) {
    sum += *it;
}

And, in addition, there is a simpler for-each variant:

sum = 0;
for (auto value : vec) {
    sum += value;
}

And finally there is also std::accumulate where you have to be careful whether you are adding integer or floating point numbers.

Shorter syntax for casting from a List<X> to a List<Y>?

To add to Sweko's point:

The reason why the cast

var listOfX = new List<X>();
ListOf<Y> ys = (List<Y>)listOfX; // Compile error: Cannot implicitly cast X to Y

is not possible is because the List<T> is invariant in the Type T and thus it doesn't matter whether X derives from Y) - this is because List<T> is defined as:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T> ... // Other interfaces

(Note that in this declaration, type T here has no additional variance modifiers)

However, if mutable collections are not required in your design, an upcast on many of the immutable collections, is possible, e.g. provided that Giraffe derives from Animal:

IEnumerable<Animal> animals = giraffes;

This is because IEnumerable<T> supports covariance in T - this makes sense given that IEnumerable implies that the collection cannot be changed, since it has no support for methods to Add or Remove elements from the collection. Note the out keyword in the declaration of IEnumerable<T>:

public interface IEnumerable<out T> : IEnumerable

(Here's further explanation for the reason why mutable collections like List cannot support covariance, whereas immutable iterators and collections can.)

Casting with .Cast<T>()

As others have mentioned, .Cast<T>() can be applied to a collection to project a new collection of elements casted to T, however doing so will throw an InvalidCastException if the cast on one or more elements is not possible (which would be the same behaviour as doing the explicit cast in the OP's foreach loop).

Filtering and Casting with OfType<T>()

If the input list contains elements of different, incompatable types, the potential InvalidCastException can be avoided by using .OfType<T>() instead of .Cast<T>(). (.OfType<>() checks to see whether an element can be converted to the target type, before attempting the conversion, and filters out incompatable types.)

foreach

Also note that if the OP had written this instead: (note the explicit Y y in the foreach)

List<Y> ListOfY = new List<Y>();

foreach(Y y in ListOfX)
{
    ListOfY.Add(y);
}

that the casting will also be attempted. However, if no cast is possible, an InvalidCastException will result.

Examples

For example, given the simple (C#6) class hierarchy:

public abstract class Animal
{
    public string Name { get;  }
    protected Animal(string name) { Name = name; }
}

public class Elephant :  Animal
{
    public Elephant(string name) : base(name){}
}

public class Zebra : Animal
{
    public Zebra(string name)  : base(name) { }
}

When working with a collection of mixed types:

var mixedAnimals = new Animal[]
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

foreach(Animal animal in mixedAnimals)
{
     // Fails for Zed - `InvalidCastException - cannot cast from Zebra to Elephant`
     castedAnimals.Add((Elephant)animal);
}

var castedAnimals = mixedAnimals.Cast<Elephant>()
    // Also fails for Zed with `InvalidCastException
    .ToList();

Whereas:

var castedAnimals = mixedAnimals.OfType<Elephant>()
    .ToList();
// Ellie

filters out only the Elephants - i.e. Zebras are eliminated.

Re: Implicit cast operators

Without dynamic, user defined conversion operators are only used at compile-time*, so even if a conversion operator between say Zebra and Elephant was made available, the above run time behaviour of the approaches to conversion wouldn't change.

If we add a conversion operator to convert a Zebra to an Elephant:

public class Zebra : Animal
{
    public Zebra(string name) : base(name) { }
    public static implicit operator Elephant(Zebra z)
    {
        return new Elephant(z.Name);
    }
}

Instead, given the above conversion operator, the compiler will be able to change the type of the below array from Animal[] to Elephant[], given that the Zebras can be now converted to a homogeneous collection of Elephants:

var compilerInferredAnimals = new []
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

Using Implicit Conversion Operators at run time

*As mentioned by Eric, the conversion operator can however be accessed at run time by resorting to dynamic:

var mixedAnimals = new Animal[] // i.e. Polymorphic collection
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

foreach (dynamic animal in mixedAnimals)
{
    castedAnimals.Add(animal);
}
// Returns Zed, Ellie

Attaching click to anchor tag in angular

I have examined all the above answer's, We just need to implement two things to work it as expected.

Step - 1: Add the (click) event in the anchor tag in the HTML page and remove the href=" " as its explicitly for navigating to external links, Instead use routerLink = " " which helps in navigating views.

<ul>
  <li><a routerLink="" (click)="hitAnchor1($event)"><p>Click One</p></a></li>
  <li><a routerLink="" (click)="hitAnchor2($event)"><p>Click Two</p></a></li>
</ul>

Step - 2: Call the above function to attach the click event to anchor tags (coming from ajax) in the .ts file,

  hitAnchor1(e){
      console.log("Events", e);
      alert("You have clicked the anchor-1 tag");
   }
  hitAnchor2(e){
      console.log("Events", e);
      alert("You have clicked the anchor-2 tag");
   }

That's all. It work's as expected. I created the example below, You can have a look:-

https://stackblitz.com/edit/angular-yn6q6t

Extracting extension from filename in Python

Surprised this wasn't mentioned yet:

import os
fn = '/some/path/a.tar.gz'

basename = os.path.basename(fn)  # os independent
Out[] a.tar.gz

base = basename.split('.')[0]
Out[] a

ext = '.'.join(basename.split('.')[1:])   # <-- main part

# if you want a leading '.', and if no result `None`:
ext = '.' + ext if ext else None
Out[] .tar.gz

Benefits:

  • Works as expected for anything I can think of
  • No modules
  • No regex
  • Cross-platform
  • Easily extendible (e.g. no leading dots for extension, only last part of extension)

As function:

def get_extension(filename):
    basename = os.path.basename(filename)  # os independent
    ext = '.'.join(basename.split('.')[1:])
    return '.' + ext if ext else None

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

A bit similar to @bpile answer, my case was a my.cnf entry setting collation-server = utf8_general_ci. After I realized that (and after trying everything above), I forcefully switched my database to utf8_general_ci instead of utf8_unicode_ci and that was it:

ALTER DATABASE `db` CHARACTER SET utf8 COLLATE utf8_general_ci;

Can I pass parameters in computed properties in Vue.Js

Yes methods are there for using params. Like answers stated above, in your example it's best to use methods since execution is very light.

Only for reference, in a situation where the method is complex and cost is high, you can cache the results like so:

data() {
    return {
        fullNameCache:{}
    };
}

methods: {
    fullName(salut) {
        if (!this.fullNameCache[salut]) {
            this.fullNameCache[salut] = salut + ' ' + this.firstName + ' ' + this.lastName;
        }
        return this.fullNameCache[salut];
    }
}

note: When using this, watchout for memory if dealing with thousands

html "data-" attribute as javascript parameter

JS:

function fun(obj) {
    var uid= $(obj).data('uid');
    var name= $(obj).data('name');
    var value= $(obj).data('value');
}

What's the difference between text/xml vs application/xml for webservice response

This is an old question, but one that is frequently visited and clear recommendations are now available from RFC 7303 which obsoletes RFC3023. In a nutshell (section 9.2):

The registration information for text/xml is in all respects the same
as that given for application/xml above (Section 9.1), except that
the "Type name" is "text".

How to make RatingBar to show five stars

You can add default rating of five stars in side the xml layout

android:rating="5"

Edit:

<RatingBar
        android:id="@+id/rb_vvm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="@dimen/space2"
        android:layout_marginTop="@dimen/space1"
        style="@style/RatingBar"
        android:numStars="5"
        android:stepSize="1"
        android:rating="5" />

Xamarin.Forms ListView: Set the highlight color of a tapped item

It looks like there is actually a cross-platform way to do this that works on both iOS and Android (not sure about Windows). It uses only binding and does not require custom renderers (which seems rare). This is a mash-up of lots of googling, so thanks to anyone who I may have borrowed from...

I am assuming ViewCells, but this should work for Text or Image cells as well. I am only including the relevant code here beyond the typical text, image, etc.

On your page do something like this:

MyModel model1 = new MyModel();
MyModel model2 = new MyModel();

ListView list = new ListView
{
    ItemsSource = new List<MyModel> { model1, model2 };
    ItemTemplate = new DataTemplate( typeof(MyCell) )
};

Your custom Model might look something like this:

public class MyModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private Color _backgroundColor;

    public Color BackgroundColor 
    { 
        get { return _backgroundColor; } 
        set 
        { 
            _backgroundColor = value; 

            if ( PropertyChanged != null )
            {
                PropertyChanged( this, new PropertyChangedEventArgs( "BackgroundColor" ) );
            }
        }
    }

    public void SetColors( bool isSelected )
    {
        if ( isSelected )
        {
            BackgroundColor = Color.FromRgb( 0.20, 0.20, 1.0 );
        }
        else
        {
            BackgroundColor = Color.FromRgb( 0.95, 0.95, 0.95 ); 
        }
    }
}

Then for your ItemTemplate you need a custom cell class something like this:

public class MyCell : ViewCell
{
    public MyCell() : base()
    {
        RelativeLayout layout = new RelativeLayout();
        layout.SetBinding( Layout.BackgroundColorProperty, new Binding( "BackgroundColor" ) );

        View = layout;
    }
}

Then in your ItemSelected event handler, do the following. Note that 'selected' is an instance of MyModel used to track the currently selected item. I am only showing background color here, but I also use this technique to reverse highlight the text and detail text colors.

private void ItemSelected( object sender, ItemTappedEventArgs args )
{
    // Deselect previous
    if ( selected != null )
    {
        selected.SetColors( false );
    }

    // Select new
    selected = (list.SelectedItem as MyModel);
    selected.SetColors( true );
}

Refresh a page using PHP

You sure can refresh a page periodically using PHP:

<?php
    header("refresh: 3;");
?>

This will refresh the page every three seconds.

How to compare the contents of two string objects in PowerShell

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

Using SVG as background image

You have set a fixed width and height in your svg tag. This is probably the root of your problem. Try not removing those and set the width and height (if needed) using CSS instead.

What's the environment variable for the path to the desktop?

EDIT: Use the accepted answer, this will not work if the default location isn't being used, for example: The user moved the desktop to another drive like D:\Desktop


At least on Windows XP, Vista and 7 you can use the "%UserProfile%\Desktop" safely.

Windows XP en-US it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows XP pt-BR it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows 7 en-US it will expand to "C:\Users\YourName\Desktop"
Windows 7 pt-BR it will expand to "C:\Usuarios\YourName\Desktop"

On XP you can't use this to others folders exept for Desktop My documents turning to Meus Documentos and Local Settings to Configuracoes locais Personaly I thinks this is a bad thing when projecting a OS.

How to enumerate an enum with String type?

Here's my suggested approach. It's not completely satisfactory (I'm very new to Swift and OOP!) but maybe someone can refine it. The idea is to have each enum provide its own range information as .first and .last properties. It adds just two lines of code to each enum: still a bit hard-coded, but at least it's not duplicating the whole set. It does require modifying the Suit enum to be an Int like the Rank enum is, instead of untyped.

Rather than echo the whole solution, here's the code I added to the . enum, somewhere after the case statements (Suit enum is similar):

var first: Int { return Ace.toRaw() }
var last: Int { return King.toRaw() }

and the loop I used to build the deck as an array of String. (The problem definition did not state how the deck was to be structured.)

func createDeck() -> [String] {
    var deck: [String] = []
    var card: String
    for r in Rank.Ace.first...Rank.Ace.last {
        for s in Suit.Hearts.first...Suit.Hearts.last {
            card = Rank.simpleDescription( Rank.fromRaw(r)!)() + " of " + Suit.simpleDescription( Suit.fromRaw(s)!)()
           deck.append( card)
       }
    }
    return deck
}

It's unsatisfactory because the properties are associated to an element rather than to the enum. But it does add clarity to the 'for' loops. I'd like it to say Rank.first instead of Rank.Ace.first. It works (with any element), but it's ugly. Can someone show how to elevate that to the enum level?

And to make it work, I lifted the createDeck method out of the Card struct. I could not figure out how to get a [String] array returned from that struct, and that seems a bad place to put such a method anyway.

How to get MAC address of your machine using a C program?

I have just write one and test it on gentoo in virtualbox.

// get_mac.c
#include <stdio.h>    //printf
#include <string.h>   //strncpy
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>   //ifreq
#include <unistd.h>   //close

int main()
{
    int fd;
    struct ifreq ifr;
    char *iface = "enp0s3";
    unsigned char *mac = NULL;

    memset(&ifr, 0, sizeof(ifr));

    fd = socket(AF_INET, SOCK_DGRAM, 0);

    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);

    if (0 == ioctl(fd, SIOCGIFHWADDR, &ifr)) {
        mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;

        //display mac address
        printf("Mac : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    }

    close(fd);

    return 0;
}

Keras input explanation: input_shape, units, batch_size, dim, etc

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

In Keras LSTM, it refers to the total Time Steps

The term has been very confusing, is correct and we live in a very confusing world!!

I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.

RecyclerView inside ScrollView is not working

This does the trick:

recyclerView.setNestedScrollingEnabled(false);

How can I pass a parameter in Action?

If you know what parameter you want to pass, take a Action<T> for the type. Example:

void LoopMethod (Action<int> code, int count) {
     for (int i = 0; i < count; i++) {
         code(i);
     }
}

If you want the parameter to be passed to your method, make the method generic:

void LoopMethod<T> (Action<T> code, int count, T paramater) {
     for (int i = 0; i < count; i++) {
         code(paramater);
     }
}

And the caller code:

Action<string> s = Console.WriteLine;
LoopMethod(s, 10, "Hello World");

Update. Your code should look like:

private void Include(IList<string> includes, Action<string> action)
{
    if (includes != null)
    {
         foreach (var include in includes)
             action(include);
    }
}

public void test()
{
    Action<string> dg = (s) => {
        _context.Cars.Include(s);
    };
    this.Include(includes, dg);
}

Reloading submodules in IPython

IPython offers dreload() to recursively reload all submodules. Personally, I prefer to use the %run() magic command (though it does not perform a deep reload, as pointed out by John Salvatier in the comments).

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

In Visual Studio Code How do I merge between two local branches?

Actually you can do with VS Code the following:

Merge Local Branch with VS Code

jQuery Force set src attribute for iframe

Use attr

$('#abc_frame').attr('src', url)

This way you can get and set every HTML tag attribute. Note that there is also .prop(). See .prop() vs .attr() about the differences. Short version: .attr() is used for attributes as they are written in HTML source code and .prop() is for all that JavaScript attached to the DOM element.

Assign variable in if condition statement, good practice or not?

It's not good practice. You soon will get confused about it. It looks similiar to a common error: misuse "=" and "==" operators.

You should break it into 2 lines of codes. It not only helps to make the code clearer, but also easy to refactor in the future. Imagine that you change the IF condition? You may accidently remove the line and your variable no longer get the value assigned to it.

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

Error QApplication: no such file or directory

You can change build versiyon.For example i tried QT 5.6.1 but it didn't work.Than i tried QT 5.7.0 .So it worked , Good Luck! :)

How to automatically generate unique id in SQL like UID12345678?

The only viable solution in my opinion is to use

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.tblUsers
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into tblUsers without specifying values for ID or UserID:

INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and UserID will contain values like UID00000001, UID00000002,...... and so on - automatically, safely, reliably, no duplicates.

Update: the column UserID is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:

enter image description here

Adding Git-Bash to the new Windows Terminal

That's how I've added mine in profiles json table,

{
    "guid": "{00000000-0000-0000-ba54-000000000002}",
    "name": "Git",
    "commandline": "C:/Program Files/Git/bin/bash.exe --login",
    "icon": "%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico",
    "startingDirectory": "%USERPROFILE%",
    "hidden": false
}

How does Java handle integer underflows and overflows and how would you check for it?

It doesn't do anything -- the under/overflow just happens.

A "-1" that is the result of a computation that overflowed is no different from the "-1" that resulted from any other information. So you can't tell via some status or by inspecting just a value whether it's overflowed.

But you can be smart about your computations in order to avoid overflow, if it matters, or at least know when it will happen. What's your situation?

Set selected option of select box

Some cases may be

$('#gate option[value='+data.Gateway2+']').attr('selected', true);

Apply CSS Style to child elements

div.test td, div.test caption, div.test th 

works for me.

The child selector > does not work in IE6.

Best PHP IDE for Mac? (Preferably free!)

Komodo is wonderful, and it runs on OS X; they have a free version, Komodo Edit.

UPDATE from 2015: I've switched to PHPStorm from Jetbrains, the same folks that built IntelliJ IDEA and Resharper. It's better. Not just better. It's well worth the money.

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

A single listening port can accept more than one connection simultaneously.

There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.

Each TCP/IP packet has basically four fields for addressing. These are:

source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>

Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).

If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.

However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.

So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.

The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.

PDO's query vs execute

Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.

In one case, I found that query worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.

I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query could be faster than prepare & execute because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.

Given a couple rare conditions:

  1. If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.

  2. If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.

  3. PDO::lastInsertId is not supported by the Microsoft ODBC driver.

Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:

To start, I've created a basic table in Microsoft SQL Server

CREATE TABLE performancetest (
    sid INT IDENTITY PRIMARY KEY,
    id INT,
    val VARCHAR(100)
);

And now a basic timed test for performance metrics.

$logs = [];

$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
    $start = microtime(true);
    $i = 0;
    while ($i < $count) {
        $sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
        if ($type === 'query') {
            $smt = $pdo->query($sql);
        } else {
            $smt = $pdo->prepare($sql);
            $smt ->execute();
        }
        $sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
        $i++;
    }
    $total = (microtime(true) - $start);
    $logs[$type] []= $total;
    echo "$total $type\n";
};

$trials = 15;
$i = 0;
while ($i < $trials) {
    if (random_int(0,1) === 0) {
        $test('query');
    } else {
        $test('prepare');
    }
    $i++;
}

foreach ($logs as $type => $log) {
    $total = 0;
    foreach ($log as $record) {
        $total += $record;
    }
    $count = count($log);
    echo "($count) $type Average: ".$total/$count.PHP_EOL;
}

I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query than prepare/execute

5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769

I'm curious to see how this test compares in other environments, like MySQL.

Can Flask have optional URL parameters?

You can write as you show in example, but than you get build-error.

For fix this:

  1. print app.url_map () in you root .py
  2. you see something like:

<Rule '/<userId>/<username>' (HEAD, POST, OPTIONS, GET) -> user.show_0>

and

<Rule '/<userId>' (HEAD, POST, OPTIONS, GET) -> .show_1>

  1. than in template you can {{ url_for('.show_0', args) }} and {{ url_for('.show_1', args) }}

How to avoid precompiled headers

Right click project solution

Properties -> Configuration Properties -> C/C++ -> Precompiled Headers

  1. Click on "Precompiled Headers" change to "Not Using Precompiled Headers".

  2. Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.

  3. Then you can feel free to delete the pch./stdafx. files in your project

How to increase timeout for a single test case in mocha

From command line:

mocha -t 100000 test.js

C++ Convert string (or char*) to wstring (or wchar_t*)

If you have QT and if you are lazy to implement a function and stuff you can use

std::string str;
QString(str).toStdWString()

Load content with ajax in bootstrap modal

Easily done in Bootstrap 3 like so:

<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>

How to check if MySQL returns null/empty?

Also, don't forget the === operator when you're working with numbers that could mean null or 0 or return some form of false or null that isn't what you're looking for.

Best way to check for "empty or null value"

If database having large number of records then null check can take more time you can use null check in different ways like : 1) where columnname is null 2) where not exists() 3) WHERE (case when columnname is null then true end)

Relay access denied on sending mail, Other domain outside of network

If it is giving you relay access denied when you are trying to send an email from outside your network to a domain that your server is not authoritative for then it means your receive connector does not grant you the permissions for sending/relaying. Most likely what you need to do is to authenticate to the server to be granted the permissions for relaying but that does depend upon the configuration of your receive connector. In Exchange 2007/2010/2013 you would need to enable ExchangeUsers permission group as well as an authentication mechanism such as Basic authentication.

Once you're sure your receive connector is configured make sure your email client is configured for authentication as well for the SMTP server. It depends upon your server setup but normally for Exchange you would configure the username by itself, no need for the domain to appended or prefixed to it.

To test things out with authentication via telnet you can go over my post here for directions: https://jefferyland.wordpress.com/2013/05/28/essential-exchange-troubleshooting-send-email-via-telnet/

Detect enter press in JTextField

Do you want to do something like this ?

JTextField mTextField = new JTextField();
    mTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                // something like...
               //mTextField.getText();
               // or...
               //mButton.doClick();
            }
        }

    });

How to hide first section header in UITableView (grouped style)

In Swift 4.2 and many earlier versions, instead of setting the first header's height to 0 like in the other answers, you can just set the other headers to nil. Say you have two sections and only want the second one (i.e., 1) to have a header. That header will have the text Foobar:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return section == 1 ? "Foobar" : nil
}

Is there a timeout for idle PostgreSQL connections?

Another option is set this value "tcp_keepalives_idle". Check more in documentation https://www.postgresql.org/docs/10/runtime-config-connection.html.

How to capture the "virtual keyboard show/hide" event in Android?

Nebojsa Tomcic's answer wasn't helpful for me. I have RelativeLayout with TextView and AutoCompleteTextView inside it. I need to scroll the TextView to the bottom when the keyboard is showed and when it's hidden. To accomplish this I overrode onLayout method and it works fine for me.

public class ExtendedLayout extends RelativeLayout
{
    public ExtendedLayout(Context context, AttributeSet attributeSet)
    {
        super(context, attributeSet);
        LayoutInflater inflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.main, this);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        super.onLayout(changed, l, t, r, b);

        if (changed)
        {
            int scrollEnd = (textView.getLineCount() - textView.getHeight() /
                textView.getLineHeight()) * textView.getLineHeight();
            textView.scrollTo(0, scrollEnd);
        }
    }
}

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

If everything mentioned above does not work try the following. It worked for me.

Remove your project from the server > Restart server > Add your project to server > Restart server.

Detailed Instruction:

1. Right click on server > Add and Remove
2. Select your project > Remove > Finish
3. Restart your server
4. Right click on server > Add and Remove
5. Select your project > Add > Finish
6. Restart your server again.

Difference between Date(dateString) and new Date(dateString)

Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?

Until ES5, there was no string format that browsers were required to support, though there are a number that are widely supported. However browser support is unreliable an inconsistent, e.g. some will allow out of bounds values and others wont, some support certain formats and others don't, etc.

ES5 introduced support for some ISO 8601 formats, however the OP is not compliant with ISO 8601 and not all browsers in use support it anyway.

The only reliable way is to use a small parsing function. The following parses the format in the OP and also validates the values.

_x000D_
_x000D_
/* Parse date string in format yyyy-mm-dd hh:mm:ss_x000D_
** If string contains out of bounds values, an invalid date is returned_x000D_
** _x000D_
** @param {string} s - string to parse, e.g. "2010-08-17 12:09:36"_x000D_
**                     treated as "local" date and time_x000D_
** @returns {Date}   - Date instance created from parsed string_x000D_
*/_x000D_
function parseDateString(s) {_x000D_
  var b = s.split(/\D/);_x000D_
  var d = new Date(b[0], --b[1], b[2], b[3], b[4], b[5]);_x000D_
  return d && d.getMonth() == b[1] && d.getHours() == b[3] &&_x000D_
         d.getMinutes() == b[4]? d : new Date(NaN);_x000D_
}_x000D_
  _x000D_
document.write(_x000D_
  parseDateString('2010-08-17 12:09:36') + '<br>' +  // Valid values_x000D_
  parseDateString('2010-08-45 12:09:36')             // Out of bounds date_x000D_
);
_x000D_
_x000D_
_x000D_

Javascript: The prettiest way to compare one value against multiple values

You can use a switch:

switch (foobar) {
  case foo:
  case bar:
    // do something
}

How to make child process die after parent exits?

I think a quick and dirty way is to create a pipe between child and parent. When parent exits, children will receive a SIGPIPE.

What is the default Precision and Scale for a Number in Oracle?

Oracle stores numbers in the following way: 1 byte for power, 1 byte for the first significand digit (that is one before the separator), the rest for the other digits.

By digits here Oracle means centesimal digits (i. e. base 100)

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 125, '9'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('7', 125, '7'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
  2  /

INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))

ORA-01426: numeric overflow

SQL> SELECT DUMP(num) FROM t_numtest;

DUMP(NUM)
--------------------------------------------------------------------------------
Typ=2 Len=2: 255,11
Typ=2 Len=21: 255,8,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,79

As we can see, the maximal number here is 7.(7) * 10^124, and he have 19 centesimal digits for precision, or 38 decimal digits.

CSS3 transitions inside jQuery .css()

Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.

Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.

JS Fiddle Live Demo

Javascript:

$("#startTransition").on("click", function()
{

    if( $(".boxOne").is(":visible")) 
    {
        $(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
        $(".boxTwo").css({ x: '100%' });
        $(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
        return;        
    }

    $(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
    $(".boxOne").css({ x: '100%' });
    $(".boxOne").show().transition({ x: '0%', opacity: 1.0 });

});

Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.

Calculate the display width of a string in Java

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

Could not load type from assembly error

Maybe not as likely, but for me it was caused by my application trying to load a library with the same assembly name (xxx.exe loading xxx.dll).

How can I quickly delete a line in VIM starting at the cursor position?

You might also be interested in C, it will also delete the end of line like D, but additionally it will put you in Insert mode at the cursor location.

How can I pass POST parameters in a URL?

Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.

You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).

To make a POST request, you need to create a <form>. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.

Change Volley timeout duration

To handle Android Volley Timeout you need to use RetryPolicy

RetryPolicy

  • Volley provides an easy way to implement your RetryPolicy for your requests.
  • Volley sets default Socket & ConnectionTImeout to 5 secs for all requests.

RetryPolicy is an interface where you need to implement your logic of how you want to retry a particular request when a timeout happens.

It deals with these three parameters

  • Timeout - Specifies Socket Timeout in millis per every retry attempt.
  • Number Of Retries - Number of times retry is attempted.
  • Back Off Multiplier - A multiplier which is used to determine exponential time set to socket for every retry attempt.

For ex. If RetryPolicy is created with these values

Timeout - 3000 ms, Num of Retry Attempts - 2, Back Off Multiplier - 2.0

Retry Attempt 1:

  • time = time + (time * Back Off Multiplier);
  • time = 3000 + 6000 = 9000ms
  • Socket Timeout = time;
  • Request dispatched with Socket Timeout of 9 Secs

Retry Attempt 2:

  • time = time + (time * Back Off Multiplier);
  • time = 9000 + 18000 = 27000ms
  • Socket Timeout = time;
  • Request dispatched with Socket Timeout of 27 Secs

So at the end of Retry Attempt 2 if still Socket Timeout happens Volley would throw a TimeoutError in your UI Error response handler.

//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. 
//Volley does retry for you if you have specified the policy.
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Simple way to get element by id within a div tag?

A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.

You could change your HTML to this:

<div id="div1" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>
<div id="div2" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>

Then, you could get the first item in div1 with a CSS selector like this:

#div1 .edit1

On in jQuery:

$("#div1 .edit1")

Or, if you want to iterate the items in one of your divs, you can do it like this:

$("#div1 input").each(function(index) {
    // do something with one of the input objects
});

If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.

If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.

You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

I was having a similar issue with a property being null or undefined.

This ended up being that IE's document mode was being defaulted to IE7 Standards. This was due to the compatibility mode being automatically set to be used for all intranet sites (Tools > Compatibility View Setting > Display Intranet Sites in Compatibility View).

How to display multiple notifications in android

Below is the code for pass unique notification id:

//"CommonUtilities.getValudeFromOreference" is the method created by me to get value from savedPreferences.
String notificationId = CommonUtilities.getValueFromPreference(context, Global.NOTIFICATION_ID, "0");
int notificationIdinInt = Integer.parseInt(notificationId);

notificationManager.notify(notificationIdinInt, notification);

// will increment notification id for uniqueness
notificationIdinInt = notificationIdinInt + 1;
CommonUtilities.saveValueToPreference(context, Global.NOTIFICATION_ID, notificationIdinInt + "");
//Above "CommonUtilities.saveValueToPreference" is the method created by me to save new value in savePreferences.

Reset notificationId in savedPreferences at specific range like I have did it at 1000. So it will not create any issues in future. Let me know if you need more detail information or any query. :)

@angular/material/index.d.ts' is not a module

This can be solved by writing full path, for example if you want to include MatDialogModule follow:

Prior to @angular/material 9.x.x

import { MatDialogModule } from "@angular/material";
//leading to error mentioned

As per @angular/material 9.x.x

import { MatDialogModule } from "@angular/material/dialog";
//works fine 

Official change log breaking change reference: https://github.com/angular/components/blob/master/CHANGELOG.md#material-9

WebDriver: check if an element exists?

Write the following method using Java:

protected boolean isElementPresent(By by){
        try{
            driver.findElement(by);
            return true;
        }
        catch(NoSuchElementException e){
            return false;
        }
    }

Call the above method during assertion.

How to Consolidate Data from Multiple Excel Columns All into One Column

Best and Simple solution to follow:

Select the range of the columns you want to be copied to single column

Copy the range of cells (multiple columns)

Open Notepad++

Paste the selected range of cells

Press Ctrl+H, replace \t by \n and click on replace all

all the multiple columns fall under one single column

now copy the same and paste in excel

Simple and effective solution for those who dont want to waste time coding in VBA

How to change a dataframe column from String type to Double type in PySpark?

There is no need for an UDF here. Column already provides cast method with DataType instance :

from pyspark.sql.types import DoubleType

changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))

or short string:

changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))

where canonical string names (other variations can be supported as well) correspond to simpleString value. So for atomic types:

from pyspark.sql import types 

for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType', 
          'DecimalType', 'DoubleType', 'FloatType', 'IntegerType', 
           'LongType', 'ShortType', 'StringType', 'TimestampType']:
    print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp

and for example complex types

types.ArrayType(types.IntegerType()).simpleString()   
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'

Importing larger sql files into MySQL

Had a similar problem, but in Windows. I was trying to figure out how to open a large MySql sql file in Windows, and these are the steps I had to take:

  • Go to the download website (http://dev.mysql.com/downloads/).
  • Download the MySQL Community Server and install it (select the developer or full install, so it will install client and server tools).
  • Open MySql Command Line Client from the Start menu.
  • Enter your password used in install.
  • In the prompt, mysql>, enter:

    CREATE DATABASE database_name;

    USE database_name;

    SOURCE myfile.sql

That should import your large file.

Using scanner.nextLine()

Rather than placing an extra scanner.nextLine() each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)

import java.util.Scanner;

class ScannerTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\\n");

        System.out.print("Enter an index: ");
        int index = scanner.nextInt();

        System.out.print("Enter a sentence: ");
        String sentence = scanner.next();

        System.out.println("\nYour sentence: " + sentence);
        System.out.println("Your index: " + index);
    }
}

Thus, to read a line of input, you only need scanner.next() that has the same behavior delimiter-wise of next{Int, Double, ...}

The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3, 3<space> and 3<space>whatever while the former only accepts 3 on a line on its own

How do you test a public/private DSA keypair?

Encrypt something with the public key, and see which private key decrypts it.

This Code Project article by none other than Jeff Atwood implements a simplified wrapper around the .NET cryptography classes. Assuming these keys were created for use with RSA, use the asymmetric class with your public key to encrypt, and the same with your private key to decrypt.

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Tools >> Options >> Designers and uncheck “Prevent Saving changes that require table re-creation”:

Description in Photos format

How to make overlay control above all other controls?

Put the control you want to bring to front at the end of your xaml code. I.e.

<Grid>
  <TabControl ...>
  </TabControl>
  <Button Content="ALways on top of TabControl Button"/>
</Grid>

Generate Java classes from .XSD files...?

If you want to start coding Java to XML and XML to Java in less than 5 minutes, try Simple XML Serialization. Don't spend hours learning the JAXB API http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php

However, if you are really keen on learning JAXB, here's an excellent tutorial http://blogs.oracle.com/teera/entry/jaxb_for_simple_java_xml

Contents of tutorial:

JAXB for simple Java-XML serialization

There're a number of way to do XML serialization in Java. If you want fine-grained control over parsing and serialization you can go for SAX, DOM, or Stax for better performance. Yet, what I often want to do is a simple mapping between POJOs and XML. However, creating Java classes to do XML event parsing manually is not trivial. I recently found JAXB to be a quick and convenient Java-XML mapping or serialization.

JAXB contains a lot of useful features, you can check out the reference implementation here. Kohsuke's Blog is also a good resource to learn more about JAXB. For this blog entry, I'll show you how to do a simple Java-XML serialization with JAXB.

POJO to XML

Let's say I have an Item Java object. I want to serialize an Item object to XML format. What I have to do first is to annotate this POJO with a few XML annotation from javax.xml.bind.annotation.* package. See code listing 1 for Item.java

From the code

  • @XmlRootElement(name="Item") indicates that I want to be the root element.
  • @XmlType(propOrder = {"name", "price"}) indicates the order that I want the element to be arranged in XML output.
  • @XmlAttribute(name="id", ...) indicates that id is an attribute to root element.
  • @XmlElement(....) indicates that I want price and name to be element within Item.

My Item.java is ready. I can then go ahead and create JAXB script for marshaling Item.

//creating Item data object
Item item = new Item();
item.setId(2);
item.setName("Foo");
item.setPrice(200);
.....

JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
//I want to save the output file to item.xml
marshaller.marshal(item, new FileWriter("item.xml"));

For complete code Listing please see Code Listing 2 main.java. The output Code Listing 3 item.xml file is created. It looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:item ns1:id="2" xmlns:ns1="http://blogs.sun.com/teera/ns/item">
  <ns1:itemName>Foo</ns1:itemName>
  <ns1:price>200</ns1:price>
</ns1:item>

Easy right? You can alternatively channel the output XML as text String, Stream, Writer, ContentHandler, etc by simply change the parameter of the marshal(...) method like

...
JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
// save xml output to the OutputStream instance
marshaller.marshal(item, <java.io.OutputStream instance>);

...
JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
//save to StringWriter, you can then call sw.toString() to get java.lang.String
marshaller.marshal(item, sw);

XML to POJO

Let's reverse the process. Assume that I now have a piece of XML string data and I want to turn it into Item.java object. XML data (Code listing 3) looks like

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:item ns1:id="2" xmlns:ns1="http://blogs.sun.com/teera/ns/item">
  <ns1:itemName>Bar</ns1:itemName>
  <ns1:price>80</ns1:price>
</ns1:item>

I can then unmarshal this xml code to Item object by

...
ByteArrayInputStream xmlContentBytes = new ByteArrayInputStream (xmlContent.getBytes());
JAXBContext context = JAXBContext.newInstance(Item.getClass());
Unmarshaller unmarshaller = context.createUnmarshaller();
//note: setting schema to null will turn validator off
unmarshaller.setSchema(null);
Object xmlObject = Item.getClass().cast(unmarshaller.unmarshal(xmlContentBytes));
return xmlObject;
...

For complete code Listing please see Code Listing 2 (main.java). The XML source can come in many forms both from Stream and file. The only difference, again, is the method parameter:

...
unmarshaller.unmarshal(new File("Item.xml")); // reading from file
...
// inputStream is an instance of java.io.InputStream, reading from stream
unmarshaller.unmarshal(inputStream);

Validation with XML Schema

Last thing I want to mention here is validating input XML with schema before unmarshalling to Java object. I create an XML schema file called item.xsd. For complete code Listing please see Code Listing 4 (Item.xsd). Now what I have to do is register this schema for validation.

...
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
.newSchema(new File("Item.xsd"));
unmarshaller.setSchema(schema); //register item.xsd shcema for validation
...

When I try to unmarshal XML data to POJO, if the input XML is not conformed to the schema, exception will be caught. For complete code Listing please see Code Listing 5 (invalid_item.xml).

javax.xml.bind.UnmarshalException
- with linked exception:
javax.xml.bind.JAXBException caught: null
[org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: 'item1' is
                                not a valid value for 'integer'.]

Here I change the 'id' attribute to string instead of integer.

If XML input is valid against the schema, the XML data will be unmarshalled to Item.java object successfully.