Programs & Examples On #Tipc

How to get coordinates of an svg element?

The way to determine the coordinates depends on what element you're working with. For circles for example, the cx and cy attributes determine the center position. In addition, you may have a translation applied through the transform attribute which changes the reference point of any coordinates.

Most of the ways used in general to get screen coordinates won't work for SVGs. In addition, you may not want absolute coordinates if the line you want to draw is in the same container as the elements it connects.


In your particular code, it's quite difficult to get the position of the node because its determined by a translation of the parent element. So you need to get the transform attribute of the parent node and extract the translation from that.


Working jsfiddle here.

Set View Width Programmatically

You can use something like code below, if you need to affect only specific value, and not touch others:

view.getLayoutParams().width = newWidth;

Tooltips with Twitter Bootstrap

I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:

<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>

Then you can trigger all links with the .link class attached as tooltips like so:


Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel attribute. With this attribute you can target all links or elements with the rel property set to tooltip, like so:


And your links would look like something like this:

<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>

Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:

    selector: "a[rel=tooltip]"

This selector will target all of your tooltips with the rel attribute "within" your #example div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.

Sass Variable in CSS calc() function

you can use your verbal #{your verbal}

How do I lowercase a string in Python?

Use .lower() - For example:

s = "Kilometer"

The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

How to iterate over a TreeMap?

Just to point out the generic way to iterate over any map:

 private <K, V> void iterateOverMap(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
        System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());

how to convert numeric to nvarchar in sql command

select convert(nvarchar(255), 4343)

Should do the trick.

Getting unix timestamp from Date()

In java 8, it's convenient to use the new date lib and getEpochSecond method to get the timestamp (it's in second);

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

You need to specify data, index and columns to DataFrame constructor, as in:

>>> pd.DataFrame(data=data[1:,1:],    # values
...              index=data[1:,0],    # 1st column as index
...              columns=data[0,1:])  # 1st row as the column names

edit: as in the @joris comment, you may need to change above to np.int_(data[1:,1:]) to have correct data type.

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

Sounds like one part of the project is being built for x86-only while the rest is being built for any CPU/x64. This bit me, too. Are you running an x64 (or uh... IA64)?

Check the project properties and make sure everything is being built for "Any CPU". f you're in Visual Studio, you can check for everything by going to the "x86" or "Any CPU" menu (next to the "Debug"/"Release" menu) on the toolbar at the top of the screen and clicking "Configuration Manager..."

Convert between UIImage and Base64 string

For the Base64 code like:


Use Swift5.0 code like:

func imageFromBase64(_ base64: String) -> UIImage? {
    if let url = URL(string: base64) {
        if let data = try? Data(contentsOf: url) {
            return UIImage(data: data)
    return nil

What is the use of style="clear:both"?

clear:both makes the element drop below any floated elements that precede it in the document.

You can also use clear:left or clear:right to make it drop below only those elements that have been floated left or right.

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |

How to enable multidexing with the new Android Multidex support library

Add to AndroidManifest.xml:




in your custom Application's attachBaseContext method

or your custom Application extend MultiDexApplication

add multiDexEnabled = true in your build.gradle

defaultConfig {
    multiDexEnabled true

dependencies {
    compile ''

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

It looks like the string contains an array with a single MyStok object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStok objects, and take the object at index zero.

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];

Bold & Non-Bold Text In A Single UILabel?

If you want to make using attributed strings easier, try using Attributed String Creator, which will generate the code for you.

How to Get a Specific Column Value from a DataTable?

I suppose you could use a DataView object instead, this would then allow you to take advantage of the RowFilter property as explained here:

private void MakeDataView() 
    DataView view = new DataView();

    view.Table = DataSet1.Tables["Countries"];
    view.RowFilter = "CountryName = 'France'";
    view.RowStateFilter = DataViewRowState.ModifiedCurrent;

    // Simple-bind to a TextBox control
    Text1.DataBindings.Add("Text", view, "CountryID");

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

How can I make git show a list of the files that are being tracked?

The accepted answer only shows files in the current directory's tree. To show all of the tracked files that have been committed (on the current branch), use

git ls-tree --full-tree --name-only -r HEAD
  • --full-tree makes the command run as if you were in the repo's root directory.
  • -r recurses into subdirectories. Combined with --full-tree, this gives you all committed, tracked files.
  • --name-only removes SHA / permission info for when you just want the file paths.
  • HEAD specifies which branch you want the list of tracked, committed files for. You could change this to master or any other branch name, but HEAD is the commit you have checked out right now.

This is the method from the accepted answer to the ~duplicate question

Select rows with same id but different value in another column

You can simply achieve it by

FROM test
     HAVING COUNT(*) > 1)


How do I increment a DOS variable in a FOR /F loop?

Or you can do this without using Delay.

set /a "counter=0"

-> your for loop here

do (
   call :increaseby1

set /a "counter+=1"

Boolean vs tinyint(1) for boolean values in MySQL

My experience when using Dapper to connect to MySQL is that it does matter. I changed a non nullable bit(1) to a nullable tinyint(1) by using the following script:


Then Dapper started throwing Exceptions. I tried to look at the difference before and after the script. And noticed the bit(1) had changed to tinyint(1).

I then ran:


Which solved the problem.

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

Convert bytes to a string

You need to decode the byte string and turn it in to a character (Unicode) string.

On Python 2

encoding = 'utf-8'


unicode('hello', encoding)

On Python 3

encoding = 'utf-8'


str(b'hello', encoding)

How to use XPath contains() here?

Paste my contains example here:

//table[contains(@class, "EC_result")]/tbody

Just get column names from hive table

use desc tablename from Hive CLI or beeline to get all the column names. If you want the column names in a file then run the below command from the shell.

$ hive -e 'desc dbname.tablename;' > ~/columnnames.txt

where dbname is the name of the Hive database where your table is residing You can find the file columnnames.txt in your root directory.

$cd ~

How do I draw a grid onto a plot in Python?

Using rcParams you can show grid very easily as follows

plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.edgecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 1
plt.rcParams['grid.color'] = "#cccccc"

If grid is not showing even after changing these parameters then use


before calling

Accessing a Dictionary.Keys Key through a numeric index

To expand on Daniels post and his comments regarding the key, since the key is embedded within the value anyway, you could resort to using a KeyValuePair<TKey, TValue> as the value. The main reasoning for this is that, in general, the Key isn't necessarily directly derivable from the value.

Then it'd look like this:

public sealed class CustomDictionary<TKey, TValue>
  : KeyedCollection<TKey, KeyValuePair<TKey, TValue>>
  protected override TKey GetKeyForItem(KeyValuePair<TKey, TValue> item)
    return item.Key;

To use this as in the previous example, you'd do:

CustomDictionary<string, int> custDict = new CustomDictionary<string, int>();

custDict.Add(new KeyValuePair<string, int>("key", 7));

int valueByIndex = custDict[0].Value;
int valueByKey = custDict["key"].Value;
string keyByIndex = custDict[0].Key;

Convert a timedelta to days, hours and minutes

I found the easiest way is using str(timedelta). It will return a sting formatted like 3 days, 21:06:40.001000, and you can parse hours and minutes using simple string operations or regular expression.

Working with SQL views in Entity Framework Core

Here is a new way to work with SQL views in EF Core: Query Types.

Doing a cleanup action just before Node.js exits

In the case where the process was spawned by another node process, like:

var child = spawn('gulp', ['watch'], {
    stdio: 'inherit',

And you try to kill it later, via:


This is how you handle the event [on the child]:

process.on('SIGTERM', function() {

How can I find the link URL by link text with XPath?

//a[text()='programming quesions site']/@href 

which basically identifies an anchor node <a> that has the text you want, and extracts the href attribute.

Git: How to pull a single file from a server repository in Git?

git fetch --all
git checkout origin/master -- <your_file_path>
git add <your_file_path>
git commit -m "<your_file_name> updated"

This is assuming you are pulling the file from origin/master.

Stored procedure with default parameters

I wrote with parameters that are predefined

They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:

Alter Procedure [Test]
    @StartDate AS varchar(6) = NULL, 
    @EndDate AS varchar(6) = NULL

NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.

Now you can call it without passing any arguments e.g. exec dbo.TEST

Get environment variable value in Dockerfile

If you just want to find and replace all environment variables ($ExampleEnvVar) in a Dockerfile then build it this would work:

envsubst < /path/to/Dockerfile | docker build -t myDockerImage . -f -

What to put in a python module docstring?

To quote the specifications:

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

Setting DataContext in XAML in WPF

This code will always fail.

As written, it says: "Look for a property named "Employee" on my DataContext property, and set it to the DataContext property". Clearly that isn't right.

To get your code to work, as is, change your window declaration to:

<Window x:Class="SampleApplication.MainWindow"
    Title="MainWindow" Height="350" Width="525">

This declares a new XAML namespace (local) and sets the DataContext to an instance of the Employee class. This will cause your bindings to display the default data (from your constructor).

However, it is highly unlikely this is actually what you want. Instead, you should have a new class (call it MainViewModel) with an Employee property that you then bind to, like this:

public class MainViewModel
   public Employee MyEmployee { get; set; } //In reality this should utilize INotifyPropertyChanged!

Now your XAML becomes:

<Window x:Class="SampleApplication.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding MyEmployee.EmpID}" />
    <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding MyEmployee.EmpName}" />

Now you can add other properties (of other types, names), etc. For more information, see Implementing the Model-View-ViewModel Pattern

How to get height of Keyboard?

// Step 1 :- Register NotificationCenter

ViewDidLoad() {


   // Register your Notification, To know When Key Board Appears.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   // Register your Notification, To know When Key Board Hides.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

// Step 2 :- These Methods will be called Automatically when Keyboard appears Or Hides

    func keyboardWillShow(notification:NSNotification) {
        let userInfo:NSDictionary = notification.userInfo! as NSDictionary
        let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        tblViewListData.frame.size.height = fltTblHeight-keyboardHeight

    func keyboardWillHide(notification:NSNotification) {
        tblViewListData.frame.size.height = fltTblHeight

How do I change the font-size of an <option> element within <select>?

.service-small option {
    font-size: 14px;
    padding: 5px;
    background: #5c5c5c;

I think it because you used .styled-select in start of the class code.

What precisely does 'Run as administrator' do?

Windows 7 requires that you intentionally ask for certain privileges so that a malicious program can't do bad things to you. If the free calculator you downloaded needed to be run as an administrator, you would know something is up. There are OS commands to elevate the privilege of your application (which will request confirmation from the user).

A good description can be found at:

How do I start Mongo DB from Windows?

  1. Download from
  2. Install .msi file in folder C:\mongodb
  3. Create data, data\db, log directories and mongo.config file under C:\mongodb.
  4. Add the following lines in "mongo.config" file

  5. Start server :

    mongod.exe --config="C:\mongodb\mongo.config"
  6. Connect to localhost MongoDB server via command line

    mongo --port 27017
  7. Connect to remote MongoDB server via command line with authentication.

    mongo --username abcd --password abc123 --host server_ip_or_dns --port 27017

That's it !!!

Doing HTTP requests FROM Laravel to an external API

Updated on March 21 2019

Add GuzzleHttp package using composer require guzzlehttp/guzzle:~6.3.3

Or you can specify Guzzle as a dependency in your project's composer.json

   "require": {
      "guzzlehttp/guzzle": "~6.3.3"

Include below line in the top of the class where you are calling the API

use GuzzleHttp\Client;

Add below code for making the request

$client = new Client();

$res = $client->request('POST', '', [
    'form_params' => [
        'name' => 'george',

if ($res->getStatusCode() == 200) { // 200 OK
    $response_data = $res->getBody()->getContents();

Default optional parameter in Swift function

in case you need to use a bool param, you need just to assign the default value.

func test(WithFlag flag: Bool = false){.....}

then you can use without or with the param:

test() //here flag automatically has the default value: false
test(WithFlag: true) //here flag has the value: true

How do you serialize a model instance in Django?

This is a project that it can serialize(JSON base now) all data in your model and put them to a specific directory automatically and then it can deserialize it whenever you want... I've personally serialized thousand records with this script and then load all of them back to another database without any losing data.

Anyone that would be interested in opensource projects can contribute this project and add more feature to it.


How to implement a SQL like 'LIKE' operator in java?

Check out

It's a zero dependency library in Java for doing glob (and sql like) type of comparisons. Over a large data set it is faster than translating to a regular expression.

Basic syntax

MatchingEngine m = GlobPattern.compile("dog%cat\%goat_", '%', '_', GlobPattern.HANDLE_ESCAPES);
if (m.matches(str)) { ... }

Change form size at runtime in C#

As a complement to the answers given above; do not forget about Form MinimumSize Property, in case you require to create smaller Forms.

Example Bellow:

private void SetDefaultWindowSize()
   int sizeW, sizeH;
   sizeW = 180;
   sizeH = 100;

   var size = new Size(sizeW, sizeH);

   Size = size;
   MinimumSize = size;

private void SetNewSize()
   Size = new Size(Width, 10);

How do I display an alert dialog on Android?

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("This is Title");
    builder.setMessage("This is message for Alert Dialog");
    builder.setPositiveButton("Positive Button", (dialog, which) -> onBackPressed());
    builder.setNegativeButton("Negative Button", (dialog, which) -> dialog.cancel());;

This is a way which alike to create the Alert dialog with some line of code.

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be, then you have to use port forwarding to connect to machine. IP address will be

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Ant build failed: "Target "build..xml" does not exist"

Is this a problem Only when you run ant -d or ant -verbose, but works other times?

I noticed this error message line:

Could not load definitions from resource org/apache/tools/ant/antlib.xml. It could not be found.

The org/apache/tools/ant/antlib.xml file is embedded in the ant.jar. The ant command is really a shell script called ant or a batch script called ant.bat. If the environment variable ANT_HOME is not set, it will figure out where it's located by looking to see where the ant command itself is located.

Sometimes I've seen this where someone will move the ant shell/batch script to put it in their path, and have ANT_HOME either not set, or set incorrectly.

What platform are you on? Is this Windows or Unix/Linux/MacOS? If you're on Windows, check to see if %ANT_HOME% is set. If it is, make sure it's the right directory. Make sure you have set your PATH to include %ANT_HOME%/bin.

If you're on Unix, don't copy the ant shell script to an executable directory. Instead, make a symbolic link. I have a directory called /usr/local/bin where I put the command I want to override the commands in /bin and /usr/bin. My Ant is installed in /opt/ant-1.9.2, and I have a symbolic link from /opt/ant-1.9.2 to /opt/ant. Then, I have symbolic links from all commands in /opt/ant/bin to /usr/local/bin. The Ant shell script can detect the symbolic links and find the correct Ant HOME location.

Next, go to your Ant installation directory and look under the lib directory to make sure ant.jar is there, and that it contains org/apache/tools/ant/antlib.xml. You can use the jar tvf ant.jar command. The only thing I can emphasize is that you do have everything setup correctly. You have your Ant shell script in your PATH either because you included the bin directory of your Ant's HOME directory in your classpath, or (if you're on Unix/Linux/MacOS), you have that file symbolically linked to a directory in your PATH.

Make sure your JAVA_HOME is set correctly (on Unix, you can use the symbolic link trick to have the java command set it for you), and that you're using Java 1.5 or higher. Java 1.4 will no longer work with newer versions of Ant.

Also run ant -version and see what you get. You might get the same error as before which leads me to think you have something wrong.

Let me know what you find, and your OS, and I can give you directions on reinstalling Ant.

how to get data from selected row from datagridview

To get the cell value, you need to read it directly from DataGridView1 using e.RowIndex and e.ColumnIndex properties.


Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
   Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

   If IsDBNull(value) Then 
      TextBox1.Text = "" ' blank if dbnull values
      TextBox1.Text = CType(value, String)
   End If
End Sub

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

When you generate a JAXB model from an XML Schema, global elements that correspond to named complex types will have that metadata captured as an @XmlElementDecl annotation on a create method in the ObjectFactory class. Since you are creating the JAXBContext on just the DocumentType class this metadata isn't being processed. If you generated your JAXB model from an XML Schema then you should create the JAXBContext on the generated package name or ObjectFactory class to ensure all the necessary metadata is processed.

Example solution:

JAXBContext jaxbContext = JAXBContext.newInstance(my.generatedschema.dir.ObjectFactory.class);
DocumentType documentType = ((JAXBElement<DocumentType>) jaxbContext.createUnmarshaller().unmarshal(inputStream)).getValue();

How to add a new column to a CSV file?

I'm surprised no one suggested Pandas. Although using a set of dependencies like Pandas might seem more heavy-handed than is necessary for such an easy task, it produces a very short script and Pandas is a great library for doing all sorts of CSV (and really all data types) data manipulation. Can't argue with 4 lines of code:

import pandas as pd
csv_input = pd.read_csv('input.csv')
csv_input['Berries'] = csv_input['Name']
csv_input.to_csv('output.csv', index=False)

Check out Pandas Website for more information!

Contents of output.csv:


Change SQLite database mode to read-write

There can be several reasons for this error message:

  • Several processes have the database open at the same time (see the FAQ).

  • There is a plugin to compress and encrypt the database. It doesn't allow to modify the DB.

  • Lastly, another FAQ says: "Make sure that the directory containing the database file is also writable to the user executing the CGI script." I think this is because the engine needs to create more files in the directory.

  • The whole filesystem might be read only, for example after a crash.

  • On Unix systems, another process can replace the whole file.

Add column with constant value to pandas dataframe

Here is another one liner using lambdas (create column with constant value = 10)

df['newCol'] = df.apply(lambda x: 10, axis=1)


    A           B           C
1   1.764052    0.400157    0.978738
2   2.240893    1.867558    -0.977278
3   0.950088    -0.151357   -0.103219


        A           B           C           newCol
    1   1.764052    0.400157    0.978738    10
    2   2.240893    1.867558    -0.977278   10
    3   0.950088    -0.151357   -0.103219   10

How to clear form after submit in Angular 2?

Below code works for me in Angular 4

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class RegisterComponent implements OnInit {
 registerForm: FormGroup; 

 constructor(private formBuilder: FormBuilder) { }   

 ngOnInit() {
    this.registerForm ={
      empname: [''],
      empemail: ['']

    //sending data to server using http request


How to list all dates between two dates

Use this,

DECLARE @start_date DATETIME = '2015-02-12 00:00:00.000';
DECLARE @end_date DATETIME = '2015-02-13 00:00:00.000';

WITH    AllDays
          AS ( SELECT   @start_date AS [Date], 1 AS [level]
               UNION ALL
               SELECT   DATEADD(DAY, 1, [Date]), [level] + 1
               FROM     AllDays
               WHERE    [Date] < @end_date )
     SELECT [Date], [level]

pass the @start_date and @end_date as SP parameters.


Date                    level
----------------------- -----------
2015-02-12 00:00:00.000 1
2015-02-13 00:00:00.000 2

(2 row(s) affected)

SQL Not Like Statement not working


Should work, do you get more rows if you run the same SQL with the "NOT LIKE" line commented out? If not, check the data. I know you mentioned in your question, but check that the actual SQL statement is using that clause. The other answers with NULL are also a good idea.

IFrame: This content cannot be displayed in a frame

The X-Frame-Options is defined in the Http Header and not in the <head> section of the page you want to use in the iframe.

Accepted values are: DENY, SAMEORIGIN and ALLOW-FROM "url"

Spring boot - Not a managed type

never forget to add @Entity on domain class

Disable cache for some images

Browser caching strategies can be controlled by HTTP headers. Remember that they are just a hint, really. Since browsers are terribly inconsistent in this (and any other) field, you'll need several headers to get the desired effect on a range of browsers.

header ("Pragma-directive: no-cache");
header ("Cache-directive: no-cache");
header ("Cache-control: no-cache");
header ("Pragma: no-cache");
header ("Expires: 0");

How can I uninstall Ruby on ubuntu?

This command should do the trick (provided that you installed it using a dpkg-based packet manager):

aptitude purge ruby

How do I share a global variable between c files?

file 1:

int x = 50;

file 2:

extern int x;

printf("%d", x);

Uninstall all installed gems, in OSX?

If you are using Rubygems version 2.1.0 or later, you can try: gem uninstall --all.

add column to mysql table if it does not exist

Most of the answers address how to add a column safely in a stored procedure, I had the need to add a column to a table safely without using a stored proc and discovered that MySQL does not allow the use of IF Exists() outside a SP. I'll post my solution that it might help someone in the same situation.

SELECT count(*)
INTO @exist
FROM information_schema.columns 
WHERE table_schema = database()
and COLUMN_NAME = 'original_data'
AND table_name = 'mytable';

set @query = IF(@exist <= 0, 'alter table intent add column mycolumn4 varchar(2048) NULL after mycolumn3', 
'select \'Column Exists\' status');

prepare stmt from @query;


Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

   gson = new;
            Response respuesta = gson.fromJson(json, Response.class);


        } catch (IOException ex) {
        return null;

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        public void setExample(String example) {
            this.example = example;
        public String getFr() {
            return fr;
        public void setFr(String fr) {
   = fr;

Using json-simple:


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {


    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;

            } catch (Exception e) {
                // TODO: handle exception

        } catch (IOException ex) {
        return null;


Formatting floats in a numpy array

[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]

How do I include a file over 2 directories back?

I recomend to use __DIR__ to specify current php file directory. Check here for the reason.

__DIR__ . /../../index.php

DateTime "null" value

If you're using .NET 2.0 (or later) you can use the nullable type:

DateTime? dt = null;


Nullable<DateTime> dt = null;

then later:

dt = new DateTime();

And you can check the value with:

if (dt.HasValue)
  // Do something with dt.Value

Or you can use it like:

DateTime dt2 = dt ?? DateTime.MinValue;

You can read more here:

Run an exe from C# code

I know this is well answered, but if you're interested, I wrote a library that makes executing commands much easier.

Check it out here:

error C2220: warning treated as error - no 'object' file generated

The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.

In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.

Is System.nanoTime() completely useless?

The Java 5 documentation also recommends using this method for the same purpose.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

Java 5 API Doc

How can I upload files asynchronously?

You can see a solved solution with a working demo here that allows you to preview and submit form files to the server. For your case, you need to use Ajax to facilitate the file upload to the server:

<from action="" id="formContent" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file" size="10"/>
    <input id="uploadbutton" type="button" value="Upload"/>

The data being submitted is a formdata. On your jQuery, use a form submit function instead of a button click to submit the form file as shown below.

$(document).ready(function () {

     var formdata = new FormData(this);

     url: "ajax_upload_image.php",
     type: "POST",
     data: formdata,
     contentType: false,
     cache: false,
     processData: false,
     success: function(){

     alert("successfully submitted");


View more details

How do I run a single test using Jest?

Full command to run a single Jest test


node <path-to-jest> -i <you-test-file> -c <jest-config> -t "<test-block-name>"

  • <path-to-jest>:
    • Windows: node_modules\jest\bin\jest.js
    • Others: node_modules/.bin/jest
  • -i <you-test-file>: path to the file with tests (js or ts)
  • -c <jest-config>: path to a separate Jest config file (JSON), if you keep your Jest configuration in package.json, you don't have to specify this parameter (Jest will find it without your help)
  • -t <the-name-of-test-block>: actually it's a name (the first parameter) of describe(...), it(...), or test(...) block.


describe("math tests", () => {

  it("1 + 1 = 2", () => {
    expect(1 + 1).toBe(2);

  it("-1 * -1 !== -1", () => {
    expect(-1 * -1).not.toBe(-1);


So, the command

node node_modules/jest/bin/jest.js -i test/math-tests.js -c test/tests-config.json -t "1 + 1 = 2"

will test it("1 + 1 = 2", ...), but if you change the -t parameter to "math tests" then it will run both tests from the describe("math tests",...) block.


  1. For Windows, replace node_modules/.bin/jest with node_modules\jest\bin\jest.js.
  2. This approach allows you to debug the running script. To enable debugging add '--inspect-brk' parameter to the command.

Running a single Jest test via NPM scripts in 'package.json'

Having Jest installed, you can simplify the syntax of this command (above) by using NPM scripts. In "package.json" add a new script to the "scripts" section:

"scripts": {
  "test:math": "jest -i test/my-tests.js -t \"math tests\"",

In this case, we use an alias 'jest' instead of writing the full path to it. Also, we don't specify the configuration file path since we can place it in "package.json" as well and Jest will look into it by default. Now you can run the command:

npm run test:math

And the "math tests" block with two tests will be executed. Or, of course, you can specify one particular test by its name.

Another option would be to pull the <the-name-of-test-block> parameter outside the "test:math" script and pass it from the NPM command:


"scripts": {
  "test:math": "jest -i test/my-tests.js -t",


npm run test:math "math tests"

Now you can manage the name of the run test(s) with a much shorter command.


  1. The 'jest' command will work with NPM scripts because

npm makes "./node_modules/.bin" the first entry in the PATH environment variable when running any lifecycle scripts, so this will work fine, even if your program is not globally installed (NPM blog) 2. This approach doesn't seem to allow debugging because Jest is run via its binary/CLI, not via node.

Running a selected Jest test in Visual Studio Code

If you are using Visual Studio Code you can take advantage of it and run the currently selected test (in the code editor) by pressing the F5 button. To do this, we will need to create a new launch configuration block in the ".vscode/launch.json" file. In that configuration, we will use predefined variables which are substituted with the appropriate (unfortunately not always) values when running. Of all available we are only interested in these:

  • ${relativeFile} - the current opened file relative to ${workspaceFolder}
  • ${selectedText} - the current selected text in the active file

But before writing out the launch configuration we should add the 'test' script in our 'package.json' (if we haven't done it yet).

File package.json:

"scripts": {
  "test": "jest"

Then we can use it in our launch configuration.

Launch configuration:

  "type": "node",
  "request": "launch",
  "name": "Run selected Jest test",
  "runtimeExecutable": "npm",
  "runtimeArgs": [
  "args": [
  "console": "integratedTerminal",

It actually does the same as the commands described earlier in this answer. Now that everything is ready, we can run any test we want without having to rewrite the command parameters manually.

Here's all you need to do:

  1. Select currently created launch config in the debug panel:

    Select launch config in the Visual Studio Code debug panel

  2. Open the file with tests in the code editor and select the name of the test you want to test (without quotation marks):

    Select test name

  3. Press F5 button.

And voilà!

Now to run any test you want. Just open it in the editor, select its name, and press F5.

Unfortunately, it won't be "voilà" on a Windows machines because they substitute (who knows why) the ${relativeFile} variable with the path having reversed slashes and Jest wouldn't understand such a path.


  1. To run under the debugger, don't forget to add the '--inspect-brk' parameter.
  2. In this configuration example, we don't have the Jest configuration parameter assuming that it's included in 'package.json'.

Update built-in vim on Mac OS X

A note to romainl's answer: aliases don't work together with sudo because only the first word is checked on aliases. To change this add another alias to your .profile / .bashrc:

alias sudo='sudo '

With this change sudo vim will behave as expected!

Convert to/from DateTime and Time in Ruby

You'll need two slightly different conversions.

To convert from Time to DateTime you can amend the Time class as follows:

require 'date'
class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24), month, day, hour, min, seconds, offset)

Similar adjustments to Date will let you convert DateTime to Time .

class Date
  def to_gm_time
    to_time(new_offset, :gm)

  def to_local_time
    to_time(new_offset(, :local)

  def to_time(dest, method)
    #Convert a fraction of a day to a number of microseconds
    usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
    Time.send(method, dest.year, dest.month,, dest.hour, dest.min,
              dest.sec, usec)

Note that you have to choose between local time and GM/UTC time.

Both the above code snippets are taken from O'Reilly's Ruby Cookbook. Their code reuse policy permits this.

Android: remove left margin from actionbar's custom layout

You need to add this line app2:contentInsetStart="0dp" in your toolbar

< xmlns:android=""

Regex match text between tags


Regular expression visualization

Add g (global) flag after:

             //^-----here it is 

However if you want to get all matched elements, then you need something like this:

var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
   return val.replace(/<\/?b>/g,'');
//result -> ["Bob", "20", "programming"] 

If an element has attributes, regexp will be:

/<b [^>]+>(.*?)<\/b>/g.exec(str)

How to install Openpyxl with pip

  1. download zip file and unzip it on local system.
  2. go to openpyxl folder where is present.
  3. open command prompt under the same path.
  4. Run a command: python install
  5. It will install openpyxl.

Flutter: Setting the height of the AppBar

At the time of writing this, I was not aware of PreferredSize. Cinn's answer is better to achieve this.

You can create your own custom widget with a custom height:

import "package:flutter/material.dart";

class Page extends StatelessWidget {
  Widget build(BuildContext context) {
    return new Column(children : <Widget>[new CustomAppBar("Custom App Bar"), new Container()],);

class CustomAppBar extends StatelessWidget {

  final String title;
  final double barHeight = 50.0; // change this for different heights 


  Widget build(BuildContext context) {
    final double statusbarHeight = MediaQuery

    return new Container(
      padding: new EdgeInsets.only(top: statusbarHeight),
      height: statusbarHeight + barHeight,
      child: new Center(
        child: new Text(
          style: new TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),

How to subtract date/time in JavaScript?

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

In your example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

Array of arrays (Python/NumPy)

If the file is only numerical values separated by tabs, try using the csv library: (you can set the delimiter to '\t')

If you have a textual file in which every line represents a row in a matrix and has integers separated by spaces\tabs, wrapped by a 'arrayname = [...]' syntax, you should do something like:

import re
f = open("your-filename", 'rb')
result_matrix = []
for line in f.readlines():
    match = re.match(r'\s*\w+\s+\=\s+\[(.*?)\]\s*', line)
    if match is None:
        pass # line syntax is wrong - ignore the line
    values_as_strings =
    result_matrix.append(map(int, values_as_strings))

How to run mysql command on bash?

Use double quotes while using BASH variables.

mysql --user="$user" --password="$password" --database="$database" --execute="DROP DATABASE $user; CREATE DATABASE $database;"

BASH doesn't expand variables in single quotes.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

Why the error is raised:

JavaScript code is limited by the same-origin policy, meaning, from a page at, you can only make (AJAX) requests to services located at exactly the same domain, in that case, exactly (not - without the www - or

In your case, your Ajax code is trying to reach a service in from a page located at

Although very similar, they are not the same domain. And when they are not on the same domain, the request will only be successful if the target's respose contains a Access-Control-Allow-Origin header in it.

As your page/service at was never configured to present such header, that error message is shown.


As said, the origin (where the page with JavaScript is at) and the target (where the JavaScript is trying to reach) domains must be the exact same.

Your case seems like a typo. Looks like and are actually the same server/domain. So to fix, type the target and the origin equally: make you Ajax code request pages/services to not (Maybe place the target URL relatively, like '/login.php', without the domain).

On a more general note:

If the problem is not a typo like the one of this question seems to be, the solution would be to add the Access-Control-Allow-Origin to the target domain. To add it, depends, of course, of the server/language behind that address. Sometimes a configuration variable in the tool will do the trick. Other times you'll have to add the headers through code yourself.

Does :before not work on img elements?

Here's another solution using a div container for img while using :hover::after to achieve the effect.

The HTML as follows:

<div id=img_container><img src='' style='height:300px; width:300px;'></img></div>

The CSS as follows:

#img_container { 

#img_container:hover::after { 

To see it in action, check out the fiddle I've created. Just so you know this is cross browser friendly and there's no need to trick the code with 'fake content'.

How to make div follow scrolling smoothly with jQuery?

There's a fantastic jQuery tutorial for this at

It replicates the shopping cart type of sidebar scrolling. The Google query that might have served you well is "fixed floating sidebar".

Android: Center an image

If you are using a LinearLayout , use the gravity attribute :

<LinearLayout xmlns:android=""

    <ImageView android:layout_width="wrap_content"
        android:scaleType="centerInside" />

If you are using a RelativeLayout , you can use android:layout_centerInParent as follows :

<RelativeLayout xmlns:android=""
    android:layout_height="match_parent" >

    <ImageView android:id="@+id/imageView1"
        android:layout_centerInParent="true" />


C# create simple xml file

I'd recommend serialization,

public class Person
      public  string FirstName;
      public  string MI;
      public  string LastName;

static void Serialize()
      clsPerson p = new Person();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(System.Console.Out, p);
      System.Console.WriteLine(" --- Press any key to continue --- ");

You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:

using System;
using System.Xml;

public class GenerateXml {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

        XmlNode productsNode = doc.CreateElement("products");

        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "01";

        XmlNode nameNode = doc.CreateElement("Name");
        XmlNode priceNode = doc.CreateElement("Price");

        // Create and add another product node.
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "02";
        nameNode = doc.CreateElement("Name");
        priceNode = doc.CreateElement("Price");


And if it needs to be fast, use XmlWriter:

public static void WriteXML()
    // Create an XmlWriterSettings object with the correct options.
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "    "; //  "\t";
    settings.OmitXmlDeclaration = false;
    settings.Encoding = System.Text.Encoding.UTF8;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))


        for (int i = 0; i < 100; ++i)
            writer.WriteElementString("item", "Book "+ (i+1).ToString());


    } // End Using writer 


And btw, the fastest way to read XML is XmlReader:

public static void ReadXML()
    using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(""))
        while (xmlReader.Read())
            if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
                if (xmlReader.HasAttributes)
                    System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));

        } // Whend 

    } // End Using xmlReader


And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:

Python how to plot graph sine wave

This is another option

#!/usr/bin/env python

import numpy as np
import matplotlib
matplotlib.use('TKAgg') #use matplotlib backend TkAgg (optional)
import matplotlib.pyplot as plt

sample_rate = 200 # sampling frequency in Hz (atleast 2 times f)
t = np.linspace(0,5,sample_rate)    #time axis
f = 100 #Signal frequency in Hz
sig = np.sin(2*np.pi*f*(t/sample_rate))

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

Array.size() vs Array.length

The property 'length' returns the (last_key + 1) for arrays with numeric keys:

var  nums  =  new  Array ();
nums [ 10 ]  =  10 ; 
nums [ 11 ]  =  11 ; nums.length );

will print 12!

This will work:

var  nums  =  new  Array ();
nums [ 10 ]  =  10 ; 
nums [ 11 ]  =  11 ;
nums [ 12 ]  =  12 ; nums.length + '  /  '+ Object.keys(nums).length );

What causes java.lang.IncompatibleClassChangeError?

Please check if your code doesnt consist of two module projects that have the same classes names and packages definition. For example this could happen if someone uses copy-paste to create new implementation of interface based on previous implementation.

Upload DOC or PDF using PHP

$folder = "Resume/";
$temp = explode(".", $_FILES["uploaded"]["name"]);
$newfilename = round(microtime(true)).'.'. end($temp);
$db_path ="$folder".$newfilename  ;
//remove the .
$listtype = array(
if ( is_uploaded_file( $_FILES['uploaded']['tmp_name'] ) )
if($key = array_search($_FILES['uploaded']['type'],$listtype))
{if (move_uploaded_file($_FILES['uploaded']  ['tmp_name'],"$folder".$newfilename))
$sql ="INSERT INTO tb_upload
(filePath) VALUES ('$db_path')";
echo "File Type Should Be .Docx or .Pdf or .Rtf Or .Doc";

C# MessageBox dialog result

If you're using WPF and the previous answers don't help, you can retrieve the result using:

var result = MessageBox.Show("Message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question);

if (result == MessageBoxResult.Yes)
    // Do something

Why call super() in a constructor?

It simply calls the default constructor of the superclass.

error C2065: 'cout' : undeclared identifier

Just use printf!

Include stdio.h in your stdafx.h header file for printf.

Eclipse and Windows newlines

To recursively remove the carriage returns (\r) from the CVS/* files in all child directories, run the following in a unix shell:

find ./ -wholename "\*CVS/[RE]\*" -exec dos2unix -q -o {} \;

Setting Column width in Apache POI

With Scala there is a nice Wrapper spoiwo

You can do it like this:

      Column(autoSized = true),
      Column(width = new Width(100, WidthUnit.Character)),
      Column(width = new Width(100, WidthUnit.Character)))

Is there a "not equal" operator in Python?

Seeing as everyone else has already listed most of the other ways to say not equal I will just add:

if not (1) == (1): # This will eval true then false
    # (ie: 1 == 1 is true but the opposite(not) is false)
    print "the world is ending" # This will only run on a if true
elif (1+1) != (2): #second if
    print "the world is ending"
    # This will only run if the first if is false and the second if is true
else: # this will only run if the if both if's are false
    print "you are good for another day"

in this case it is simple switching the check of positive == (true) to negative and vise versa...

How to exit an application properly

You can use:




Process immediately terminated in Task Manager Processors!

Android Call an method from another class

In Class1:

Class2 inst = new Class2();

angular 2 how to return data from subscribe

I have used this way lots time ...

   selector: "data",_x000D_
   template: "<h1>{{ getData() }}</h1>"_x000D_
export class DataComponent{_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
    return data;_x000D_

use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...

Drop data frame columns by name

There's a function called dropNamed() in Bernd Bischl's BBmisc package that does exactly this.

BBmisc::dropNamed(df, "x")

The advantage is that it avoids repeating the data frame argument and thus is suitable for piping in magrittr (just like the dplyr approaches):

df %>% BBmisc::dropNamed("x")

Can I use an image from my local file system as background in HTML?

background: url(../images/backgroundImage.jpg) no-repeat center center fixed;

this should help

convert datetime to date format dd/mm/yyyy

This works for me:

string dateTimeString = "21?-?10?-?2014? ?15?:?40?:?30";
dateTimeString = Regex.Replace(dateTimeString, @"[^\u0000-\u007F]", string.Empty);

string inputFormat = "dd-MM-yyyy HH:mm:ss";
string outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
string output = dateTime.ToString(outputFormat);


how to check if the input is a number or not in C?

Using scanf is very easy, this is an example :

if (scanf("%d", &val_a_tester) == 1) {
    ... // it's an integer

How to get some values from a JSON string in C#?

my string

var obj = {"Status":0,"Data":{"guid":"","invitationGuid":"","entityGuid":"387E22AD69-4910-430C-AC16-8044EE4A6B24443545DD"},"Extension":null}

Following code to get guid:

var userObj = JObject.Parse(obj);
var userGuid = Convert.ToString(userObj["Data"]["guid"]);

Why is json_encode adding backslashes?

json_encode will always add slashes.

Check some examples on the manual HERE

This is because if there are some characters which needs to escaped then they will create problem.

To use the json please Parse your json to ensure that the slashes are removed

Well whether or not you remove slashesthe json will be parsed without any problem by eval.

$array = array('url'=>'','id'=>54);
<script src=""></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');

This is my code and i m able to parse the JSON.

Check your code May be you are missing something while parsing the JSON

insert data from one table to another in mysql

If you want insert all data from one table to another table there is a very simply sql

INSERT INTO destinationTable  (SELECT * FROM sourceDbName.SourceTableName);

Why does the 260 character path length limit exist in Windows?

As to how to cope with the path size limitation on Windows - using 7zip to pack (and unpack) your path-length sensitive files seems like a viable workaround. I've used it to transport several IDE installations (those Eclipse plugin paths, yikes!) and piles of autogenerated documentation and haven't had a single problem so far.

Not really sure how it evades the 260 char limit set by Windows (from a technical PoV), but hey, it works!

More details on their SourceForge page here:

"NTFS can actually support pathnames up to 32,000 characters in length."

7-zip also support such long names.

But it's disabled in SFX code. Some users don't like long paths, since they don't understand how to work with them. That is why I have disabled it in SFX code.

and release notes:

9.32 alpha 2013-12-01

  • Improved support for file pathnames longer than 260 characters.

4.44 beta 2007-01-20

  • 7-Zip now supports file pathnames longer than 260 characters.

IMPORTANT NOTE: For this to work properly, you'll need to specify the destination path in the 7zip "Extract" dialog directly, rather than dragging & dropping the files into the intended folder. Otherwise the "Temp" folder will be used as an interim cache and you'll bounce into the same 260 char limitation once Windows Explorer starts moving the files to their "final resting place". See the replies to this question for more information.

JavaScript: location.href to open in new window/tab?

For example:

        var t               = $(this), 
            URL             = t.attr('data-href');        
        $('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();


Working example.

Use jQuery to scroll to the bottom of a div with lots of text

please refer : .scrollTop(), You can give a try to the solution here :

$(function() {_x000D_
  var wtf    = $('#scroll');_x000D_
  var height = wtf[0].scrollHeight;_x000D_
 #scroll {_x000D_
   width: 200px;_x000D_
   height: 300px;_x000D_
   overflow-y: scroll;_x000D_
<script src=""></script>_x000D_
<div id="scroll">_x000D_
    <br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>_x000D_

Edit : for the people who are looking for a nice little animation with scrolling :

$(function() {_x000D_
  var height = 0;_x000D_
  function scroll(height, ele) {_x000D_
      scrollTop: height_x000D_
    }, 1000, function() {_x000D_
      var dir = height ? "top" : "bottom";_x000D_
      $(ele).html("scroll to " + dir).attr({_x000D_
        id: dir_x000D_
  var wtf = $('#scroll');_x000D_
  $("#bottom, #top").click(function() {_x000D_
    height = height < wtf[0].scrollHeight ? wtf[0].scrollHeight : 0;_x000D_, height, this);_x000D_
#scroll {_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  overflow-y: scroll;_x000D_
#top {_x000D_
  font-size: 12px;_x000D_
  cursor: pointer;_x000D_
  min-width: 50px;_x000D_
  padding: 5px;_x000D_
  border: 2px solid #0099f9;_x000D_
  border-radius: 5px;_x000D_
<script src=""></script>_x000D_
<span id="bottom">scroll to bottom</span>_x000D_
<br />_x000D_
<br />_x000D_
<br />_x000D_
<div id="scroll">_x000D_
  <center><b>There's Plenty of Room at the Top, seriously?</b>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam at enim dignissim, eleifend eros at, lobortis sem. Mauris vel erat felis. Proin quis convallis neque, quis molestie augue. Vestibulum aliquam elit sit amet venenatis eleifend. Donec dapibus_x000D_
    mauris ac lorem mattis pulvinar. Curabitur cursus elit commodo tellus bibendum, ut euismod nisi luctus. Pellentesque id magna nunc. Nam luctus nisi sapien, ac porta sem ultrices vitae. Suspendisse aliquet eleifend nunc, in mattis tellus dapibus rutrum._x000D_
    Nullam a sem venenatis, suscipit lorem eu, facilisis leo. Nunc eget eleifend magna. Curabitur dictum dui in massa vestibulum sagittis. Mauris sodales neque at tincidunt feugiat. Curabitur iaculis purus nec tortor elementum pulvinar. Donec non mattis_x000D_
  <p>Integer sit amet iaculis nulla. Cras vehicula nunc eu leo aliquet, et convallis erat aliquet. Aenean tempor faucibus justo, porta blandit felis semper at. Maecenas auctor nibh sit amet tellus consectetur, et varius velit iaculis. Phasellus convallis_x000D_
    lacinia dapibus. Praesent tempus nunc elit, id volutpat tellus sagittis commodo. Vestibulum ultrices quam vel congue viverra. Integer varius diam quis tempor consequat. Integer pulvinar neque lorem, eu lobortis augue pharetra vel. Praesent ornare_x000D_
    lacus quis nisi fermentum dignissim. Curabitur hendrerit augue eu interdum interdum.</p>_x000D_
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam a ex non dolor rutrum suscipit vitae sit amet nibh. Donec pulvinar odio non ultrices dignissim. Quisque in risus lobortis, accumsan ante et, pellentesque_x000D_
    erat. Quisque ultricies tortor sed tortor venenatis posuere. Integer convallis nunc ut tellus sagittis, et imperdiet erat volutpat. Sed non maximus augue. Sed mattis ipsum sed sem rutrum, at mollis ligula facilisis. Etiam fringilla hendrerit mi eu_x000D_
    molestie. Etiam semper feugiat nunc, eu pellentesque metus porta pretium. Duis tempor neque ut libero scelerisque euismod. Vivamus molestie, quam a mattis scelerisque, dolor turpis accumsan quam, a cursus sem quam at ex. Suspendisse congue elit quis_x000D_
    sem scelerisque commodo.</p>_x000D_
  <p>Ut eu odio at urna hendrerit ullamcorper. Nulla ut turpis molestie diam aliquet luctus. Curabitur dignissim tellus ut porta sagittis. Vivamus ut erat ut neque consequat interdum. Duis vitae risus eget arcu pulvinar venenatis. Maecenas erat arcu, hendrerit_x000D_
    id tortor ut, viverra elementum nibh. Nam quis metus sit amet lacus rhoncus porttitor ac non ipsum. Nullam lacus dui, tempus sed elementum ut, venenatis eget ipsum. Quisque blandit maximus enim eu porta.</p>_x000D_
  <p>Donec mollis diam eros, eu ultrices magna sollicitudin vitae. Nullam quam sapien, elementum a metus nec, facilisis scelerisque nulla. Praesent lobortis nisi ac leo laoreet, quis molestie ipsum porta. Suspendisse aliquet in velit eu ullamcorper. Maecenas_x000D_
    auctor, mi ut viverra elementum, metus turpis commodo orci, eu commodo erat dolor malesuada arcu. Fusce condimentum augue</p>_x000D_
  <center><b>Voila!! You have reached the bottom, already! :)</b>_x000D_

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:


The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

How do you get the footer to stay at the bottom of a Web page?

For this question many of the answers I have seen are clunky, hard to implement and inefficient so I thought I'd take a shot at it and come up with my own solution which is just a tiny bit of css and html

body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
.body {_x000D_
  min-height: calc(100% - 2rem);_x000D_
  width: 100%;_x000D_
  background-color: grey;_x000D_
.footer {_x000D_
  height: 2rem;_x000D_
  width: 100%;_x000D_
  background-color: yellow;_x000D_
  <div class="body">test as body</div>_x000D_
  <div class="footer">test as footer</div>_x000D_

this works by setting the height of the footer and then using css calc to work out the minimum height the page can be with the footer still at the bottom, hope this helps some people :)

Are loops really faster in reverse?

The way you're doing it now isn't faster (apart from it being an indefinite loop, I guess you meant to do i--.

If you want to make it faster do:

for (i = 10; i--;) {
    //super fast loop

of course you wouldn't notice it on such a small loop. The reason it's faster is because you're decrementing i while checking that it's "true" (it evaluates to "false" when it reaches 0)

Is there a color code for transparent in HTML?

#0000ffff - that is the code that you need for transparent. I just did it and it worked.

Error in plot.window(...) : need finite 'xlim' values

This error appears when the column contains character, if you check the data type it would be of type 'chr' converting the column to 'Factor' would solve this issue.

For e.g. In case you plot 'City' against 'Sales', you have to convert column 'City' to type 'Factor'

how to generate a unique token which expires after 24 hours?

you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.

To generate key refer here

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)



See javadoc:

 * Feature that determines whether parser will allow
 * JSON Strings to contain unescaped control characters
 * (ASCII characters with value less than 32, including
 * tab and line feed characters) or not.
 * If feature is set false, an exception is thrown if such a
 * character is encountered.
 * Since JSON specification requires quoting for all control characters,
 * this is a non-standard feature, and as such disabled by default.

Old option JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS was deprecated since 2.10.

Please see also github thread.

How to test a variable is null in python

You can do this in a try and catch block:

    if val is None:
except NameError:
    # throw an exception or do something else

Triggering a checkbox value changed event in DataGridView

I had the same issue, but came up with a different solution:

If you make the column or the whole grid "Read Only" so that when the user clicks the checkbox it doesn't change value.

Fortunately, the DataGridView.CellClick event is still fired. In my case I do the following in the cellClick event:

if (jM_jobTasksDataGridView.Columns[e.ColumnIndex].CellType.Name == "DataGridViewCheckBoxCell")

But you could check the column name if you have more than one checkbox column.

I then do all the modification / saving of the dataset myself.

MongoDb shuts down with Code 100

In MacOS:-

If you forgot to give the path of the previously created database while running the mongo server, the above error will appear.

sudo ./mongod --dbpath ../../mongo-data/


Note :- ./mongod && ../../mongo-data is relative path. So you can avoid it by configuration in environment variable


Why does PEP-8 specify a maximum line length of 79 characters?

Here's why I like the 80-character with: at work I use Vim and work on two files at a time on a monitor running at, I think, 1680x1040 (I can never remember). If the lines are any longer, I have trouble reading the files, even when using word wrap. Needless to say, I hate dealing with other people's code as they love long lines.

Getting the absolute path of the executable, using C#?

"Gets the path or UNC location of the loaded file that contains the manifest."



Access denied for root user in MySQL command-line

Gain access to a MariaDB 10 database server

After stopping the database server, the next step is to gain access to the server through a backdoor by starting the database server and skipping networking and permission tables. This can be done by running the commands below.

sudo mysqld_safe --skip-grant-tables --skip-networking &

Reset MariaDB root Password

Now that the database server is started in safe mode, run the commands below to logon as root without password prompt. To do that, run the commands below

sudo mysql -u root

Then run the commands below to use the mysql database.

use mysql;

Finally, run the commands below to reset the root password.

update user set password=PASSWORD("new_password_here") where User='root';

Replace new_password _here with the new password you want to create for the root account, then press Enter.

After that, run the commands below to update the permissions and save your changes to disk.

flush privileges;

Exit (CTRL + D) and you’re done.

Next start MariaDB normally and test the new password you just created.

sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service

Logon to the database by running the commands below.

sudo mysql -u root -p


How to create a horizontal loading progress bar?

It is Widget.ProgressBar.Horizontal on my phone, if I set android:indeterminate="true"

How to trigger checkbox click event even if it's checked through Javascript code?

You can use the jQuery .trigger() method. See



JVM option -Xss - What does it do exactly?

If I am not mistaken, this is what tells the JVM how much successive calls it will accept before issuing a StackOverflowError. Not something you wish to change generally.

Delete empty lines using sed

You may have spaces or tabs in your "empty" line. Use POSIX classes with sed to remove all lines containing only whitespace:

sed '/^[[:space:]]*$/d'

A shorter version that uses ERE, for example with gnu sed:

sed -r '/^\s*$/d'

(Note that sed does NOT support PCRE.)

How to add a tooltip to an svg graphic?

The only good way I found was to use Javascript to move a tooltip <div> around. Obviously this only works if you have SVG inside an HTML document - not standalone. And it requires Javascript.

function showTooltip(evt, text) {_x000D_
  let tooltip = document.getElementById("tooltip");_x000D_
  tooltip.innerHTML = text;_x000D_ = "block";_x000D_ = evt.pageX + 10 + 'px';_x000D_ = evt.pageY + 10 + 'px';_x000D_
function hideTooltip() {_x000D_
  var tooltip = document.getElementById("tooltip");_x000D_ = "none";_x000D_
#tooltip {_x000D_
  background: cornsilk;_x000D_
  border: 1px solid black;_x000D_
  border-radius: 5px;_x000D_
  padding: 5px;_x000D_
<div id="tooltip" display="none" style="position: absolute; display: none;"></div>_x000D_
  <rect width="100" height="50" style="fill: blue;" onmousemove="showTooltip(evt, 'This is blue');" onmouseout="hideTooltip();" >_x000D_

What is the difference between user variables and system variables?

Environment variable (can access anywhere/ dynamic object) is a type of variable. They are of 2 types system environment variables and user environment variables.

System variables having a predefined type and structure. That are used for system function. Values that produced by the system are stored in the system variable. They generally indicated by using capital letters Example: HOME,PATH,USER

User environment variables are the variables that determined by the user,and are represented by using small letters.

raw_input function in Python

Another example method, to mix the prompt using print, if you need to make your code simpler.


x = raw_input () -- This will return the user input as a string

x= int(raw_input()) -- Gets the input number as a string from raw_input() and then converts it to an integer using int().

print '\nWhat\'s your name ?', 
name = raw_input('--> ')
print '\nHow old are you, %s?' % name,
age = int(raw_input())
print '\nHow tall are you (in cms), %s?' % name,
height = int(raw_input())
print '\nHow much do you weigh (in kgs), %s?' % name,
weight = int(raw_input())

print '\nSo, %s is %d years old, %d cms tall and weighs %d kgs.\n' %(
name, age, height, weight)

Getting JSONObject from JSONArray

{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]

The get companyid, username, date;


GnuPG: "decryption failed: secret key not available" error from gpg on Windows

One more cause for the "secret key not available" message: GPG version mismatch.

Practical example: I had been using GPG v1.4. Switching packaging systems, the MacPorts supplied gpg was removed, and revealed another gpg binary in the path, this one version 2.0. For decryption, it was unable to locate the secret key and gave this very error. For encryption, it complained about an unusable public key. However, gpg -k and -K both listed valid keys, which was the cause of major confusion.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

This happened to me because I was using:


When I replaced url by jdbc-url then it worked:


Line Break in XML?

<description><![CDATA[first line<br/>second line<br/>]]></description>

How to remove the arrow from a select element in Firefox

If you don't mind fiddling with JS, I wrote a small jQuery plugin that helps you do it. With it you don't need to worry about vendor prefixes.

 $.fn.magicSelectBox = function() {
  var $e = this;

  $e.each(function() {
    var $select = $(this);

    var $magicbox = $('<div></div>').attr('class', $select.attr('class')).attr('style', $select.attr('style')).addClass('magicbox');
    var $innermagicbox = $('<div></div>').css({
      position: 'relative',
      height: '100%'
    var $text = $('<span></span>').css({
      position: 'absolute'

    $select.attr('class', null).css({
      width: '100%',
      height: '100%',
      opacity: 0,
      position: 'absolute'
    }).on('change', function() {

    $innermagicbox.append($text, $select);

  return $e;

Fiddle here: JS Fiddle

The condition is that you have to style the select from scratch (this means setting the background and border), but you probably want to do this anyway.

Also since the function substitutes the original select with a div, you will lose any styling done directly on the select selector in your CSS. So give the select element a class and style the class.

Supports most modern browsers, if you want to target older browsers, you can try an older version of jQuery, but perhaps have to replace on() with bind() in the function (not tested)

ie8 var w= - "Message: Invalid argument."

I also meet this issue while I used the following code:'test.html','Window title','width=1200,height=800,scrollbars=yes');

but when I delete the blank space of the "Window title" the below code is working:'test.html','Windowtitle','width=1200,height=800,scrollbars=yes');

How to recursively find the latest modified file in a directory?

find . -type f -printf '%T@ %p\n' \
| sort -n | tail -1 | cut -f2- -d" "

For a huge tree, it might be hard for sort to keep everything in memory.

%T@ gives you the modification time like a unix timestamp, sort -n sorts numerically, tail -1 takes the last line (highest timestamp), cut -f2 -d" " cuts away the first field (the timestamp) from the output.

Edit: Just as -printf is probably GNU-only, ajreals usage of stat -c is too. Although it is possible to do the same on BSD, the options for formatting is different (-f "%m %N" it would seem)

And I missed the part of plural; if you want more then the latest file, just bump up the tail argument.

How to save a data frame as CSV to a user selected location using tcltk

Take a look at the write.csv or the write.table functions. You just have to supply the file name the user selects to the file parameter, and the dataframe to the x parameter:

write.csv(x=df, file="myFileName")

Jenkins CI: How to trigger builds on SVN commit

You need to require only one plugin which is the Subversion plugin.

Then simply, go into Jenkins ? job_name ? Build Trigger section ? (i) Trigger build remotely (i.e., from scripts) Authentication token: Token_name

Go to the SVN server's hooks directory, and then after fire the below commands:

  1. cp post-commit.tmpl post-commit
  2. chmod 777 post-commit
  3. chown -R www-data:www-data post-commit
  4. vi post-commit

    Note: All lines should be commented Add the below line at last

Syntax (for Linux users):

/usr/bin/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name

Syntax (for Windows user):

C:/curl_for_win/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name

How to get value of selected radio button?

You can get the value by using the checked property.

var rates = document.getElementsByName('rate');
var rate_value;
for(var i = 0; i < rates.length; i++){
        rate_value = rates[i].value;

What is the best way to redirect a page using React Router?

You also can Redirect within the Route as follows. This is for handle invalid routes.

<Route path='*' render={() => 
       <Redirect to="/error"/>

How do you clone a Git repository into a specific folder?

To clone to Present Working Directory:

git clone

To clone to Another Directory:

git clone ./Folder1/Folder2

Hope it Helps :)

vuejs update parent data from child component

In Parent Conponent -->

data : function(){
            return {
                siteEntered : false, 

In Child Component -->

this.$parent.$data.siteEntered = true;

jquery can't get data attribute value

Iyap . Its work Case sensitive in data name data-x10

var variable = $('#myButton').data("x10"); // we get the value of custom data attribute

How to align flexbox columns left and right?

There are different ways but simplest would be to use the space-between see the example at the end

#container {    
    border: solid 1px #000;
    display: flex;    
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    height: 50px;

.item {
    width: 20%;
    border: solid 1px #000;
    text-align: center;

see the example

adding directory to sys.path /PYTHONPATH

Temporarily changing dirs works well for importing:

cwd = os.getcwd()
import <module>

commons httpclient - Adding query string parameters to GET/POST request

Here is how you would add query string parameters using HttpClient 4.2 and later:

URIBuilder builder = new URIBuilder("");
builder.setParameter("parts", "all").setParameter("action", "finish");

HttpPost post = new HttpPost(;

The resulting URI would look like:

Scraping data from website using vba

I modified some thing that were poping up error for me and end up with this which worked great to extract the data as I needed:

Sub get_data_web()

Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")

With appIE
    .navigate ""
    .Visible = True
End With

Do While appIE.Busy

Set allRowofData = appIE.document.getElementsByClassName("Ta(end) BdT Bdc($c-fuji-grey-c) H(36px)")

Dim i As Long
Dim myValue As String

Count = 1

    For Each itm In allRowofData

        For i = 0 To 4

        myValue = itm.Cells(i).innerText
        ActiveSheet.Cells(Count, i + 1).Value = myValue


        Count = Count + 1


Set appIE = Nothing

End Sub

numpy max vs amax vs maximum

np.maximum not only compares elementwise but also compares array elementwise with single value

>>>np.maximum([23, 14, 16, 20, 25], 18)
array([23, 18, 18, 20, 25])

Converting HTML to XML

Remember that HTML and XML are two distinct concepts in the tree of markup languages. You can't exactly replace HTML with XML . XML can be viewed as a generalized form of HTML, but even that is imprecise. You mainly use HTML to display data, and XML to carry(or store) the data.

This link is helpful: How to read HTML as XML?

More here - difference between HTML and XML

PHP function to get the subdomain of a URL

I know I'm really late to the game, but here goes.

What I did was take the HTTP_HOST server variable ($_SERVER['HTTP_HOST']) and the number of letters in the domain (so for it would be 11).

Then I used the substr function to get the subdomain. I did

$numberOfLettersInSubdomain = strlen($_SERVER['HTTP_HOST'])-12
$subdomain = substr($_SERVER['HTTP_HOST'], $numberOfLettersInSubdomain);

I cut the substring off at 12 instead of 11 because substrings start on 1 for the second parameter. So now if you entered, the value of $subdomain would be test.

This is better than using explode because if the subdomain has a . in it, this will not cut it off.

What is bootstrapping?

Alex, it's pretty much what your computer does when it boots up. ('Booting' a computer actually comes from the word bootstrapping)

Initially, the small program in your BIOS runs. That contains enough machine code to load and run a larger, more complex program.

That second program is probably something like NTLDR (in Windows) or LILO (in Linux), which then executes and is able to load, then run, the rest of the operating system.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

Here is a reference for using EXPLAIN PLAN with Oracle:, with specific information about the columns found here:

Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.

Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.

Random record from MongoDB

If you are using mongoose then you may use mongoose-random mongoose-random

Reading an image file in C/C++

If you decide to go for a minimal approach, without libpng/libjpeg dependencies, I suggest using stb_image and stb_image_write, found here.

It's as simple as it gets, you just need to place the header files stb_image.h and stb_image_write.h in your folder.

Here's the code that you need to read images:

#include <stdint.h>

#include "stb_image.h"

int main() {
    int width, height, bpp;

    uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);


    return 0;

And here's the code to write an image:

#include <stdint.h>

#include "stb_image_write.h"

#define CHANNEL_NUM 3

int main() {
    int width = 800; 
    int height = 800;

    uint8_t* rgb_image;
    rgb_image = malloc(width*height*CHANNEL_NUM);

    // Write your code to populate rgb_image here

    stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);

    return 0;

You can compile without flags or dependencies:

g++ main.cpp

Other lightweight alternatives include:

How to read the last row with SQL Server

You can use last_value: SELECT LAST_VALUE(column) OVER (PARTITION BY column ORDER BY column)...

I test it at one of my databases and it worked as expected.

You can also check de documentation here:

What to do with branch after merge

After the merge, it's safe to delete the branch:

git branch -d branch1

Additionally, git will warn you (and refuse to delete the branch) if it thinks you didn't fully merge it yet. If you forcefully delete a branch (with git branch -D) which is not completely merged yet, you have to do some tricks to get the unmerged commits back though (see below).

There are some reasons to keep a branch around though. For example, if it's a feature branch, you may want to be able to do bugfixes on that feature still inside that branch.

If you also want to delete the branch on a remote host, you can do:

git push origin :branch1

This will forcefully delete the branch on the remote (this will not affect already checked-out repositiories though and won't prevent anyone with push access to re-push/create it).

git reflog shows the recently checked out revisions. Any branch you've had checked out in the recent repository history will also show up there. Aside from that, git fsck will be the tool of choice at any case of commit-loss in git.

How to disable a particular checkstyle rule for a particular line of code?

<module name="Checker">
    <module name="SuppressionCommentFilter"/>
    <module name="TreeWalker">
        <module name="FileContentsHolder"/>

To configure a filter to suppress audit events between a comment containing line BEGIN GENERATED CODE and a comment containing line END GENERATED CODE:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="BEGIN GENERATED CODE"/>
  <property name="onCommentFormat" value="END GENERATED CODE"/>

public boolean equals(Object obj) { ... } // No violation events will be reported

public int hashCode() { ... } // No violation events will be reported

See more

Get Date Object In UTC format in Java

In java 8 , It's really easy to get timestamp in UTC by using java 8 java.time.Instant library :;

That few word of code will return the UTC Timestamp.

How to update Pandas from Anaconda and is it possible to use eclipse with this last

Simply type conda update pandas in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory). See this document for a detailed instruction.

Get value of Span Text

You need to change your code as below:


<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);

How to refresh datagrid in WPF

Bind you Datagrid to an ObservableCollection, and update your collection instead.

Using CSS to align a button bottom of the screen using relative positions

The below css code always keep the button at the bottom of the page


Since you want to do it in relative positioning, you should go for margin-top:100%


EDIT1: JSFiddle1

EDIT2: To place button at center of the screen,

left: 50%;



Generally, Postman used for debugging and used in the development phase. But in case you want to block it even from postman try this.

    const referrer_domain = "[enter-the-domain-name-of-the-referrer]"
    //check for the referrer domain
    app.all('/*', function(req, res, next) {
      if(req.headers.referer.indexOf(referrer_domain) == -1){
        res.send('Invalid Request')


How do I write a correct micro-benchmark in Java?

Make sure you somehow use results which are computed in benchmarked code. Otherwise your code can be optimized away.

Android Material and appcompat Manifest merger failed

Change proguardFile in build.gradle (Module: app) to the following

proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), ''

instead of

proguardFiles getDefaultProguardFile('proguard-android.txt'), ''

This worked for me

Select DataFrame rows between two dates

You can also use between:

df[df.some_date.between(start_date, end_date)]

how to make a full screen div, and prevent size to be changed by content?

Notice how most of these can only be used WITHOUT a DOCTYPE. I'm looking for the same answer, but I have a DOCTYPE. There is one way to do it with a DOCTYPE however, although it doesn't apply to the style of my site, but it will work on the type of page you want to create:

    position: absolute;

Now, this was mentioned earlier but I just wanted to clarify that this is normally used with a DOCTYPE, height:100%; only works without a DOCTYPE

get index of DataTable column with name

You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:

row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

How do I download/extract font from chrome developers tools?

To get .woff fonts first open the chrome dev tools panel (Ctrl+Shift+i) go to Network and reload the page. There you will see everything the page downloads. Find the .woff file, right click and select Copy response.

The response will be a url so paste it in the navigation bar. A file will be downloaded, just add the .woff extension to it and voila.

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

mysqli_error function requires $myConnection as parameters, that's why you get the warning

How do I generate a random integer between min and max in Java?

Using the Random class is the way to go as suggested in the accepted answer, but here is a less straight-forward correct way of doing it if you didn't want to create a new Random object :

min + (int) (Math.random() * (max - min + 1));

Should composer.lock be committed to version control?

You then commit the composer.json to your project and everyone else on your team can run composer install to install your project dependencies.

The point of the lock file is to record the exact versions that are installed so they can be re-installed. This means that if you have a version spec of 1.* and your co-worker runs composer update which installs 1.2.4, and then commits the composer.lock file, when you composer install, you will also get 1.2.4, even if 1.3.0 has been released. This ensures everybody working on the project has the same exact version.

This means that if anything has been committed since the last time a composer install was done, then, without a lock file, you will get new third-party code being pulled down.

Again, this is a problem if you’re concerned about your code breaking. And it’s one of the reasons why it’s important to think about Composer as being centered around the composer.lock file.

Source: Composer: It’s All About the Lock File.

Commit your application's composer.lock (along with composer.json) into version control. This is important because the install command checks if a lock file is present, and if it is, it downloads the versions specified there (regardless of what composer.json says). This means that anyone who sets up the project will download the exact same version of the dependencies. Your CI server, production machines, other developers in your team, everything and everyone runs on the same dependencies, which mitigates the potential for bugs affecting only some parts of the deployments. Even if you develop alone, in six months when reinstalling the project you can feel confident the dependencies installed are still working even if your dependencies released many new versions since then.

Source: Composer - Basic Usage.

jQuery ajax request being block because Cross-Origin

I solved this by changing the file path in the browser:

  • Instead of: c/XAMPP/htdocs/myfile.html
  • I wrote: localhost/myfile.html

Get list of all input objects using JavaScript, without accessing a form object

var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
  // ...

Handling the TAB character in Java

You can also use the tab character '\t' to represent a tab, instead of "\t".

char c ='t';
char c =(char)9;

Generating 8-character only UUIDs

I do not think that it is possible but you have a good workaround.

  1. cut the end of your UUID using substring()
  2. use code new Random(System.currentTimeMillis()).nextInt(99999999); this will generate random ID up to 8 characters long.
  3. generate alphanumeric id:

    char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
    Random r = new Random(System.currentTimeMillis());
    char[] id = new char[8];
    for (int i = 0;  i < 8;  i++) {
        id[i] = chars[r.nextInt(chars.length)];
    return new String(id);

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")

edit: use input in python 3.2 instead of raw_input

How to concatenate properties from multiple JavaScript objects

Probably, the fastest, efficient and more generic way is this (you can merge any number of objects and even copy to the first one ->assign):

function object_merge(){
    for (var i=1; i<arguments.length; i++)
       for (var a in arguments[i])
         arguments[0][a] = arguments[i][a];
   return arguments[0];

It also allows you to modify the first object as it passed by reference. If you don't want this but want to have a completely new object containing all properties, then you can pass {} as the first argument.

var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge(object1,object2,object3); 

combined_object and object1 both contain the properties of object1,object2,object3.

var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge({},object1,object2,object3); 

In this case, the combined_object contains the properties of object1,object2,object3 but object1 is not modified.

Check here:

Note: JavaScript objects are passed by reference.

Simulate a click on 'a' element using javascript/jquery

Using jQuery:


Aligning textviews on the left and right edges in Android layout

enter image description here

This Code will Divide the control into two equal sides.

        android:text = "Left Side"
        android:layout_weight = "1"
        android:id = "@+id/txtLeft"/>

    <TextView android:text = "Right Side"
        android:layout_weight = "1"
        android:id = "@+id/txtRight"/>

How to solve npm install throwing fsevents warning on non-MAC OS?

fsevents is dealt differently in mac and other linux system. Linux system ignores fsevents whereas mac install it. As the above error message states that fsevents is optional and it is skipped in installation process.

You can run npm install --no-optional command in linux system to avoid above warning.

Further information

Printing HashMap In Java

A simple way to see the key value pairs:

Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
System.out.println(Arrays.asList(map)); // method 1
System.out.println(Collections.singletonList(map)); // method 2

Both method 1 and method 2 output this:

[{b=2, a=1}]

Jquery click not working with ipad

Probably rather than defining both the events click and touch you could define a an handler which will look if the device will work with click or touch.

var handleClick= 'ontouchstart' in document.documentElement ? 'touchstart': 'click';
alert('Click is now working with touch and click both');

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

In Android Studio I was trying to set the compileSdkVersion and targetSdkVersion to 19.

My solution was to replace at the bottom of build.gradle, from this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile ''

To the older version of the appcompat library:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile ''

How to view the roles and permissions granted to any database user in Azure SQL server instance?

To view database roles assigned to users, you can use sys.database_role_members

The following query returns the members of the database roles.

SELECT AS DatabaseRoleName,   
    isnull (, 'No members') AS DatabaseUserName   
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

If you have multiple Java versions installed on your Mac, here's a quick way to switch the default version using Terminal. In this example, I am going to switch Java 10 to Java 8.

$ java -version
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    10.0.1, x86_64: "Java SE 10.0.1"    /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
    1.8.0_171, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home


Then, in your .bash_profile add the following.

# Java 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home

Now if you try java -version again, you should see the version you want.

$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)

How to get input type using jquery?

The best place to start looking is

This will give you a good set of examples.

Ultamatly the selecting of elements in the DOM is achived using CSS selectors so if you think about getting an element by id you will want to use $('#elementId'), if you want all the input tags use $('input') and finaly the part i think you'll want if you want all input tags with a type of checkbox use $('input, [type=checkbox])

Note: You'll find most of the values you want are on attributes so the css selector for attributes is: [attributeName=value]

Just because you asked for the dropdown as aposed to a listbox try the following:

$('select, [size]).each(function(){
  var selectedItem = $('select, [select]', this).first();

The code was from memory so please accound for small errors

How to return a table from a Stored Procedure?

Where is your problem??

For the stored procedure, just create:

   SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
   FROM dbo.Emp
   WHERE ID = @EmpID

That's all there is.

From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

DataTable tblEmployees = new DataTable();

using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
    _cmd.CommandType = CommandType.StoredProcedure;

    _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
    _cmd.Parameters["@EmpID"].Value = 42;

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);


YourGridView.DataSource = tblEmployees;

and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

How to make a GridLayout fit screen size

Note: The information below the horizontal line is no longer accurate with the introduction of Android 'Lollipop' 5, as GridLayout does accommodate the principle of weights since API level 21.

Quoted from the Javadoc:

Excess Space Distribution

As of API 21, GridLayout's distribution of excess space accomodates the principle of weight. In the event that no weights are specified, the previous conventions are respected and columns and rows are taken as flexible if their views specify some form of alignment within their groups. The flexibility of a view is therefore influenced by its alignment which is, in turn, typically defined by setting the gravity property of the child's layout parameters. If either a weight or alignment were defined along a given axis then the component is taken as flexible in that direction. If no weight or alignment was set, the component is instead assumed to be inflexible.

Multiple components in the same row or column group are considered to act in parallel. Such a group is flexible only if all of the components within it are flexible. Row and column groups that sit either side of a common boundary are instead considered to act in series. The composite group made of these two elements is flexible if one of its elements is flexible.

To make a column stretch, make sure all of the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity.

When the principle of flexibility does not provide complete disambiguation, GridLayout's algorithms favour rows and columns that are closer to its right and bottom edges. To be more precise, GridLayout treats each of its layout parameters as a constraint in the a set of variables that define the grid-lines along a given axis. During layout, GridLayout solves the constraints so as to return the unique solution to those constraints for which all variables are less-than-or-equal-to the corresponding value in any other valid solution.

It's also worth noting that contains the same information. Unfortunately it doesn't mention which version of the support library it was introduced with, but the commit that adds the functionality can be tracked back to July 2014. In November 2014, improvements in weight calculation and a bug was fixed.

To be safe, make sure to import the latest version of the gridlayout-v7 library.

The principle of 'weights', as you're describing it, does not exist with GridLayout. This limitation is clearly mentioned in the documentation; excerpt below. That being said, there are some possibilities to use 'gravity' for excess space distribution. I suggest you have read through the linked documentation.


GridLayout does not provide support for the principle of weight, as defined in weight. In general, it is not therefore possible to configure a GridLayout to distribute excess space in non-trivial proportions between multiple rows or columns. Some common use-cases may nevertheless be accommodated as follows. To place equal amounts of space around a component in a cell group; use CENTER alignment (or gravity). For complete control over excess space distribution in a row or column; use a LinearLayout subview to hold the components in the associated cell group. When using either of these techniques, bear in mind that cell groups may be defined to overlap.

For an example and some practical pointers, take a look at last year's blog post introducing the GridLayout widget.

Edit: I don't think there's an xml-based approach to scaling the tiles like in the Google Play app to 'squares' or 'rectangles' twice the length of those squares. However, it is certainly possible if you build your layout programmatically. All you really need to know in order two accomplish that is the device's screen dimensions.

Below a (very!) quick 'n dirty approximation of the tiled layout in the Google Play app.

Point size = new Point();
int screenWidth = size.x;
int screenHeight = size.y;
int halfScreenWidth = (int)(screenWidth *0.5);
int quarterScreenWidth = (int)(halfScreenWidth * 0.5);

Spec row1 = GridLayout.spec(0, 2);
Spec row2 = GridLayout.spec(2);
Spec row3 = GridLayout.spec(3);
Spec row4 = GridLayout.spec(4, 2);

Spec col0 = GridLayout.spec(0);
Spec col1 = GridLayout.spec(1); 
Spec colspan2 = GridLayout.spec(0, 2);

GridLayout gridLayout = new GridLayout(this);

TextView twoByTwo1 = new TextView(this);
GridLayout.LayoutParams first = new GridLayout.LayoutParams(row1, colspan2);
first.width = screenWidth;
first.height = quarterScreenWidth * 2;
gridLayout.addView(twoByTwo1, first);

TextView twoByOne1 = new TextView(this);
GridLayout.LayoutParams second = new GridLayout.LayoutParams(row2, col0);
second.width = halfScreenWidth;
second.height = quarterScreenWidth;
twoByOne1.setText("Staff Choices");
gridLayout.addView(twoByOne1, second);

TextView twoByOne2 = new TextView(this);
GridLayout.LayoutParams third = new GridLayout.LayoutParams(row2, col1);
third.width = halfScreenWidth;
third.height = quarterScreenWidth;
gridLayout.addView(twoByOne2, third);

TextView twoByOne3 = new TextView(this);
GridLayout.LayoutParams fourth = new GridLayout.LayoutParams(row3, col0);
fourth.width = halfScreenWidth;
fourth.height = quarterScreenWidth;
twoByOne3.setText("Editor's Choices");
gridLayout.addView(twoByOne3, fourth);

TextView twoByOne4 = new TextView(this);
GridLayout.LayoutParams fifth = new GridLayout.LayoutParams(row3, col1);
fifth.width = halfScreenWidth;
fifth.height = quarterScreenWidth;
twoByOne4.setText("Something Else");
gridLayout.addView(twoByOne4, fifth);

TextView twoByTwo2 = new TextView(this);
GridLayout.LayoutParams sixth = new GridLayout.LayoutParams(row4, colspan2);
sixth.width = screenWidth;
sixth.height = quarterScreenWidth * 2;
gridLayout.addView(twoByTwo2, sixth);

The result will look somewhat like this (on my Galaxy Nexus):

Tiled layout using GridLayout

How can a query multiply 2 cell for each row MySQL?

You can do it with:

UPDATE mytable SET Total = Pieces * Price;

How to change menu item text dynamically in Android

I needed to change the menu icon for the fragment. I altered Charles’s answer to this question a bit for the fragment:

    private Menu top_menu;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

       rootview = inflater.inflate(R.layout.first_content,null);

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(, menu);
        this.top_menu = menu;

    // my procedure
    private void updateIconMenu() {
         if(top_menu!= null) {
             MenuItem nav_undo = top_menu.findItem(;
             nav_undo.setIcon( R.drawable.back);

Struct like objects in Java

I frequently use this pattern when building private inner classes to simplify my code, but I would not recommend exposing such objects in a public API. In general, the more frequently you can make objects in your public API immutable the better, and it is not possible to construct your 'struct-like' object in an immutable fashion.

As an aside, even if I were writing this object as a private inner class I would still provide a constructor to simplify the code to initialize the object. Having to have 3 lines of code to get a usable object when one will do is just messy.

What is the purpose of using WHERE 1=1 in SQL statements?

As you said:

if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.