Programs & Examples On #Libmysql

Libmysql is a client library for connecting C written application to MySql.

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

Ubuntu apt-get unable to fetch packages

I tried this really interesting solution today, which worked for me on an Ubuntu server. Some DNS or another issue in the apt was making it adamant to not installing some packages from a custom PPA. What I did was install the apt-fast package and use it to install my packages instead of apt.

apt-fast is an alternative to apt which works on top of apt but uses aria2c to download packages. It is used to increase the download speed. In my case, it also solved whatever network problem was making apt to fail.

Using it is exactly the same as apt:

sudo apt-fast install package-name

mysql.h file can't be found

this worked for me

$ gcc dbconnect.c -o dbconnect -lmysqlclient
$ ./dbconnect

-lmysqlclient is must.

and i would personally recommend to use following notation instead of using -I compilation flag.

#include <mysql/mysql.h>

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

On Mac Sierra if using Homebrew then do:

sudo ln -s /usr/local/Cellar/[email protected]/5.6.34/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

Why do I get permission denied when I try use "make" to install something?

I had a very similar error message as you, although listing a particular file:

$ make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127

$ sudo make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127

In my case, I forgot to add a trailing slash to indicate continuation of the line as shown:

${LINEDETECTOR_OBJECTS}:\
    ../HoughLineAccumulator/houghlineaccumulator.hh  # <-- missing slash!!
    ../HoughLineExtractor/houghlineextractor.hh

Hope that helps someone else who lands here from a search engine.

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I found there was another solution for this problem rather than creating a symbolic link.

You set the path to your directory, where libmysqlclient.18.dylib resides, to DYLD_LIBRARY_PATH environment variable. What I did is to put following line in my .bash_profile:

export DYLD_LIBRARY_PATH=/usr/local/mysql-5.5.15-osx10.6-x86/lib/:$DYLD_LIBRARY_PATH

That's it.

Error: free(): invalid next size (fast):

It means that you have a memory error. You may be trying to free a pointer that wasn't allocated by malloc (or delete an object that wasn't created by new) or you may be trying to free/delete such an object more than once. You may be overflowing a buffer or otherwise writing to memory to which you shouldn't be writing, causing heap corruption.

Any number of programming errors can cause this problem. You need to use a debugger, get a backtrace, and see what your program is doing when the error occurs. If that fails and you determine you have corrupted the heap at some previous point in time, you may be in for some painful debugging (it may not be too painful if the project is small enough that you can tackle it piece by piece).

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I have solved this, eventually!

I re-installed Ruby and Rails under RVM. I'm using Ruby version 1.9.2-p136.

After re-installing under rvm, this error was still present.

In the end the magic command that solved it was:

sudo install_name_tool -change libmysqlclient.16.dylib /usr/local/mysql/lib/libmysqlclient.16.dylib ~/.rvm/gems/ruby-1.9.2-p136/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle

Hope this helps someone else!

Prevent Android activity dialog from closing on outside touch

I was facing the same problem. To handle it I set a OntouchListener to the dialog and do nothing inside. But Dialog dismiss when rotating screen too. To fix it I set a variable to tell me if the dialog has normally dismissed. Then I set a OnDismissListener to my dialog and inside I check the variable. If the dialog has dismmiss normally I do nothin, or else I run the dialog again (and setting his state as when dismissing in my case).

How to go to each directory and execute a command?

You can do the following, when your current directory is parent_directory:

for d in [0-9][0-9][0-9]
do
    ( cd "$d" && your-command-here )
done

The ( and ) create a subshell, so the current directory isn't changed in the main script.

Microsoft SQL Server 2005 service fails to start

To solve this problem, you may need to repair your SQL Server 2005

Simple steps can be

  1. Update/Install .Net 2.0 framework. Windows Installer 3.1 available online recommended
  2. Download the setup files from Microsoft website : http://www.microsoft.com/en-in/download/details.aspx?id=184
  3. Follow the steps mentioned below from the Symantec website: http://www.symantec.com/connect/articles/install-and-configure-sql-server-2005-express

Hope this helps!

Foreign Key to non-primary key

If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it.

From Books Online:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

So in your case if you make AnotherID unique, it will be allowed. If you can't apply a unique constraint you're out of luck, but this really does make sense if you think about it.

Although, as has been mentioned, if you have a perfectly good primary key as a candidate key, why not use that?

How to reduce the image file size using PIL

See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS filter when you do.

Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.

How to style components using makeStyles and still have lifecycle methods in Material UI?

I used withStyles instead of makeStyle

EX :

import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";

const useStyles = theme => ({
        root: {
           flexGrow: 1,
         },
  });

class App extends Component {
       render() {
                const { classes } = this.props;
                return(
                    <div className={classes.root}>
                       Test
                </div>
                )
          }
} 

export default withStyles(useStyles)(App)

CSS transition effect makes image blurry / moves image 1px, in Chrome?

Had the same problem with embeded youtube iframe (Translations were used for centering iframe element). None of the solutions above worked until tried reset css filters and magic happened.

Structure:

<div class="translate">
     <iframe/>
</div>

Style [before]

.translate {
  transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
}

Style [after]

.translate {
  transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
  filter: blur(0);
  -webkit-filter: blur(0);
}

How to find out what is locking my tables?

A colleague and I have created a tool just for this. It's a visual representation of all the locks that your sessions produce. Give it a try (http://www.sqllockfinder.com), it's open source (https://github.com/LucBos/SqlLockFinder)

Getting Textbox value in Javascript

<script type="text/javascript" runat="server">
 public void Page_Load(object Sender, System.EventArgs e)
    {
        double rad=0.0;
        TextBox1.Attributes.Add("Visible", "False");
        if (TextBox1.Text != "") 
        rad = Convert.ToDouble(TextBox1.Text);    
        Button1.Attributes.Add("OnClick","alert("+ rad +")");
    }
</script>

<asp:Button ID="Button1" runat="server" Text="Diameter" 
            style="z-index: 1; left: 133px; top: 181px; position: absolute" />
<asp:TextBox ID="TextBox1" Visible="True" Text="" runat="server" 
            AutoPostBack="true" 
            style="z-index: 1; left: 134px; top: 133px; position: absolute" ></asp:TextBox>

use the help of this, hope it will be usefull

How can I reverse a NSArray in Objective-C?

Try this:

for (int i = 0; i < [arr count]; i++)
{
    NSString *str1 = [arr objectAtIndex:[arr count]-1];
    [arr insertObject:str1 atIndex:i];
    [arr removeObjectAtIndex:[arr count]-1];
}

Tool for sending multipart/form-data request

The usual error is one tries to put Content-Type: {multipart/form-data} into the header of the post request. That will fail, it is best to let Postman do it for you. For example:

Suggestion To Load Via Postman Body Part

Fails If In Header Common Error

Works should remove content type from the Header

IF... OR IF... in a windows batch file

Never got exist to work.

I use if not exist g:xyz/what goto h: Else xcopy c:current/files g:bu/current There are modifiers /a etc. Not sure which ones. Laptop in shop. And computer in office. I am not there.

Never got batch files to work above Windows XP

How can I view an old version of a file with Git?

If you like GUIs, you can use gitk:

  1. start gitk with:

    gitk /path/to/file
    
  2. Choose the revision in the top part of the screen, e.g. by description or date. By default, the lower part of the screen shows the diff for that revision, (corresponding to the "patch" radio button).

  3. To see the file for the selected revision:

    • Click on the "tree" radio button. This will show the root of the file tree at that revision.
    • Drill down to your file.

What does MVW stand for?

I feel that MWV (Model View Whatever) or MV* is a more flexible term to describe some of the uniqueness of Angularjs in my opinion. It helped me to understand that it is more than a MVC (Model View Controller) JavaScript framework, but it still uses MVC as it has a Model View, and Controller.

It also can be considered as a MVP (Model View Presenter) pattern. I think of a Presenter as the user-interface business logic in Angularjs for the View. For example by using filters that can format data for display. It's not business logic, but display logic and it reminds me of the MVP pattern I used in GWT.

In addition, it also can be a MVVM (Model View View Model) the View Model part being the two-way binding between the two. Last of all it is MVW as it has other patterns that you can use as well as mentioned by @Steve Chambers.

I agree with the other answers that getting pedantic on these terms can be detrimental, as the point is to understand the concepts from the terms, but by the same token, fully understanding the terms helps one when they are designing their application code, knowing what goes where and why.

Capitalize the first letter of string in AngularJs

a nicer way

app.filter('capitalize', function() {
  return function(token) {
      return token.charAt(0).toUpperCase() + token.slice(1);
   }
});

Construct pandas DataFrame from list of tuples of (row,col,values)

I submit that it is better to leave your data stacked as it is:

df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])

# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])

Then it's a bit more intuitive to say

df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)

This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot, it's purely based on column convention as to what semantic entity it is that you are reshaping.

How to delete Tkinter widgets from a window?

I found that when the widget is part of a function and the grid_remove is part of another function it does not remove the label. In this example...

def somefunction(self):
    Label(self, text=" ").grid(row = 0, column = 0)
    self.text_ent = Entry(self)
    self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
    somefunction.text_ent.grid_remove()

...there is no valid way of removing the Label.

The only solution I could find is to give the label a name and make it global:

def somefunction(self):
    global label
    label = Label(self, text=" ")
    label.grid(row = 0, column = 0)
    self.text_ent = Entry(self)
    self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
    global label
    somefunction.text_ent.grid_remove()
    label.grid_remove()

When I ran into this problem there was a class involved, one function being in the class and one not, so I'm not sure the global label lines are really needed in the above.

How to select the row with the maximum value in each group

Here's a data.table solution:

require(data.table) ## 1.9.2
group <- as.data.table(group)

If you want to keep all the entries corresponding to max values of pt within each group:

group[group[, .I[pt == max(pt)], by=Subject]$V1]
#    Subject pt Event
# 1:       1  5     2
# 2:       2 17     2
# 3:       3  5     2

If you'd like just the first max value of pt:

group[group[, .I[which.max(pt)], by=Subject]$V1]
#    Subject pt Event
# 1:       1  5     2
# 2:       2 17     2
# 3:       3  5     2

In this case, it doesn't make a difference, as there aren't multiple maximum values within any group in your data.

Convert InputStream to byte array in Java

In new version,

IOUtils.readAllBytes(inputStream)

Pandas: Appending a row to a dataframe and specify its index label

I shall refer to the same sample of data as posted in the question:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))

Running this code will give you

The original data frame is:

          A         B         C         D
0  0.494824 -0.328480  0.818117  0.100290
1  0.239037  0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856  0.359811 -0.345560
3 -0.070814 -0.394711  0.081697 -1.178845
4 -1.638063  1.498027 -0.609325  0.882594
5 -0.510217  0.500475  1.039466  0.187076
6  1.116529  0.912380  0.869323  0.119459
7 -1.046507  0.507299 -0.373432 -1.024795

Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append returns a view of the dataframe and does not modify its contents. Following is the code:

row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))

Following would be the new output:

The new data frame is:

           A          B          C          D
0   0.494824  -0.328480   0.818117   0.100290
1   0.239037   0.954912  -0.186825  -0.651935
2  -1.818285  -0.158856   0.359811  -0.345560
3  -0.070814  -0.394711   0.081697  -1.178845
4  -1.638063   1.498027  -0.609325   0.882594
5  -0.510217   0.500475   1.039466   0.187076
6   1.116529   0.912380   0.869323   0.119459
7  -1.046507   0.507299  -0.373432  -1.024795
3  10.000000  20.000000  30.000000  40.000000

The character encoding of the HTML document was not declared

I had the same problem when I ran my form application in Firefox. Adding <meta charset="utf-8"/> in the html code solved my issue in Firefox.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title>Voice clip upload</title>_x000D_
  <script src="voiceclip.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <h2>Upload Voice Clip</h2>_x000D_
  <form id="upload_form" enctype="multipart/form-data" method="post">_x000D_
    <input type="file" name="file1" id="file1" onchange="uploadFile()"><br>_x000D_
    <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>_x000D_
  </form>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How is the default submit button on an HTML form determined?

From the HTML 4 spec:

If a form contains more than one submit button, only the activated submit button is successful.

This means that given more than 1 submit button and none activated (clicked), none should be successful.

And I'd argue this makes sense: Imagine a huge form with multiple submit-buttons. At the top, there is a "delete this record"-button, then lots of inputs follow and at the bottom there is an "update this record"-button. A user hitting enter while in a field at the bottom of the form would never suspect that he implicitly hits the "delete this record" from the top.

Therefore I think it is not a good idea to use the first or any other button it the user does not define (click) one. Nevertheless, browsers are doing it of course.

How to play or open *.mp3 or *.wav sound file in c++ program?

If you want to play the *.mp3 or *.wav file, i think the easiest way would be to use SFML.

Using SVG as background image

With my solution you're able to get something similar:

svg background image css

Here is bulletproff solution:

Your html: <input class='calendarIcon'/>

Your SVG: i used fa-calendar-alt

fa-calendar-alt

(any IDE may open svg image as shown below)

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>

To use it at css background-image you gotta encode the svg to address valid string. I used this tool

As far as you got all stuff you need, you're coming to css

.calendarIcon{
      //your url will be something like this:
      background-image: url("data:image/svg+xml,***<here place encoded svg>***");
      background-repeat: no-repeat;
    }

Note: these styling wont have any effect on encoded svg image

.{
      fill: #f00; //neither this
      background-color: #f00; //nor this
}

because all changes over the image must be applied directly to its svg code

<svg xmlns="" path="" fill="#f00"/></svg>

To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:

.calendarIcon{
      background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
      background-repeat: no-repeat;
      padding-right: calc(1.5em + 0.75rem);
      background-position: center right calc(0.375em + 0.1875rem);
      background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
    }

What is the best way to access redux store outside a react component?

Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute the global window space.

MyStore.js

const store = createStore(myReducer);
export store;

or

const store = createStore(myReducer);
export default store;

MyClient.js

import {store} from './MyStore'
store.dispatch(...)

or if you used default

import store from './MyStore'
store.dispatch(...)

For Multiple Store Use Cases

If you need multiple instances of a store, export a factory function. I would recommend making it async (returning a promise).

async function getUserStore (userId) {
   // check if user store exists and return or create it.
}
export getUserStore

On the client (in an async block)

import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

Thanks for the answers guys. My problem was that I changed a x64 solution in Visual Studio to 32 bit in the Configuration Manager only. I ended up just creating a new solution as 32 bit and then copying my C++ code and this error was gone. I think l00g33k and RogerAttrill's suggestions may have been the solution, but mine worked, too.

How to pass credentials to the Send-MailMessage command for sending emails

It took me a while to combine everything, make it a bit secure, and have it work with Gmail. I hope this answer saves someone some time.

Create a file with the encrypted server password:

In Powershell, enter the following command (replace myPassword with your actual password):

"myPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\EmailPassword.txt"

Create a powershell script (Ex. sendEmail.ps1):

$User = "[email protected]"
$File = "C:\EmailPassword.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)
$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Email Subject" 
$Body = "Email body text" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\fileIwantToSend.csv"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password); 
$SMTPClient.Send($SMTPMessage)

Automate with Task Scheduler:

Create a batch file (Ex. emailFile.bat) with the following:

powershell -ExecutionPolicy ByPass -File C:\sendEmail.ps1

Create a task to run the batch file. Note: you must have the task run with the same user account that you used to encrypted the password! (Aka, probably the logged in user)

That's all; you now have a way to automate and schedule sending an email and an attachment with Windows Task Scheduler and Powershell. No 3rd party software and the password is not stored as plain text (though granted, not terribly secure either).

You can also read this article on the level of security this provides for your email password.

How to send HTTP request in java?

Here's a complete Java 7 program:

class GETHTTPResource {
  public static void main(String[] args) throws Exception {
    try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://tools.ietf.org/rfc/rfc768.txt").openStream())) {
      System.out.println(s.useDelimiter("\\A").next());
    }
  }
}

The new try-with-resources will auto-close the Scanner, which will auto-close the InputStream.

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Instead of

return new ResponseEntity<JSONObject>(entities, HttpStatus.OK);

try

return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);

await vs Task.Wait - Deadlock?

Wait and await - while similar conceptually - are actually completely different.

Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. As a general rule, you should use "async all the way down"; that is, don't block on async code. On my blog, I go into the details of how blocking in asynchronous code causes deadlock.

await will asynchronously wait until the task completes. This means the current method is "paused" (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation.

You also mentioned a "cooperative block", by which I assume you mean a task that you're Waiting on may execute on the waiting thread. There are situations where this can happen, but it's an optimization. There are many situations where it can't happen, like if the task is for another scheduler, or if it's already started or if it's a non-code task (such as in your code example: Wait cannot execute the Delay task inline because there's no code for it).

You may find my async / await intro helpful.

update query with join on two tables

Using table aliases in the join condition:

update addresses a
set cid = b.id 
from customers b 
where a.id = b.id

Apply vs transform on a group object

tmp = df.groupby(['A'])['c'].transform('mean')

is like

tmp1 = df.groupby(['A']).agg({'c':'mean'})
tmp = df['A'].map(tmp1['c'])

or

tmp1 = df.groupby(['A'])['c'].mean()
tmp = df['A'].map(tmp1)

ASP.NET MVC3 - textarea with @Html.EditorFor

Someone asked about adding attributes (specifically, 'rows' and 'cols'). If you're using Razor, you could just do this:

@Html.TextAreaFor(model => model.Text, new { cols = 35, @rows = 3 })

That works for me. The '@' is used to escape keywords so they are treated as variables/properties.

How to get your Netbeans project into Eclipse

Sharing my experience, how to import simple Netbeans java project into Eclipse workspace. Please follow the following steps:

  1. Copy the Netbeans project folder into Eclipse workspace.
  2. Create .project file, inside the project folder at root level. Below code is the sample reference. Change your project name appropriately.

    <?xml version="1.0" encoding="UTF-8"?>
    <projectDescription>
        <name>PROJECT_NAME</name>
        <comment></comment>
        <projects>
        </projects>
        <buildSpec>
            <buildCommand>
                <name>org.eclipse.jdt.core.javabuilder</name>
                <arguments>
                </arguments>
            </buildCommand>
        </buildSpec>
        <natures>
            <nature>org.eclipse.jdt.core.javanature</nature>
        </natures>
    </projectDescription>
    
  3. Now open Eclipse and follow the steps,

    File > import > Existing Projects into Workspace > Select root directory > Finish

  4. Now we need to correct the build path for proper compilation of src, by following these steps:

    Right Click on project folder > Properties > Java Build Path > Click Source tab > Add Folder

(Add the correct src path from project and remove the incorrect ones). Find the image ref link how it looks.

  1. You are done. Let me know for any queries. Thanks.

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

I know this post was about 11g, but a bug in the 12c client with how it encrypts passwords may be to blame for this error if you decide to use that one and you:

  • Don't have the password case-sensitivity issue (i.e. you tried ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE and resetting the password and still doesn't work),
  • Put quotes around your password in your connection string and it still doesn't help,
  • You've verified all of your environmental variables (ORACLE_HOME, PATH, TNS_ADMIN), and the TNS_ADMIN registry string at HKLM\Software\Oracle\KEY_OraClient12Home is in place,
  • You've verified your connection string and user name/password combination works in Net Manager, and
  • You can connect using SQL*Plus, Oracle SQL Developer using the same credentials.

All the basic checks.

Fix: Try setting HKLM\System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy\Enabled to 0 in the registry (regedit) to disable FIPS.

Oracle.ManagedDataAccess and ORA-01017: invalid username/password; logon denied

ORA-01005 error connecting with ODP.Net

https://community.oracle.com/thread/2557592?start=0&tstart=0

https://dba.stackexchange.com/questions/142085/ora-01017-invalid-username-passwordlogon-denied/142149#142149

jquery select option click handler

One possible solution is to add a class to every option

<select name="export_type" id="export_type">
    <option class="export_option" value="pdf">PDF</option>
    <option class="export_option" value="xlsx">Excel</option>
    <option class="export_option" value="docx">DocX</option>
</select>

and then use the click handler for this class

$(document).ready(function () {

    $(".export_option").click(function (e) {
        //alert('click');
    });

});

UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome. Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.

Checking cin input stream produces an integer

You can check like this:

int x;
cin >> x;

if (cin.fail()) {
    //Not an int.
}

Furthermore, you can continue to get input until you get an int via:

#include <iostream>



int main() {

    int x;
    std::cin >> x;
    while(std::cin.fail()) {
        std::cout << "Error" << std::endl;
        std::cin.clear();
        std::cin.ignore(256,'\n');
        std::cin >> x;
    }
    std::cout << x << std::endl;

    return 0;
}

EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).

#include <iostream>
#include <string>

int main() {

    std::string theInput;
    int inputAsInt;

    std::getline(std::cin, theInput);

    while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {

        std::cout << "Error" << std::endl;

        if( theInput.find_first_not_of("0123456789") == std::string::npos) {
            std::cin.clear();
            std::cin.ignore(256,'\n');
        }

        std::getline(std::cin, theInput);
    }

    std::string::size_type st;
    inputAsInt = std::stoi(theInput,&st);
    std::cout << inputAsInt << std::endl;
    return 0;
}

getting the screen density programmatically in android?

Actualy if you want to have the real display dpi the answer is somewhere in between if you query for display metrics:

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int dpiClassification = dm.densityDpi;
float xDpi = dm.xdpi;
float yDpi = dm.ydpi;

densityDpi * 160 will give you the values/suggestion which density you should use

0.75 - ldpi - 120 dpi
1.0 - mdpi - 160 dpi
1.5 - hdpi - 240 dpi
2.0 - xhdpi - 320 dpi
3.0 - xxhdpi - 480 dpi
4.0 - xxxhdpi - 640 dpi

as specified in previous posts

but dm.xdpi won't give you always the REAL dpi of given display: Example:

Device: Sony ericsson xperia mini pro (SK17i)
Density: 1.0 (e.g. suggests you use 160dpi resources)
xdpi: 193.5238
Real device ppi is arround 193ppi


Device: samsung GT-I8160 (Samsung ace 2)
Density 1.5 (e.g. suggests you use 240dpi resources)
xdpi 160.42105
Real device ppi is arround 246ppi

so maybe real dpi of the display should be Density*xdpi .. but i'm not sure if this is the correct way to do!

How to create empty folder in java?

You can create folder using the following Java code:

File dir = new File("nameoffolder");
dir.mkdir();

By executing above you will have folder 'nameoffolder' in current folder.

How to dynamically remove items from ListView on a button click?

Well you just remove the desired item from the list using the remove() method of your ArrayAdapter.

A possible way to do that would be:

Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);

Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.

arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();

json_encode(): Invalid UTF-8 sequence in argument

Updated.. I solved this issue by stating the charset on PDO connection as below:

"mysql:host=$host;dbname=$db;charset=utf8"

All data received was then in the correct charset for the rest of the code to use

How can I correctly format currency using jquery?

Another option (If you are using ASP.Net razor view) is, On your view you can do

<div>@String.Format("{0:C}", Model.total)</div>

This would format it correctly. note (item.total is double/decimal)

if in jQuery you can also use Regex

$(".totalSum").text('$' + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());

Better way to Format Currency Input editText?

I got this from here and changed it to comply with Portuguese currency format.

import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class CurrencyTextWatcher implements TextWatcher {

    private String current = "";
    private int index;
    private boolean deletingDecimalPoint;
    private final EditText currency;

    public CurrencyTextWatcher(EditText p_currency) {
        currency = p_currency;
    }


    @Override
    public void beforeTextChanged(CharSequence p_s, int p_start, int p_count, int p_after) {

        if (p_after>0) {
                index = p_s.length() - p_start;
            } else {
                index = p_s.length() - p_start - 1;
            }
            if (p_count>0 && p_s.charAt(p_start)==',') {
                deletingDecimalPoint = true;
            } else {
                deletingDecimalPoint = false;
            }

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable p_s) {


         if(!p_s.toString().equals(current)){
                currency.removeTextChangedListener(this);
                if (deletingDecimalPoint) {
                    p_s.delete(p_s.length()-index-1, p_s.length()-index);
                }
                // Currency char may be retrieved from  NumberFormat.getCurrencyInstance()
                String v_text = p_s.toString().replace("€","").replace(",", "");
                v_text = v_text.replaceAll("\\s", "");
                double v_value = 0;
                if (v_text!=null && v_text.length()>0) {
                    v_value = Double.parseDouble(v_text);
                }
                // Currency instance may be retrieved from a static member.
                NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale("pt", "PT"));
                String v_formattedValue = numberFormat.format((v_value/100));
                current = v_formattedValue;
                currency.setText(v_formattedValue);
                if (index>v_formattedValue.length()) {
                    currency.setSelection(v_formattedValue.length());
                } else {
                    currency.setSelection(v_formattedValue.length()-index);
                }
                // include here anything you may want to do after the formatting is completed.
                currency.addTextChangedListener(this);
             }
    }

}

The layout.xml

<EditText
    android:id="@+id/edit_text_your_id"
    ...
    android:text="0,00 €"
    android:inputType="numberDecimal"
    android:digits="0123456789" />

Get it to work

    yourEditText = (EditText) findViewById(R.id.edit_text_your_id);
    yourEditText.setRawInputType(Configuration.KEYBOARD_12KEY);
    yourEditText.addTextChangedListener(new CurrencyTextWatcher(yourEditText));

Subscript out of range error in this Excel VBA script

Set sh1 = Worksheets(filenum(lngPosition)).Activate

You are getting Subscript out of range error error becuase it cannot find that Worksheet.

Also please... please... please do not use .Select/.Activate/Selection/ActiveCell You might want to see How to Avoid using Select in Excel VBA Macros.

Python: Assign print output to a variable

probably you need one of str,repr or unicode functions

somevar = str(tag.getArtist())

depending which python shell are you using

How do I make the first letter of a string uppercase in JavaScript?

Capitalize the first letter of all words in a string:

function ucFirstAllWords( str )
{
    var pieces = str.split(" ");
    for ( var i = 0; i < pieces.length; i++ )
    {
        var j = pieces[i].charAt(0).toUpperCase();
        pieces[i] = j + pieces[i].substr(1);
    }
    return pieces.join(" ");
}

What processes are using which ports on unix?

Which process uses port in unix;

1. netstat -Aan | grep port

root> netstat -Aan | grep 3872

output> f1000e000bb5c3b8 tcp 0 0 *.3872 . LISTEN

2. rmsock f1000e000bb5c3b8 tcpcb

output> The socket 0xf1000e000bb5c008 is being held by proccess 13959354 (java).

3. ps -ef | grep 13959354

Understanding Bootstrap's clearfix class

.clearfix is defined in less/mixins.less. Right above its definition is a comment with a link to this article:

A new micro clearfix hack

The article explains how it all works.

UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):

This “micro clearfix” generates pseudo-elements and sets their display to table. This creates an anonymous table-cell and a new block formatting context that means the :before pseudo-element prevents top-margin collapse. The :after pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.

Including the :before selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:

  • It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g., overflow:hidden

  • It ensures visual consistency with IE 6/7 when zoom:1 is applied.

N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.

The use of content:" " (note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if the contenteditable attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to use font:0/0 a.

Legacy Firefox

Firefox < 3.5 will benefit from using Thierry’s method with the addition of visibility:hidden to hide the inserted character. This is because legacy versions of Firefox need content:"." to avoid extra space appearing between the body and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)

Alternative float-containment methods that create a new block formatting context, such as applying overflow:hidden or display:inline-block to the container element, will also avoid this behaviour in legacy versions of Firefox.

.attr('checked','checked') does not work

 $('.checkbox').attr('checked',true);

will not work with from jQuery 1.6.

Instead use

$('.checkbox').prop('checked',true);
$('.checkbox').prop('checked',false);

Full explanation / examples and demo can be found in the jQuery API Documentation https://api.jquery.com/attr/

How do I create an empty array/matrix in NumPy?

Here is some workaround to make numpys look more like Lists

np_arr = np.array([])
np_arr = np.append(np_arr , 2)
np_arr = np.append(np_arr , 24)
print(np_arr)

OUTPUT: array([ 2., 24.])

React Router v4 - How to get current route?

In the 5.1 release of react-router there is a hook called useLocation, which returns the current location object. This might useful any time you need to know the current URL.

import { useLocation } from 'react-router-dom'

function HeaderView() {
  const location = useLocation();
  console.log(location.pathname);
  return <span>Path : {location.pathname}</span>
}

I can't understand why this JAXB IllegalAnnotationException is thrown

One of the following may cause the exception:

  1. Add an empty public constructor to your Fields class, JAXB uses reflection to load your classes, that's why the exception is thrown.
  2. Add separate getter and setter for your list.

Avoid dropdown menu close on click inside

In Bootstrap 4 you can also do this:

$('#dd-link').on('hide.bs.dropdown', onListHide)

function onListHide(e)
{
  if(e.clickEvent && $.contains(e.relatedTarget.parentNode, e.clickEvent.target)) {
  e.preventDefault()
  }
}

where #dd-link is the anchor element or button that has the data-toggle="drowndown" property.

Converting char[] to byte[]

char[] ch = ?
new String(ch).getBytes();

or

new String(ch).getBytes("UTF-8");

to get non-default charset.

Update: Since Java 7: new String(ch).getBytes(StandardCharsets.UTF_8);

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

axios post request to send form data

The above method worked for me but since it was something I needed often, I used a basic method for flat object. Note, I was also using Vue and not REACT

packageData: (data) => {
  const form = new FormData()
  for ( const key in data ) {
    form.append(key, data[key]);
  }
  return form
}

Which worked for me until I ran into more complex data structures with nested objects and files which then let to the following

packageData: (obj, form, namespace) => {
  for(const property in obj) {
    // if form is passed in through recursion assign otherwise create new
    const formData = form || new FormData()
    let formKey

    if(obj.hasOwnProperty(property)) {
      if(namespace) {
        formKey = namespace + '[' + property + ']';
      } else {
        formKey = property;
      }

      // if the property is an object, but not a File, use recursion.
      if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
        packageData(obj[property], formData, property);
      } else {
        // if it's a string or a File
      formData.append(formKey, obj[property]);
      }
    }
  }
  return formData;
}

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

How do I convert a byte array to Base64 in Java?

Java 8+

Encode or decode byte arrays:

byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded)    // Outputs "Hello"

For more info, see Base64.

Java < 8

Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.

For direct byte arrays:

Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = codec.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(codec.decodeBase64(encoded));
println(decoded)    // Outputs "Hello"

Spring

If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils class more ergonomic:

For direct byte arrays:

byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded))    // Outputs "SGVsbG8="

byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded))    // Outputs "Hello"

Android (with Java < 8)

If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64.

For direct byte arrays:

byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded))    // Outputs "SGVsbG8="

byte [] decoded = Base64.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.decode(encoded));
println(decoded)    // Outputs "Hello"

What is the difference between Trap and Interrupt?

Generally speaking, terms like exceptions, faults, aborts, Traps, and Interrupts all mean the same thing and are called "Interrupts".

Coming to the difference between Trap and Interrupt:

Trap: Is a programmer initiated and expected transfer of control to a special handler routine. (For ex: 80x86 INT instruction is a good example)

Where as

Interrupt(Hardware): Is a program control interruption based on an external hardware event external to the CPU (For ex: Pressing a key on the keyboard or a time out on a timer chip)

How to change css property using javascript

Just for the info, this can be done with CSS only with just minor HTML and CSS changes

HTML:

<div class="left">
    Hello
</div>
<div class="right">
    Hello2
</div>
<div class="center">
       <div class="left1">
           Bye
    </div>
       <div class="right1">
           Bye1
    </div>    
</div>

CSS:

.left, .right{
    margin:10px;
    float:left;
    border:1px solid red;
    height:60px;
    width:60px
}
.left:hover, .right:hover{
    border:1px solid blue;
}
.right{
     float :right;
}
.center{
    float:left;
    height:60px;
    width:160px
}

.center .left1, .center .right1{
    margin:10px;
    float:left;
    border:1px solid green;
    height:60px;
    width:58px;
    display:none;
}
.left:hover ~ .center .left1 {
    display:block;
}

.right:hover ~ .center .right1 {
    display:block;
}

and the DEMO: http://jsfiddle.net/pavloschris/y8LKM/

How do I delete an exported environment variable?

unset is the command you're looking for.

unset GNUPLOT_DRIVER_DIR

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The reject actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject() the exception value is undefined, hence the "undefined" part in the error that you get.

You do not show the code that uses the promise, but I reckon it is something like this:

var promise = doSth();
promise.then(function() { doSthHere(); });

Try adding an empty failure call, like this:

promise.then(function() { doSthHere(); }, function() {});

This will prevent the error to appear.

However, I would consider calling reject only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.

CSS3 Transparency + Gradient

I just came across this more recent example . To simplify and use the most recent examples, giving the css a selector class of 'grad',(I've included backwards compatibility)

.grad {
    background-color: #F07575; /* fallback color if gradients are not supported */
    background-image: -webkit-linear-gradient(top left, red, rgba(255,0,0,0));/* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
    background-image: -moz-linear-gradient(top left, red, rgba(255,0,0,0));/* For Firefox (3.6 to 15) */
    background-image: -o-linear-gradient(top left, red, rgba(255,0,0,0));/* For old Opera (11.1 to 12.0) */
    background-image: linear-gradient(to bottom right, red, rgba(255,0,0,0)); /* Standard syntax; must be last */
}

from https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

Using moment.js to convert date to string "MM/dd/yyyy"

this also might be relevant to anyone using React -

install react-moment (npm i react-moment)

import Moment from 'react-moment'


<Moment format="MM/DD/YYYY">{yourTimeStamp}</Moment>

(or any other format you'd like)

What is the difference between "px", "dip", "dp" and "sp"?

I have calculated the formula below to make the conversions dpi to dp and sp enter image description here

Remove blue border from css custom-styled button in Chrome

For anyone using Bootstrap and having this problem, they use :active:focus as well as just :active and :focus so you'll need:

element:active:focus {
    outline: 0;
}

Hopefully saved someone some time figuring that one out, banged my head for bit wondering why such a simple thing wasn't working.

How to get relative path of a file in visual studio?

Omit the "~\":

var path = @"FolderIcon\Folder.ico";

~\ doesn't mean anything in terms of the file system. The only place I've seen that correctly used is in a web app, where ASP.NET replaces the tilde with the absolute path to the root of the application.

You can typically assume the paths are relative to the folder where the EXE is located. Also, make sure that the image is specified as "content" and "copy if newer"/"copy always" in the properties tab in Visual Studio.

What is the backslash character (\\)?

The \ on it's own is used to escape special characters, such as \n (new line), \t (tabulation), \" (quotes) when typing these specific values in a System.out.println() statement.

Thus, if you want to print a backslash, \, you can't have it on it's own since the compiler will be expecting a special character (such as the ones above). Thus, to print a backslash you need to escape it, since itself is also one of these special characters, thus, \\ yields \.

SQL Server: Best way to concatenate multiple columns?

SELECT CONCAT(LOWER(LAST_NAME), UPPER(LAST_NAME)
       INITCAP(LAST_NAME), HIRE DATE AS ‘up_low_init_hdate’)
FROM EMPLOYEES
WHERE HIRE DATE = 1995

How to Toggle a div's visibility by using a button click

jQuery would be the easiest way if you want to use it, but this should work.

function showHide(){
    var e = document.getElementById('e');

    if ( e.style.display !== 'none' ) {
        e.style.display = 'none';
    } else {
        e.style.display = '';
    }
}

Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

To pass a pointer to an int it should be void Fun(int* pointer).

Passing a reference to an int would look like this...

void Fun(int& ref) {
   ref = 10;
}

int main() {
   int test = 5;
   cout << test << endl;  // prints 5

   Fun(test);
   cout << test << endl;  // prints 10 because Fun modified the value

   return 1;
}

What is the difference between json.load() and json.loads() functions

Documentation is quite clear: https://docs.python.org/2/library/json.html

json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.

So load is for a file, loads for a string

Force IE compatibility mode off using tags

If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add Name: X-UA-Compatible
Value: IE=edge This will override your browser and your code.

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

random number generator between 0 - 1000 in c#

Have you tried this

Random integer between 0 and 1000(1000 not included):

Random random = new Random();
int randomNumber = random.Next(0, 1000);

Loop it as many times you want

How to extract the decimal part from a floating point number in C?

 #include <stdio.h>
Int main ()
{
float f=56.75;
int a=(int)f;
int result=(f-a)*100;
printf ("integer = %d\n decimal part to integer 
 =%d\n",result);
}
Output:- 
integer =56
decimal part to integer = 75

How to Get a Sublist in C#

With LINQ:

List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();

If you need foreach, then no need for ToList:

foreach (string s in l.Skip(1).Take(2)){}

Advantage of LINQ is that if you want to just skip some leading element,you can :

List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}

i.e. no need to take care of count/length, etc.

How can I download a specific Maven artifact in one command line?

Here's an example to get ASM-7 using Maven 3.6:

mvn dependency:get -DremoteRepositories=maven.apache.org -Dartifact=org.ow2.asm:7.0:sources:jar

Or you can download the jar from here: https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm and then

mvn install:install-file -DgroupId=org.ow2.asm -DartifactId=asm -Dversion=7.0 -Dclassifier=sources -Dpackaging=jar -Dfile=/path/to/asm-7.0.jar

Change the URL in the browser without loading the new page using JavaScript

Browser security settings prevent people from modifying the displayed url directly. You could imagine the phishing vulnerabilities that would cause.

Only reliable way to change the url without changing pages is to use an internal link or hash. e.g.: http://site.com/page.html becomes http://site.com/page.html#item1 . This technique is often used in hijax(AJAX + preserve history).

When doing this I'll often just use links for the actions with the hash as the href, then add click events with jquery that use the requested hash to determine and delegate the action.

I hope that sets you on the right path.

View JSON file in Browser

Well I was searching view json file in WebBrowser in my Desktop app, when I try in IE still same problem IE was also prompt to download the file. Luckily after too much search I find the solution for it.

You need to : Open Notepad and paste the following:

    [HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
    "CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
    "Encoding"=hex:08,00,00,00
    
Save document as Json.reg and then right click on file and run as administrator.

After this You can view json file in IE and you Desktop WebBrowser enjoy :)

Java - Find shortest path between 2 points in a distance weighted map

This maybe too late but No one provided a clear explanation of how the algorithm works

The idea of Dijkstra is simple, let me show this with the following pseudocode.

Dijkstra partitions all nodes into two distinct sets. Unsettled and settled. Initially all nodes are in the unsettled set, e.g. they must be still evaluated.

At first only the source node is put in the set of settledNodes. A specific node will be moved to the settled set if the shortest path from the source to a particular node has been found.

The algorithm runs until the unsettledNodes set is empty. In each iteration it selects the node with the lowest distance to the source node out of the unsettledNodes set. E.g. It reads all edges which are outgoing from the source and evaluates each destination node from these edges which are not yet settled.

If the known distance from the source to this node can be reduced when the selected edge is used, the distance is updated and the node is added to the nodes which need evaluation.

Please note that Dijkstra also determines the pre-successor of each node on its way to the source. I left that out of the pseudo code to simplify it.

Credits to Lars Vogel

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

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.

proper hibernate annotation for byte[]

On Postgres @Lob is breaking for byte[] as it tries to save it as oid, and for String also same problem occurs. Below code is breaking on postgres which is working fine on oracle.

@Lob
private String stringField;

and

@Lob
private byte[]   someByteStream;

In order to fix above on postgres have written below custom hibernate.dialect

public class PostgreSQLDialectCustom extends PostgreSQL82Dialect{

public PostgreSQLDialectCustom()
{
    super();
    registerColumnType(Types.BLOB, "bytea");
}

 @Override
 public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (Types.CLOB == sqlTypeDescriptor.getSqlType()) {
      return LongVarcharTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
}

Now configure custom dialect in hibernate

hibernate.dialect=X.Y.Z.PostgreSQLDialectCustom   

X.Y.Z is package name.

Now it working fine. NOTE- My Hibernate version - 5.2.8.Final Postgres version- 9.6.3

How to make the corners of a button round?

Create rounded_btn.xml file in Drawable folder...

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
     <solid android:color="@color/#FFFFFF"/>    

     <stroke android:width="1dp"
        android:color="@color/#000000"
        />

     <padding android:left="1dp"
         android:top="1dp"
         android:right="1dp"
         android:bottom="1dp"
         /> 

     <corners android:bottomRightRadius="5dip" android:bottomLeftRadius="5dip" 
         android:topLeftRadius="5dip" android:topRightRadius="5dip"/> 
  </shape>

and use this.xml file as a button background

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/rounded_btn"
android:text="Test" />

How to fix git error: RPC failed; curl 56 GnuTLS

Reinstalling git will solve the problem.

sudo apt-get remove git
sudo apt-get update
sudo apt-get install git

Difference between angle bracket < > and double quotes " " while including header files in C++?

When you use angle brackets, the compiler searches for the file in the include path list. When you use double quotes, it first searches the current directory (i.e. the directory where the module being compiled is) and only then it'll search the include path list.

So, by convention, you use the angle brackets for standard includes and the double quotes for everything else. This ensures that in the (not recommended) case in which you have a local header with the same name as a standard header, the right one will be chosen in each case.

Taking pictures with camera on Android programmatically

For those who came here looking for a way to take pictures/photos programmatically using both Android's Camera and Camera2 API, take a look at the open source sample provided by Google itself here.

How to include view/partial specific styling in AngularJS

@sz3, funny enough today I had to do exactly what you were trying to achieve: 'load a specific CSS file only when a user access' a specific page. So I used the solution above.

But I am here to answer your last question: 'where exactly should I put the code. Any ideas?'

You were right including the code into the resolve, but you need to change a bit the format.

Take a look at the code below:

.when('/home', {
  title:'Home - ' + siteName,
  bodyClass: 'home',
  templateUrl: function(params) {
    return 'views/home.html';
  },
  controler: 'homeCtrl',
  resolve: {
    style : function(){
      /* check if already exists first - note ID used on link element*/
      /* could also track within scope object*/
      if( !angular.element('link#mobile').length){
        angular.element('head').append('<link id="home" href="home.css" rel="stylesheet">');
      }
    }
  }
})

I've just tested and it's working fine, it injects the html and it loads my 'home.css' only when I hit the '/home' route.

Full explanation can be found here, but basically resolve: should get an object in the format

{
  'key' : string or function()
} 

You can name the 'key' anything you like - in my case I called 'style'.

Then for the value you have two options:

  • If it's a string, then it is an alias for a service.

  • If it's function, then it is injected and the return value is treated as the dependency.

The main point here is that the code inside the function is going to be executed before before the controller is instantiated and the $routeChangeSuccess event is fired.

Hope that helps.

React: how to update state.item[1] in state using setState?

You could use the update immutability helper for this:

this.setState({
  items: update(this.state.items, {1: {name: {$set: 'updated field name'}}})
})

Or if you don't care about being able to detect changes to this item in a shouldComponentUpdate() lifecycle method using ===, you could edit the state directly and force the component to re-render - this is effectively the same as @limelights' answer, as it's pulling an object out of state and editing it.

this.state.items[1].name = 'updated field name'
this.forceUpdate()

Post-edit addition:

Check out the Simple Component Communication lesson from react-training for an example of how to pass a callback function from a state-holding parent to a child component which needs to trigger a state change.

Copy multiple files in Python

import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below

dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")

for filename in os.listdir(dir_src):
    if filename.endswith('.txt'):
        shutil.copy( dir_src + filename, dir_dst)
    print(filename)

Draw horizontal rule in React Native

If you have a solid background (like white), this could be your solution:

<View style={container}>
  <View style={styles.hr} />
  <Text style={styles.or}>or</Text>
</View>

const styles = StyleSheet.create({
  container: {
    flex: 0,
    backgroundColor: '#FFFFFF',
    width: '100%',
  },
  hr: {
    position: 'relative',
    top: 11,
    borderBottomColor: '#000000',
    borderBottomWidth: 1,
  },
  or: {
    width: 30,
    fontSize: 14,
    textAlign: 'center',
    alignSelf: 'center',
    backgroundColor: '#FFFFFF',
  },
});

How do browser cookie domains work?

There are rules that determine whether a browser will accept the Set-header response header (server-side cookie writing), a slightly different rules/interpretations for cookie set using Javascript (I haven't tested VBScript).

Then there are rules that determine whether the browser will send a cookie along with the page request.

There are differences between the major browser engines how domain matches are handled, and how parameters in path values are interpreted. You can find some empirical evidence in the article How Different Browsers Handle Cookies Differently

Are static class variables possible in Python?

One very interesting point about Python's attribute lookup is that it can be used to create "virtual variables":

class A(object):

  label="Amazing"

  def __init__(self,d): 
      self.data=d

  def say(self): 
      print("%s %s!"%(self.label,self.data))

class B(A):
  label="Bold"  # overrides A.label

A(5).say()      # Amazing 5!
B(3).say()      # Bold 3!

Normally there aren't any assignments to these after they are created. Note that the lookup uses self because, although label is static in the sense of not being associated with a particular instance, the value still depends on the (class of the) instance.

Android emulator: could not get wglGetExtensionsStringARB error

just change your JDK I installed the JDK of SUN not Oracle and it works for me....

How to change font size in html?

Give them a class and add your style to the class.

<style>
  p {
    color: red;
  }
  .paragraph1 {
    font-size: 18px;
  }
  .paragraph2 {
    font-size: 13px;
  }
</style>

<p class="paragraph1">Paragraph 1</p>
<p class="paragraph2">Paragraph 2</p>

Check this EXAMPLE

Python, Unicode, and the Windows console

The below code will make Python output to console as UTF-8 even on Windows.

The console will display the characters well on Windows 7 but on Windows XP it will not display them well, but at least it will work and most important you will have a consistent output from your script on all platforms. You'll be able to redirect the output to a file.

Below code was tested with Python 2.6 on Windows.


#!/usr/bin/python
# -*- coding: UTF-8 -*-

import codecs, sys

reload(sys)
sys.setdefaultencoding('utf-8')

print sys.getdefaultencoding()

if sys.platform == 'win32':
    try:
        import win32console 
    except:
        print "Python Win32 Extensions module is required.\n You can download it from https://sourceforge.net/projects/pywin32/ (x86 and x64 builds are available)\n"
        exit(-1)
    # win32console implementation  of SetConsoleCP does not return a value
    # CP_UTF8 = 65001
    win32console.SetConsoleCP(65001)
    if (win32console.GetConsoleCP() != 65001):
        raise Exception ("Cannot set console codepage to 65001 (UTF-8)")
    win32console.SetConsoleOutputCP(65001)
    if (win32console.GetConsoleOutputCP() != 65001):
        raise Exception ("Cannot set console output codepage to 65001 (UTF-8)")

#import sys, codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

print "This is an ??amp?? testing Unicode support using Arabic, Latin, Cyrillic, Greek, Hebrew and CJK code points.\n"

Java: Finding the highest value in an array

An easy way without using collections

public void findHighestNoInArray() {
        int[] a = {1,2,6,8,9};
        int large = a[0];
            for(int num : a) {
                if(large < num) {
                    large = num;
                }
            }
            System.out.println("Large number is "+large+"");
        }

How to set a header for a HTTP GET request, and trigger file download?

Pure jQuery.

$.ajax({
  type: "GET",
  url: "https://example.com/file",
  headers: {
    'Authorization': 'Bearer eyJraWQiFUDA.......TZxX1MGDGyg'
  },
  xhrFields: {
    responseType: 'blob'
  },
  success: function (blob) {
    var windowUrl = window.URL || window.webkitURL;
    var url = windowUrl.createObjectURL(blob);
    var anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = 'filename.zip';
    anchor.click();
    anchor.parentNode.removeChild(anchor);
    windowUrl.revokeObjectURL(url);
  },
  error: function (error) {
    console.log(error);
  }
});

regular expression for DOT

Use String.Replace() if you just want to replace the dots from string. Alternative would be to use Pattern-Matcher with StringBuilder, this gives you more flexibility as you can find groups that are between dots. If using the latter, i would recommend that you ignore empty entries with "\\.+".

public static int count(String str, String regex) {
    int i = 0;
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(str);
    while (m.find()) {
        m.group();
        i++;
    }
    return i;
}

public static void main(String[] args) {
    int i = 0, j = 0, k = 0;
    String str = "-.-..-...-.-.--..-k....k...k..k.k-.-";

    // this will just remove dots
    System.out.println(str.replaceAll("\\.", ""));
    // this will just remove sequences of ".." dots
    System.out.println(str.replaceAll("\\.{2}", ""));
    // this will just remove sequences of dots, and gets
    // multiple of dots as 1
    System.out.println(str.replaceAll("\\.+", ""));

    /* for this to be more obvious, consider following */
    System.out.println(count(str, "\\."));
    System.out.println(count(str, "\\.{2}"));
    System.out.println(count(str, "\\.+"));
}

The output will be:

--------kkkkk--
-.--.-.-.---kk.kk.k-.-
--------kkkkk--
21
7
11

How to download a branch with git?

Navigate to the folder on your new machine you want to download from git on git bash.

Use below command to download the code from any branch you like

git clone 'git ssh url' -b 'Branch Name'

It will download the respective branch code.

How to check whether the user uploaded a file in PHP?

You can use is_uploaded_file():

if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
    echo 'No upload';
}

From the docs:

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

EDIT: I'm using this in my FileUpload class, in case it helps:

public function fileUploaded()
{
    if(empty($_FILES)) {
        return false;       
    } 
    $this->file = $_FILES[$this->formField];
    if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
        $this->errors['FileNotExists'] = true;
        return false;
    }   
    return true;
}

how to create a Java Date object of midnight today and midnight tomorrow?

java.time

If you are using Java 8 and later, you can try the java.time package (Tutorial):

LocalDate tomorrow = LocalDate.now().plusDays(1);
Date endDate = Date.from(tomorrow.atStartOfDay(ZoneId.systemDefault()).toInstant());

Laravel Unknown Column 'updated_at'

In the model, write the below code;

public $timestamps = false;

This would work.

Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.

JQuery post JSON object to a server

It is also possible to use FormData(). But you need to set contentType as false:

var data = new FormData();
data.append('name', 'Bob'); 

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: false,
        data: data,
        dataType: 'json'
    });
}

Replacing from match to end-of-line

This should do what you want:

sed 's/two.*/BLAH/'

$ echo "   one  two  three  five
>    four two  five five six
>    six  one  two seven four" | sed 's/two.*/BLAH/'
   one  BLAH
   four BLAH
   six  one  BLAH

The $ is unnecessary because the .* will finish at the end of the line anyways, and the g at the end is unnecessary because your first match will be the first two to the end of the line.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

How do I read the contents of a Node.js stream into a string variable?

(This answer is from years ago, when it was the best answer. There is now a better answer below this. I haven't kept up with node.js, and I cannot delete this answer because it is marked "correct on this question". If you are thinking of down clicking, what do you want me to do?)

The key is to use the data and end events of a Readable Stream. Listen to these events:

stream.on('data', (chunk) => { ... });
stream.on('end', () => { ... });

When you receive the data event, add the new chunk of data to a Buffer created to collect the data.

When you receive the end event, convert the completed Buffer into a string, if necessary. Then do what you need to do with it.

ERROR 2006 (HY000): MySQL server has gone away

For Drupal 8 users looking for solution for DB import failure:

At end of sql dump file there can commands inserting data to "webprofiler" table. That's I guess some debug log file and is not really important for site to work so all this can be removed. I deleted all those inserts including LOCK TABLES and UNLOCK TABLES (and everything between). It's at very bottom of the sql file. Issue is described here:

https://www.drupal.org/project/devel/issues/2723437

But there is no solution for it beside truncating that table.

BTW I tried all solutions from answers above and nothing else helped.

How do I use Docker environment variable in ENTRYPOINT array?

I tried to resolve with the suggested answer and still ran into some issues...

This was a solution to my problem:

ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}

# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh

# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]

Specifically targeting your problem:

RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

Make Https call using HttpClient

I agree with felickz but also i want to add an example for clarifying the usage in c#. I use SSL in windows service as follows.

    var certificatePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");
    gateway = new GatewayService();
    gateway.PreAuthenticate = true;


    X509Certificate2 cert = new X509Certificate2(certificatePath + @"\Attached\my_certificate.pfx","certificate_password");
    gateway.ClientCertificates.Add(cert);

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    gateway.UserAgent = Guid.NewGuid().ToString();
    gateway.Timeout = int.MaxValue;

If I'm going to use it in a web application, I'm just changing the implementation on the proxy side like this:

public partial class GatewayService : System.Web.Services.Protocols.SoapHttpClientProtocol // to => Microsoft.Web.Services2.WebServicesClientProtocol

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?

How to replace multiple white spaces with one white space

I'm sharing what I use, because it appears I've come up with something different. I've been using this for a while and it is fast enough for me. I'm not sure how it stacks up against the others. I uses it in a delimited file writer and run large datatables one field at a time through it.

    public static string NormalizeWhiteSpace(string S)
    {
        string s = S.Trim();
        bool iswhite = false;
        int iwhite;
        int sLength = s.Length;
        StringBuilder sb = new StringBuilder(sLength);
        foreach(char c in s.ToCharArray())
        {
            if(Char.IsWhiteSpace(c))
            {
                if (iswhite)
                {
                    //Continuing whitespace ignore it.
                    continue;
                }
                else
                {
                    //New WhiteSpace

                    //Replace whitespace with a single space.
                    sb.Append(" ");
                    //Set iswhite to True and any following whitespace will be ignored
                    iswhite = true;
                }  
            }
            else
            {
                sb.Append(c.ToString());
                //reset iswhitespace to false
                iswhite = false;
            }
        }
        return sb.ToString();
    }

How do I make a JSON object with multiple arrays?

var cars = [
    manufacturer: [
        {
            color: 'gray',
            model: '1',
            nOfDoors: 4
        },
        {
            color: 'yellow',
            model: '2',
            nOfDoors: 4
        }
    ]
]

Configuring diff tool with .gitconfig

Others have done a 99% answer on this, but there is one step left out. (My answer will be coming from OS X so you will have to change file paths accordingly.)

You make these changes to your ~/.gitconfig:

[diff]
    tool = diffmerge
[difftool "diffmerge"]
    cmd = /Applications/Diffmerge.app/Contents/MacOS/diffmerge $LOCAL $REMOTE

This will fix the diff tool. You can also fix this without editing the ~/.gitconfig directly by entering these commands from the terminal:

git config --global diff.tool diffmerge
git config --global difftool.diffmerge.cmd "/Applications/DiffMerge.appContents/MacOS/diffmerge \$LOCAL \$REMOTE"

The 1% that everyone else failed to mention is when using this you can't just run git diff myfile.txt; you need to run git difftool myfile.txt.

JavaScript moving element in the DOM

jQuery.fn.swap = function(b){ 
    b = jQuery(b)[0]; 
    var a = this[0]; 
    var t = a.parentNode.insertBefore(document.createTextNode(''), a); 
    b.parentNode.insertBefore(a, b); 
    t.parentNode.insertBefore(b, t); 
    t.parentNode.removeChild(t); 
    return this; 
};

and use it like this:

$('#div1').swap('#div2');

if you don't want to use jQuery you could easily adapt the function.

Excel SUMIF between dates

I found another way to work around this issue that I thought I would share.

In my case I had a years worth of daily columns (i.e. Jan-1, Jan-2... Dec-31), and I had to extract totals for each month. I went about it this way: Sum the entire year, Subtract out the totals for the dates prior and the dates after. It looks like this for February's totals:

=SUM($P3:$NP3)-(SUMIF($P$2:$NP$2, ">2/28/2014",$P3:$NP3)+SUMIF($P$2:$NP$2, "<2/1/2014",$P3:$NP3))

Where $P$2:$NP$2 contained my date values and $P3:$NP3 was the first row of data I am totaling. So SUM($P3:$NP3) is my entire year's total and I subtract (the sum of two sumifs):

SUMIF($P$2:$NP$2, ">2/28/2014",$P3:$NP3), which totals all the months after February and SUMIF($P$2:$NP$2, "<2/1/2014",$P3:$NP3), which totals all the months before February.

Use jQuery to change value of a label

Validation (HTML5): Attribute 'name' is not a valid attribute of element 'label'.

Angularjs - Pass argument to directive

Controller code

myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {
    $scope.person = {
        name:"sangeetha PH",
       address:"first Block"
    }
}]);

Directive Code

myApp.directive('searchResult',function(){
   return{
       restrict:'AECM',
       templateUrl:'directives/search.html',
       replace: true,
       scope:{
           personName:"@",
           personAddress:"@"
       }
   } 
});

USAGE

File :directives/search.html
content:

<h1>{{personName}} </h1>
<h2>{{personAddress}}</h2>

the File where we use directive

<search-result person-name="{{person.name}}" person-address="{{person.address}}"></search-result>

sqlite copy data from one table to another

I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

create table destination_old as select * from destination;

drop table destination;

create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;

It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;

Input type "number" won't resize

For <input type=number>, by the HTML5 CR, the size attribute is not allowed. However, in Obsolete features it says: “Authors should not, but may despite requirements to the contrary elsewhere in this specification, specify the maxlength and size attributes on input elements whose type attributes are in the Number state. One valid reason for using these attributes regardless is to help legacy user agents that do not support input elements with type="number" to still render the text field with a useful width.”

Thus, the size attribute can be used, but it only affects older browsers that do not support type=number, so that the element falls back to a simple text control, <input type=text>.

The rationale behind this is that the browser is expected to provide a user interface that takes the other attributes into account, for good usability. As the implementations may vary, any size imposed by an author might mess things up. (This also applies to setting the width of the control in CSS.)

The conclusion is that you should use <input type=number> in a more or less fluid setup that does not make any assumptions about the dimensions of the element.

Angular 2 - View not updating after model changes

It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

import {Component, OnInit, NgZone} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private zone:NgZone, // <== added
        private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => { 
                 this.zone.run(() => { // <== added
                     this.recentDetections = recent;
                     console.log(this.recentDetections[0].macAddress) 
                 });
        });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());
    }
}

For other ways to invoke change detection see Triggering change detection manually in Angular

Alternative ways to invoke change detection are

ChangeDetectorRef.detectChanges()

to immediately run change detection for the current component and its children

ChangeDetectorRef.markForCheck()

to include the current component the next time Angular runs change detection

ApplicationRef.tick()

to run change detection for the whole application

How link to any local file with markdown syntax?

If the file is in the same directory as the one where the .md is, then just putting [Click here](MY-FILE.md) should work.

Otherwise, can create a path from the root directory of the project. So if the entire project/git-repo root directory is called 'my-app', and one wants to point to my-app/client/read-me.md, then try [My hyperlink](/client/read-me.md).

At least works from Chrome.

How to loop through a HashMap in JSP?

Below code works for me

first I defined the partnerTypesMap like below in the server side,

Map<String, String> partnerTypes = new HashMap<>();

after adding values to it I added the object to model,

model.addAttribute("partnerTypesMap", partnerTypes);

When rendering the page I use below foreach to print them one by one.

<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
      <form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>

How to install Cmake C compiler and CXX compiler

Even though I had gcc already installed, I had to run

sudo apt-get install build-essential

to get rid of that error

HTML table with horizontal scrolling (first column fixed)

How about:

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed; _x000D_
  width: 100%;_x000D_
  *margin-left: -100px; /*ie7*/_x000D_
}_x000D_
td, th {_x000D_
  vertical-align: top;_x000D_
  border-top: 1px solid #ccc;_x000D_
  padding: 10px;_x000D_
  width: 100px;_x000D_
}_x000D_
.fix {_x000D_
  position: absolute;_x000D_
  *position: relative; /*ie7*/_x000D_
  margin-left: -100px;_x000D_
  width: 100px;_x000D_
}_x000D_
.outer {_x000D_
  position: relative;_x000D_
}_x000D_
.inner {_x000D_
  overflow-x: scroll;_x000D_
  overflow-y: visible;_x000D_
  width: 400px; _x000D_
  margin-left: 100px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th class=fix></th>_x000D_
        <th>Col 1</th>_x000D_
        <th>Col 2</th>_x000D_
        <th>Col 3</th>_x000D_
        <th>Col 4</th>_x000D_
        <th class="fix">Col 5</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header A</th>_x000D_
        <td>col 1 - A</td>_x000D_
        <td>col 2 - A (WITH LONGER CONTENT)</td>_x000D_
        <td>col 3 - A</td>_x000D_
        <td>col 4 - A</td>_x000D_
        <td class=fix>col 5 - A</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header B</th>_x000D_
        <td>col 1 - B</td>_x000D_
        <td>col 2 - B</td>_x000D_
        <td>col 3 - B</td>_x000D_
        <td>col 4 - B</td>_x000D_
        <td class=fix>col 5 - B</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header C</th>_x000D_
        <td>col 1 - C</td>_x000D_
        <td>col 2 - C</td>_x000D_
        <td>col 3 - C</td>_x000D_
        <td>col 4 - C</td>_x000D_
        <td class=fix>col 5 - C</td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can test it out in this jsbin: http://jsbin.com/uxecel/4/edit

Push git commits & tags simultaneously

Update August 2020

As mentioned originally in this answer by SoBeRich, and in my own answer, as of git 2.4.x

git push --atomic origin <branch name> <tag>

(Note: this actually work with HTTPS only with Git 2.24)

Update May 2015

As of git 2.4.1, you can do

git config --global push.followTags true

If set to true enable --follow-tags option by default.
You may override this configuration at time of push by specifying --no-follow-tags.

As noted in this thread by Matt Rogers answering Wes Hurd:

--follow-tags only pushes annotated tags.

git tag -a -m "I'm an annotation" <tagname>

That would be pushed (as opposed to git tag <tagname>, a lightweight tag, which would not be pushed, as I mentioned here)

Update April 2013

Since git 1.8.3 (April 22d, 2013), you no longer have to do 2 commands to push branches, and then to push tags:

The new "--follow-tags" option tells "git push" to push relevant annotated tags when pushing branches out.

You can now try, when pushing new commits:

git push --follow-tags

That won't push all the local tags though, only the one referenced by commits which are pushed with the git push.

Git 2.4.1+ (Q2 2015) will introduce the option push.followTags: see "How to make “git push” include tags within a branch?".

Original answer, September 2010

The nuclear option would be git push --mirror, which will push all refs under refs/.

You can also push just one tag with your current branch commit:

git push origin : v1.0.0 

You can combine the --tags option with a refspec like:

git push origin --tags :

(since --tags means: All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line)


You also have this entry "Pushing branches and tags with a single "git push" invocation"

A handy tip was just posted to the Git mailing list by Zoltán Füzesi:

I use .git/config to solve this:

[remote "origin"]
    url = ...
    fetch = +refs/heads/*:refs/remotes/origin/*
    push = +refs/heads/*
    push = +refs/tags/*

With these lines added git push origin will upload all your branches and tags. If you want to upload only some of them, you can enumerate them.

Haven't tried it myself yet, but it looks like it might be useful until some other way of pushing branches and tags at the same time is added to git push.
On the other hand, I don't mind typing:

$ git push && git push --tags

Beware, as commented by Aseem Kishore

push = +refs/heads/* will force-pushes all your branches.

This bit me just now, so FYI.


René Scheibe adds this interesting comment:

The --follow-tags parameter is misleading as only tags under .git/refs/tags are considered.
If git gc is run, tags are moved from .git/refs/tags to .git/packed-refs. Afterwards git push --follow-tags ... does not work as expected anymore.

sudo: port: command not found

First, you might need to edit your system's PATH

sudo vi /etc/paths

Add 2 following lines:

/opt/local/bin
/opt/local/sbin

Reboot your terminal

How do I separate an integer into separate digits in an array in JavaScript?

_x000D_
_x000D_
const toIntArray = (n) => ([...n + ""].map(v => +v))
_x000D_
_x000D_
_x000D_

.NET NewtonSoft JSON deserialize map to a different property name

If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me

Usage:

var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);

Logic:

public class CustomContractResolver : DefaultContractResolver
{
    private Dictionary<string, string> PropertyMappings { get; set; }

    public CustomContractResolver()
    {
        this.PropertyMappings = new Dictionary<string, string> 
        {
            {"Meta", "meta"},
            {"LastUpdated", "last_updated"},
            {"Disclaimer", "disclaimer"},
            {"License", "license"},
            {"CountResults", "results"},
            {"Term", "term"},
            {"Count", "count"},
        };
    }

    protected override string ResolvePropertyName(string propertyName)
    {
        string resolvedName = null;
        var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
        return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
    }
}

VideoView Full screen in android application

I had to make my VideoView sit in a RelativeLayout in order to make the chosen answer work.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <VideoView android:id="@+id/videoViewRelative"
         android:layout_alignParentTop="true"
         android:layout_alignParentBottom="true"
         android:layout_alignParentLeft="true"
         android:layout_alignParentRight="true"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">
    </VideoView>

</RelativeLayout>

As given here: Android - How to stretch video to fill VideoView area Toggling between screen sizes would be as simple as changing the layout parameters as given in the chosen answer.

Java enum - why use toString instead of name

A practical example when name() and toString() make sense to be different is a pattern where single-valued enum is used to define a singleton. It looks surprisingly at first but makes a lot of sense:

enum SingletonComponent {
    INSTANCE(/*..configuration...*/);

    /* ...behavior... */

    @Override
    String toString() {
      return "SingletonComponent"; // better than default "INSTANCE"
    }
}

In such case:

SingletonComponent myComponent = SingletonComponent.INSTANCE;
assertThat(myComponent.name()).isEqualTo("INSTANCE"); // blah
assertThat(myComponent.toString()).isEqualTo("SingletonComponent"); // better

Export specific rows from a PostgreSQL table as INSERT SQL script

For a data-only export use COPY.
You get a file with one table row per line as plain text (not INSERT commands), it's smaller and faster:

COPY (SELECT * FROM nyummy.cimory WHERE city = 'tokio') TO '/path/to/file.csv';

Import the same to another table of the same structure anywhere with:

COPY other_tbl FROM '/path/to/file.csv';

COPY writes and read files local to the server, unlike client programs like pg_dump or psql which read and write files local to the client. If both run on the same machine, it doesn't matter much, but it does for remote connections.

There is also the \copy command of psql that:

Performs a frontend (client) copy. This is an operation that runs an SQL COPY command, but instead of the server reading or writing the specified file, psql reads or writes the file and routes the data between the server and the local file system. This means that file accessibility and privileges are those of the local user, not the server, and no SQL superuser privileges are required.

The input is not a valid Base-64 string as it contains a non-base 64 character

And some times it started with double quotes, most of the times when you call API from dotNetCore 2 for getting file

string string64 = string64.Replace(@"""", string.Empty);
byte[] bytes = Convert.ToBase64String(string64);

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

substring(from: index) Converted to [index...]

Check the sample

let text = "1234567890"
let index = text.index(text.startIndex, offsetBy: 3)

text.substring(from: index) // "4567890"   [Swift 3]
String(text[index...])      // "4567890"   [Swift 4]

Read input stream twice

In case anyone is running in a Spring Boot app, and you want to read the response body of a RestTemplate (which is why I want to read a stream twice), there is a clean(er) way of doing this.

First of all, you need to use Spring's StreamUtils to copy the stream to a String:

String text = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()))

But that's not all. You also need to use a request factory that can buffer the stream for you, like so:

ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
RestTemplate restTemplate = new RestTemplate(factory);

Or, if you're using the factory bean, then (this is Kotlin but nevertheless):

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun createRestTemplate(): RestTemplate = RestTemplateBuilder()
  .requestFactory { BufferingClientHttpRequestFactory(SimpleClientHttpRequestFactory()) }
  .additionalInterceptors(loggingInterceptor)
  .build()

Source: https://objectpartners.com/2018/03/01/log-your-resttemplate-request-and-response-without-destroying-the-body/

NoClassDefFoundError in Java: com/google/common/base/Function

Please include all the jar files of selenium stand-alone and lib folder, then this error will resolved

Converting a year from 4 digit to 2 digit and back again in C#

This seems to work okay for me. yourDateTime.ToString().Substring(2);

How to create a scrollable Div Tag Vertically?

Well, your code worked for me (running Chrome 5.0.307.9 and Firefox 3.5.8 on Ubuntu 9.10), though I switched

overflow-y: scroll;

to

overflow-y: auto;

Demo page over at: http://davidrhysthomas.co.uk/so/tableDiv.html.

xhtml below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <META http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Div in table</title>
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css" />

        <style type="text/css" media="all">

        th      {border-bottom: 2px solid #ccc; }

        th,td       {padding: 0.5em 1em; 
                margin: 0;
                border-collapse: collapse;
                }

        tr td:first-child
                {border-right: 2px solid #ccc; } 

        td > div    {width: 249px;
                height: 299px;
                background-color:Gray;
                overflow-y: auto;
                max-width:230px;
                max-height:100px;
                }
        </style>

    <script type="text/javascript" src="js/jquery.js"></script>

    <script type="text/javascript">

    </script>

</head>

<body>

<div>

    <table>

        <thead>
            <tr><th>This is column one</th><th>This is column two</th><th>This is column three</th>
        </thead>



        <tbody>
            <tr><td>This is row one</td><td>data point 2.1</td><td>data point 3.1</td>
            <tr><td>This is row two</td><td>data point 2.2</td><td>data point 3.2</td>
            <tr><td>This is row three</td><td>data point 2.3</td><td>data point 3.3</td>
            <tr><td>This is row four</td><td><div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies mattis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum a accumsan purus. Vivamus semper tempus nisi et convallis. Aliquam pretium rutrum lacus sed auctor. Phasellus viverra elit vel neque lacinia ut dictum mauris aliquet. Etiam elementum iaculis lectus, laoreet tempor ligula aliquet non. Mauris ornare adipiscing feugiat. Vivamus condimentum luctus tortor venenatis fermentum. Maecenas eu risus nec leo vehicula mattis. In nisi nibh, fermentum vitae tincidunt non, mattis eu metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc vel est purus. Ut accumsan, elit non lacinia porta, nibh magna pretium ligula, sed iaculis metus tortor aliquam urna. Duis commodo tincidunt aliquam. Maecenas in augue ut ligula sodales elementum quis vitae risus. Vivamus mollis blandit magna, eu fringilla velit auctor sed.</p></div></td><td>data point 3.4</td>
            <tr><td>This is row five</td><td>data point 2.5</td><td>data point 3.5</td>
            <tr><td>This is row six</td><td>data point 2.6</td><td>data point 3.6</td>
            <tr><td>This is row seven</td><td>data point 2.7</td><td>data point 3.7</td>
        </body>



    </table>

</div>

</body>

</html>

Call web service in excel

Yes You Can!

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

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

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

VBA: Consume Soap Web Services

How to preserve request url with nginx proxy_pass

In case something modifies the location that you're trying to serve, e.g. try_files, this preserves the request for the back-end:

location / {
  proxy_pass http://127.0.0.1:8080$request_uri;
}

Tools: replace not replacing in Android manifest

Declare your manifest header like this

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yourpackage"
    xmlns:tools="http://schemas.android.com/tools">

Then you can add to your application tag the following attribute:

<application
    tools:replace="icon, label" ../>

For example I need to replace icon and label. Good luck!

Why do package names often begin with "com"

This is what Sun-Oracle documentation says:

Package names are written in all lower case to avoid conflict with the names of classes or interfaces.

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

Maybe you are trying to set it in Apache's php.ini, but your CLI (Command Line Interface) php.ini is not good.

Find your php.ini file with the following command:

php -i | grep php.ini

And then search for date.timezone and set it to "Europe/Amsterdam". all valid timezone will be found here http://php.net/manual/en/timezones.php

Another way (if the other does not work), search for the file AppKernel.php, which should be under the folder app of your Symfony project directory. Overwrite the __construct function below in the class AppKernel:

<?php     

class AppKernel extends Kernel
{
    // Other methods and variables


    // Append this init function below

    public function __construct($environment, $debug)
    {
        date_default_timezone_set( 'Europe/Paris' );
        parent::__construct($environment, $debug);
    }

}

jQuery Combobox/select autocomplete?

Have a look at the following example of the jQueryUI Autocomplete, as it is keeping a select around and I think that is what you are looking for. Hope this helps.

http://jqueryui.com/demos/autocomplete/#combobox

AngularJS access scope from outside js function

This is how I did for my CRUDManager class initialized in Angular controller, which later passed over to jQuery button-click event defined outside the controller:

In Angular Controller:

        // Note that I can even pass over the $scope to my CRUDManager's constructor.
        var crudManager = new CRUDManager($scope, contextData, opMode);

        crudManager.initialize()
            .then(() => {
                crudManager.dataBind();
                $scope.crudManager = crudManager;
                $scope.$apply();
            })
            .catch(error => {
                alert(error);
            });

In jQuery Save button click event outside the controller:

    $(document).on("click", "#ElementWithNgControllerDefined #btnSave", function () {
        var ngScope = angular.element($("#ElementWithNgControllerDefined")).scope();
        var crudManager = ngScope.crudManager;
        crudManager.saveData()
            .then(finalData => {
               alert("Successfully saved!");
            })
            .catch(error => {
               alert("Failed to save.");
            });
    });

This is particularly important and useful when your jQuery events need to be placed OUTSIDE OF CONTROLLER in order to prevent it from firing twice.

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

Use Invalidations to clear the cache, you can put the path to the files you want to clear, or simply use wild cards to clear everything.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidating-objects-api

This can also be done using the API! http://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateInvalidation.html

The AWS PHP SDK now has the methods but if you want to use something lighter check out this library: http://www.subchild.com/2010/09/17/amazon-cloudfront-php-invalidator/

user3305600's solution doesn't work as setting it to zero is the equivalent of Using the Origin Cache Headers.

What's the difference between equal?, eql?, ===, and ==?

Equality operators: == and !=

The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.

"koan" == "koan" # Output: => true

The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.

"koan" != "discursive thought" # Output: => true

Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.

When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.

2 == 2.0 # Output: => true

equal?

Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.

Example: a = "zen" b = "zen"

a.object_id  # Output: => 20139460
b.object_id  # Output :=> 19972120

a.equal? b  # Output: => false

In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.

Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.

a = "zen"
b = a

a.object_id  # Output: => 18637360
b.object_id  # Output: => 18637360

a.equal? b  # Output: => true

eql?

In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.

Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).

"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547

The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.

Symbol.instance_method(:hash).owner  # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel

String.instance_method(:hash).owner  # Output: => String
Hash.instance_method(:hash).owner  # Output: => Hash

In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.

"zen".eql? "zen"    # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true

In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.

2 == 2.0    # Output: => true
2.eql? 2.0    # Output: => false
2.hash == 2.0.hash  # Output: => false

Case equality operator: ===

Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.

2.is_a? Integer   # Output: => true
2.kind_of? Integer  # Output: => true
2.instance_of? Integer # Output: => false

Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.

The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:

Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true

Range Implementation of ===

When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.

Regexp Implementation of ===

Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is the same as "practice zazen today"=~ /zen/

Implicit usage of the === operator on case/when statements

This operator is also used under the hood on case/when statements. That is its most common use.

minutes = 15

case minutes
  when 10..20
    puts "match"
  else
    puts "no match"
end

# Output: match

In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:

if (10..20) === minutes
  puts "match"
else
  puts "no match"
end

Pattern matching operators: =~ and !~

The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.

The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.

"practice zazen" =~ /zen/   # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil

:zazen =~ /zen/    # Output: => 2
:zazen =~ /discursive thought/  # Output: => nil

The implementation in the Regexp class expects a string or a symbol as an argument.

/zen/ =~ "practice zazen"  # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil

In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.

puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes

Pattern-matching operators are also useful for writing shorter if statements. Example:

if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
  true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
  true
end

The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.

More info is available at this blog post.

How to use ? : if statements with Razor and inline code blocks

The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.

"elseif" syntax in JavaScript

if ( 100 < 500 ) {
   //any action
}
else if ( 100 > 500 ){
   //any another action
}

Easy, use space

Clear dropdown using jQuery Select2

I found the answer (compliments to user780178) I was looking for in this other question:

Reset select2 value and show placeholdler

$("#customers_select").select2("val", "");

How to calculate DATE Difference in PostgreSQL?

CAST both fields to datatype DATE and you can use a minus:

(CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference

Test case:

SELECT  (CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
FROM 
    generate_series('2014-01-01'::timestamp, '2014-02-01'::timestamp, interval '1 hour') g(joindate);

Result: 31

Or create a function datediff():

CREATE OR REPLACE FUNCTION datediff(timestamp, timestamp) 
RETURNS int 
LANGUAGE sql 
AS
$$
    SELECT CAST($1 AS date) - CAST($2 AS date) as DateDifference
$$;

Remove a fixed prefix/suffix from a string in Bash

I use grep for removing prefixes from paths (which aren't handled well by sed):

echo "$input" | grep -oP "^$prefix\K.*"

\K removes from the match all the characters before it.

Steps to upload an iPhone application to the AppStore

This arstechnica article describes the basic steps:

Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?

Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.

Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.

You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.

The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.

If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.

If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.

Assigning the output of a command to a variable

If you want to do it with multiline/multiple command/s then you can do this:

output=$( bash <<EOF
#multiline/multiple command/s
EOF
)

Or:

output=$(
#multiline/multiple command/s
)

Example:

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

Output:

first
second
third

Defining Z order of views of RelativeLayout in Android

Or put the overlapping button or views inside a FrameLayout. Then, the RelativeLayout in the xml file will respect the order of child layouts as they added.

How do I add a linker or compile flag in a CMake file?

You can also add linker flags to a specific target using the LINK_FLAGS property:

set_property(TARGET ${target} APPEND_STRING PROPERTY LINK_FLAGS " ${flag}")

If you want to propagate this change to other targets, you can create a dummy target to link to.

Python: how to print range a-z?

import string

string.printable[10:36]
# abcdefghijklmnopqrstuvwxyz
    
string.printable[10:62]
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Try this, it will combine your arrays removing duplicates

array1 = ["foo", "bar"]
array2 = ["foo1", "bar1"]

array3 = array1|array2

http://www.ruby-doc.org/core/classes/Array.html

Further documentation look at "Set Union"

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

That happened to me too, because I was trying to get an IEnumerable but the response had a single value. Please try to make sure it's a list of data in your response. The lines I used (for api url get) to solve the problem are like these:

HttpResponseMessage response = await client.GetAsync("api/yourUrl");

if (response.IsSuccessStatusCode)
{
    IEnumerable<RootObject> rootObjects =
        awaitresponse.Content.ReadAsAsync<IEnumerable<RootObject>>();

    foreach (var rootObject in rootObjects)
    {
        Console.WriteLine(
            "{0}\t${1}\t{2}",
            rootObject.Data1, rootObject.Data2, rootObject.Data3);
    }

    Console.ReadLine();
}

Hope It helps.

Enable/Disable Anchor Tags using AngularJS

My problem was slightly different: I have anchor tags that define an href, and I want to use ng-disabled to prevent the link from going anywhere when clicked. The solution is to un-set the href when the link is disabled, like this:

<a ng-href="{{isDisabled ? '' : '#/foo'}}"
   ng-disabled="isDisabled">Foo</a>

In this case, ng-disabled is only used for styling the element.

If you want to avoid using unofficial attributes, you'll need to style it yourself:

<style>
a.disabled {
    color: #888;
}
</style>
<a ng-href="{{isDisabled ? '' : '#/foo'}}"
   ng-class="{disabled: isDisabled}">Foo</a>

ImageMagick security policy 'PDF' blocking conversion

As pointed out in some comments, you need to edit the policies of ImageMagick in /etc/ImageMagick-7/policy.xml. More particularly, in ArchLinux at the time of writing (05/01/2019) the following line is uncommented:

<policy domain="coder" rights="none" pattern="{PS,PS2,PS3,EPS,PDF,XPS}" />

Just wrap it between <!-- and --> to comment it, and pdf conversion should work again.

Best practices for circular shift (rotate) operations in C++

See also an earlier version of this answer on another rotate question with some more details about what asm gcc/clang produce for x86.

The most compiler-friendly way to express a rotate in C and C++ that avoids any Undefined Behaviour seems to be John Regehr's implementation. I've adapted it to rotate by the width of the type (using fixed-width types like uint32_t).

#include <stdint.h>   // for uint32_t
#include <limits.h>   // for CHAR_BIT
// #define NDEBUG
#include <assert.h>

static inline uint32_t rotl32 (uint32_t n, unsigned int c)
{
  const unsigned int mask = (CHAR_BIT*sizeof(n) - 1);  // assumes width is a power of 2.

  // assert ( (c<=mask) &&"rotate by type width or more");
  c &= mask;
  return (n<<c) | (n>>( (-c)&mask ));
}

static inline uint32_t rotr32 (uint32_t n, unsigned int c)
{
  const unsigned int mask = (CHAR_BIT*sizeof(n) - 1);

  // assert ( (c<=mask) &&"rotate by type width or more");
  c &= mask;
  return (n>>c) | (n<<( (-c)&mask ));
}

Works for any unsigned integer type, not just uint32_t, so you could make versions for other sizes.

See also a C++11 template version with lots of safety checks (including a static_assert that the type width is a power of 2), which isn't the case on some 24-bit DSPs or 36-bit mainframes, for example.

I'd recommend only using the template as a back-end for wrappers with names that include the rotate width explicitly. Integer-promotion rules mean that rotl_template(u16 & 0x11UL, 7) would do a 32 or 64-bit rotate, not 16 (depending on the width of unsigned long). Even uint16_t & uint16_t is promoted to signed int by C++'s integer-promotion rules, except on platforms where int is no wider than uint16_t.


On x86, this version inlines to a single rol r32, cl (or rol r32, imm8) with compilers that grok it, because the compiler knows that x86 rotate and shift instructions mask the shift-count the same way the C source does.

Compiler support for this UB-avoiding idiom on x86, for uint32_t x and unsigned int n for variable-count shifts:

  • clang: recognized for variable-count rotates since clang3.5, multiple shifts+or insns before that.
  • gcc: recognized for variable-count rotates since gcc4.9, multiple shifts+or insns before that. gcc5 and later optimize away the branch and mask in the wikipedia version, too, using just a ror or rol instruction for variable counts.
  • icc: supported for variable-count rotates since ICC13 or earlier. Constant-count rotates use shld edi,edi,7 which is slower and takes more bytes than rol edi,7 on some CPUs (especially AMD, but also some Intel), when BMI2 isn't available for rorx eax,edi,25 to save a MOV.
  • MSVC: x86-64 CL19: Only recognized for constant-count rotates. (The wikipedia idiom is recognized, but the branch and AND aren't optimized away). Use the _rotl / _rotr intrinsics from <intrin.h> on x86 (including x86-64).

gcc for ARM uses an and r1, r1, #31 for variable-count rotates, but still does the actual rotate with a single instruction: ror r0, r0, r1. So gcc doesn't realize that rotate-counts are inherently modular. As the ARM docs say, "ROR with shift length, n, more than 32 is the same as ROR with shift length n-32". I think gcc gets confused here because left/right shifts on ARM saturate the count, so a shift by 32 or more will clear the register. (Unlike x86, where shifts mask the count the same as rotates). It probably decides it needs an AND instruction before recognizing the rotate idiom, because of how non-circular shifts work on that target.

Current x86 compilers still use an extra instruction to mask a variable count for 8 and 16-bit rotates, probably for the same reason they don't avoid the AND on ARM. This is a missed optimization, because performance doesn't depend on the rotate count on any x86-64 CPU. (Masking of counts was introduced with 286 for performance reasons because it handled shifts iteratively, not with constant-latency like modern CPUs.)

BTW, prefer rotate-right for variable-count rotates, to avoid making the compiler do 32-n to implement a left rotate on architectures like ARM and MIPS that only provide a rotate-right. (This optimizes away with compile-time-constant counts.)

Fun fact: ARM doesn't really have dedicated shift/rotate instructions, it's just MOV with the source operand going through the barrel-shifter in ROR mode: mov r0, r0, ror r1. So a rotate can fold into a register-source operand for an EOR instruction or something.


Make sure you use unsigned types for n and the return value, or else it won't be a rotate. (gcc for x86 targets does arithmetic right shifts, shifting in copies of the sign-bit rather than zeroes, leading to a problem when you OR the two shifted values together. Right-shifts of negative signed integers is implementation-defined behaviour in C.)

Also, make sure the shift count is an unsigned type, because (-n)&31 with a signed type could be one's complement or sign/magnitude, and not the same as the modular 2^n you get with unsigned or two's complement. (See comments on Regehr's blog post). unsigned int does well on every compiler I've looked at, for every width of x. Some other types actually defeat the idiom-recognition for some compilers, so don't just use the same type as x.


Some compilers provide intrinsics for rotates, which is far better than inline-asm if the portable version doesn't generate good code on the compiler you're targeting. There aren't cross-platform intrinsics for any compilers that I know of. These are some of the x86 options:

  • Intel documents that <immintrin.h> provides _rotl and _rotl64 intrinsics, and same for right shift. MSVC requires <intrin.h>, while gcc require <x86intrin.h>. An #ifdef takes care of gcc vs. icc, but clang doesn't seem to provide them anywhere, except in MSVC compatibility mode with -fms-extensions -fms-compatibility -fms-compatibility-version=17.00. And the asm it emits for them sucks (extra masking and a CMOV).
  • MSVC: _rotr8 and _rotr16.
  • gcc and icc (not clang): <x86intrin.h> also provides __rolb/__rorb for 8-bit rotate left/right, __rolw/__rorw (16-bit), __rold/__rord (32-bit), __rolq/__rorq (64-bit, only defined for 64-bit targets). For narrow rotates, the implementation uses __builtin_ia32_rolhi or ...qi, but the 32 and 64-bit rotates are defined using shift/or (with no protection against UB, because the code in ia32intrin.h only has to work on gcc for x86). GNU C appears not to have any cross-platform __builtin_rotate functions the way it does for __builtin_popcount (which expands to whatever's optimal on the target platform, even if it's not a single instruction). Most of the time you get good code from idiom-recognition.

// For real use, probably use a rotate intrinsic for MSVC, or this idiom for other compilers.  This pattern of #ifdefs may be helpful
#if defined(__x86_64__) || defined(__i386__)

#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>  // Not just <immintrin.h> for compilers other than icc
#endif

uint32_t rotl32_x86_intrinsic(rotwidth_t x, unsigned n) {
  //return __builtin_ia32_rorhi(x, 7);  // 16-bit rotate, GNU C
  return _rotl(x, n);  // gcc, icc, msvc.  Intel-defined.
  //return __rold(x, n);  // gcc, icc.
  // can't find anything for clang
}
#endif

Presumably some non-x86 compilers have intrinsics, too, but let's not expand this community-wiki answer to include them all. (Maybe do that in the existing answer about intrinsics).


(The old version of this answer suggested MSVC-specific inline asm (which only works for 32bit x86 code), or http://www.devx.com/tips/Tip/14043 for a C version. The comments are replying to that.)

Inline asm defeats many optimizations, especially MSVC-style because it forces inputs to be stored/reloaded. A carefully-written GNU C inline-asm rotate would allow the count to be an immediate operand for compile-time-constant shift counts, but it still couldn't optimize away entirely if the value to be shifted is also a compile-time constant after inlining. https://gcc.gnu.org/wiki/DontUseInlineAsm.

Add / remove input field dynamically with jQuery

In your click function, you can write:

function addMoreRows(frm) {
   rowCount ++;
   var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="" type="text" size="17%"  maxlength="120" /></td><td><input name="" type="text"  maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input name="" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> <a href="javascript:void(0);" onclick="removeRow('+rowCount+');">Delete</a></p>';
   jQuery('#addedRows').append(recRow);
}

Or follow this link: http://www.discussdesk.com/add-remove-more-rows-dynamically-using-jquery.htm

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

getElementById will return false if the element was not found in the DOM.

var el = document.getElementById("customx");
if (el !== null && el.value === "")
{
  //The element was found and the value is empty.
}

create table in postgreSQL

-- Table: "user"

-- DROP TABLE "user";

CREATE TABLE "user"
(
  id bigserial NOT NULL,
  name text NOT NULL,
  email character varying(20) NOT NULL,
  password text NOT NULL,
  CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "user"
  OWNER TO postgres;

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Static constant string (class member)

To use that in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression.

This is the restriction. Hence, in this case you need to define variable outside the class. refer answwer from @AndreyT

Changing button text onclick

It seems like there is just a simple typo error:

  1. Remove the semicolon after change(), there should not be any in the function declaration.
  2. Add a quote in front of the myButton1 declaration.

Corrected code:

<input onclick="change()" type="button" value="Open Curtain" id="myButton1" />
...
function change()
{
    document.getElementById("myButton1").value="Close Curtain"; 
}

A faster and simpler solution would be to include the code in your button and use the keyword this to access the button.

<input onclick="this.value='Close Curtain'" type="button" value="Open Curtain" id="myButton1" />

How to uninstall/upgrade Angular CLI?

Ran into this recently myself on mac, had to remove the ng folder from /usr/local/bin. Was so long ago that I installed the Angular CLI, I'm not entirely sure how I installed it originally.

Possible to access MVC ViewBag object from Javascript file?

Not in a JavaScript file, no.
Your JavaScript file could contains a class and you could instantiate a new instance of that class in the View, then you can pass ViewBag values in the class constructor.

Or if it's not a class, your only other alternative, is to use data attributes in your HTML elements, assign them to properties in your View and retrieve them in the JS file.

Assuming you had this input:

<input type="text" id="myInput" data-myValue="@ViewBag.MyValue" />

Then in your JS file you could get it by using:

var myVal = $("#myInput").data("myValue");

How to get the latest tag name in current branch in Git?

git tag -l ac* | tail -n1

Get the last tag with prefix "ac". For example, tag named with ac1.0.0, or ac1.0.5. Other tags named 1.0.0, 1.1.0 will be ignored.

git tag -l [0-9].* | tail -n1

Get the last tag, whose first char is 0-9. So, those tags with first char a-z will be ignored.

More info

git tag --help # Help for `git tag`

git tag -l <pattern>

List tags with names that match the given pattern (or all if no pattern is given). Running "git tag" without arguments also lists all tags. The pattern is a shell wildcard (i.e., matched using fnmatch(3)). Multiple patterns may be given; if any of them matches, the tag is shown.


tail -n <number> # display the last part of a file
tail -n1 # Display the last item 

Update

With git tag --help, about the sort argument. It will use lexicorgraphic order by default, if tag.sort property doesn't exist.

Sort order defaults to the value configured for the tag.sort variable if it exists, or lexicographic order otherwise. See git-config(1).

After google, someone said git 2.8.0 support following syntax.

git tag --sort=committerdate

Objective-C : BOOL vs bool

At the time of writing this is the most recent version of objc.h:

/// Type to represent a boolean value.
#if (TARGET_OS_IPHONE && __LP64__)  ||  TARGET_OS_WATCH
#define OBJC_BOOL_IS_BOOL 1
typedef bool BOOL;
#else
#define OBJC_BOOL_IS_CHAR 1
typedef signed char BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#endif

It means that on 64-bit iOS devices and on WatchOS BOOL is exactly the same thing as bool while on all other devices (OS X, 32-bit iOS) it is signed char and cannot even be overridden by compiler flag -funsigned-char

It also means that this example code will run differently on different platforms (tested it myself):

int myValue = 256;
BOOL myBool = myValue;
if (myBool) {
    printf("i'm 64-bit iOS");
} else {
    printf("i'm 32-bit iOS");
}

BTW never assign things like array.count to BOOL variable because about 0.4% of possible values will be negative.

OpenCV Python rotate image by X degrees around specific point

Quick tweak to @alex-rodrigues answer... deals with shape including the number of channels.

import cv2
import numpy as np

def rotateImage(image, angle):
    center=tuple(np.array(image.shape[0:2])/2)
    rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
    return cv2.warpAffine(image, rot_mat, image.shape[0:2],flags=cv2.INTER_LINEAR)

Does JavaScript have a built in stringbuilder class?

In C# you can do something like

 String.Format("hello {0}, your age is {1}.",  "John",  29) 

In JavaScript you could do something like

 var x = "hello {0}, your age is {1}";
 x = x.replace(/\{0\}/g, "John");
 x = x.replace(/\{1\}/g, 29);

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

I have been using this change in my code :

old code :

 <td>
  @Html.DisplayFor(modelItem => item.dataakt)
 </td>

new :

<td>
 @Convert.ToDateTime(item.dataakt).ToString("dd/MM/yyyy")
</td>

Limiting the number of characters in a JTextField

Here is an optimized version of npinti's answer:

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import java.awt.*;

public class TextComponentLimit extends PlainDocument
{
    private int charactersLimit;

    private TextComponentLimit(int charactersLimit)
    {
        this.charactersLimit = charactersLimit;
    }

    @Override
    public void insertString(int offset, String input, AttributeSet attributeSet) throws BadLocationException
    {
        if (isAllowed(input))
        {
            super.insertString(offset, input, attributeSet);
        } else
        {
            Toolkit.getDefaultToolkit().beep();
        }
    }

    private boolean isAllowed(String string)
    {
        return (getLength() + string.length()) <= charactersLimit;
    }

    public static void addTo(JTextComponent textComponent, int charactersLimit)
    {
        TextComponentLimit textFieldLimit = new TextComponentLimit(charactersLimit);
        textComponent.setDocument(textFieldLimit);
    }
}

To add a limit to your JTextComponent, simply write the following line of code:

JTextFieldLimit.addTo(myTextField, myMaximumLength);

Get path from open file in Python

The key here is the name attribute of the f object representing the opened file. You get it like that:

>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> f.name
'/Users/Desktop/febROSTER2012.xls'

Does it help?

How do I get the last day of a month?

From DateTimePicker:

First date:

DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);

Last date:

DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));

Using Jquery Datatable with AngularJs

visit this link for reference:http://codepen.io/kalaiselvan/pen/RRBzda

<script>  
var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope){
  $scope.data=[
        [
            "Tiger Nixon",
            "System Architect",
            "Edinburgh",
            "5421",
            "2011\/04\/25",
            "$320,800"
        ],
        [
            "Garrett Winters",
            "Accountant",
            "Tokyo",
            "8422",
            "2011\/07\/25",
            "$170,750"
        ],
        [
            "Ashton Cox",
            "Junior Technical Author",
            "San Francisco",
            "1562",
            "2009\/01\/12",
            "$86,000"
        ],
        [
            "Cedric Kelly",
            "Senior Javascript Developer",
            "Edinburgh",
            "6224",
            "2012\/03\/29",
            "$433,060"
        ],
        [
            "Airi Satou",
            "Accountant",
            "Tokyo",
            "5407",
            "2008\/11\/28",
            "$162,700"
        ],
        [
            "Brielle Williamson",
            "Integration Specialist",
            "New York",
            "4804",
            "2012\/12\/02",
            "$372,000"
        ],
        [
            "Herrod Chandler",
            "Sales Assistant",
            "San Francisco",
            "9608",
            "2012\/08\/06",
            "$137,500"
        ],
        [
            "Rhona Davidson",
            "Integration Specialist",
            "Tokyo",
            "6200",
            "2010\/10\/14",
            "$327,900"
        ],
        [
            "Colleen Hurst",
            "Javascript Developer",
            "San Francisco",
            "2360",
            "2009\/09\/15",
            "$205,500"
        ],
        [
            "Sonya Frost",
            "Software Engineer",
            "Edinburgh",
            "1667",
            "2008\/12\/13",
            "$103,600"
        ],
        [
            "Jena Gaines",
            "Office Manager",
            "London",
            "3814",
            "2008\/12\/19",
            "$90,560"
        ],
        [
            "Quinn Flynn",
            "Support Lead",
            "Edinburgh",
            "9497",
            "2013\/03\/03",
            "$342,000"
        ],
        [
            "Charde Marshall",
            "Regional Director",
            "San Francisco",
            "6741",
            "2008\/10\/16",
            "$470,600"
        ],
        [
            "Haley Kennedy",
            "Senior Marketing Designer",
            "London",
            "3597",
            "2012\/12\/18",
            "$313,500"
        ],
        [
            "Tatyana Fitzpatrick",
            "Regional Director",
            "London",
            "1965",
            "2010\/03\/17",
            "$385,750"
        ],
        [
            "Michael Silva",
            "Marketing Designer",
            "London",
            "1581",
            "2012\/11\/27",
            "$198,500"
        ],
        [
            "Paul Byrd",
            "Chief Financial Officer (CFO)",
            "New York",
            "3059",
            "2010\/06\/09",
            "$725,000"
        ],
        [
            "Gloria Little",
            "Systems Administrator",
            "New York",
            "1721",
            "2009\/04\/10",
            "$237,500"
        ],
        [
            "Bradley Greer",
            "Software Engineer",
            "London",
            "2558",
            "2012\/10\/13",
            "$132,000"
        ],
        [
            "Dai Rios",
            "Personnel Lead",
            "Edinburgh",
            "2290",
            "2012\/09\/26",
            "$217,500"
        ],
        [
            "Jenette Caldwell",
            "Development Lead",
            "New York",
            "1937",
            "2011\/09\/03",
            "$345,000"
        ],
        [
            "Yuri Berry",
            "Chief Marketing Officer (CMO)",
            "New York",
            "6154",
            "2009\/06\/25",
            "$675,000"
        ],
        [
            "Caesar Vance",
            "Pre-Sales Support",
            "New York",
            "8330",
            "2011\/12\/12",
            "$106,450"
        ],
        [
            "Doris Wilder",
            "Sales Assistant",
            "Sidney",
            "3023",
            "2010\/09\/20",
            "$85,600"
        ],
        [
            "Angelica Ramos",
            "Chief Executive Officer (CEO)",
            "London",
            "5797",
            "2009\/10\/09",
            "$1,200,000"
        ],
        [
            "Gavin Joyce",
            "Developer",
            "Edinburgh",
            "8822",
            "2010\/12\/22",
            "$92,575"
        ],
        [
            "Jennifer Chang",
            "Regional Director",
            "Singapore",
            "9239",
            "2010\/11\/14",
            "$357,650"
        ],
        [
            "Brenden Wagner",
            "Software Engineer",
            "San Francisco",
            "1314",
            "2011\/06\/07",
            "$206,850"
        ],
        [
            "Fiona Green",
            "Chief Operating Officer (COO)",
            "San Francisco",
            "2947",
            "2010\/03\/11",
            "$850,000"
        ],
        [
            "Shou Itou",
            "Regional Marketing",
            "Tokyo",
            "8899",
            "2011\/08\/14",
            "$163,000"
        ],
        [
            "Michelle House",
            "Integration Specialist",
            "Sidney",
            "2769",
            "2011\/06\/02",
            "$95,400"
        ],
        [
            "Suki Burks",
            "Developer",
            "London",
            "6832",
            "2009\/10\/22",
            "$114,500"
        ],
        [
            "Prescott Bartlett",
            "Technical Author",
            "London",
            "3606",
            "2011\/05\/07",
            "$145,000"
        ],
        [
            "Gavin Cortez",
            "Team Leader",
            "San Francisco",
            "2860",
            "2008\/10\/26",
            "$235,500"
        ],
        [
            "Martena Mccray",
            "Post-Sales support",
            "Edinburgh",
            "8240",
            "2011\/03\/09",
            "$324,050"
        ],
        [
            "Unity Butler",
            "Marketing Designer",
            "San Francisco",
            "5384",
            "2009\/12\/09",
            "$85,675"
        ],
        [
            "Howard Hatfield",
            "Office Manager",
            "San Francisco",
            "7031",
            "2008\/12\/16",
            "$164,500"
        ],
        [
            "Hope Fuentes",
            "Secretary",
            "San Francisco",
            "6318",
            "2010\/02\/12",
            "$109,850"
        ],
        [
            "Vivian Harrell",
            "Financial Controller",
            "San Francisco",
            "9422",
            "2009\/02\/14",
            "$452,500"
        ],
        [
            "Timothy Mooney",
            "Office Manager",
            "London",
            "7580",
            "2008\/12\/11",
            "$136,200"
        ],
        [
            "Jackson Bradshaw",
            "Director",
            "New York",
            "1042",
            "2008\/09\/26",
            "$645,750"
        ],
        [
            "Olivia Liang",
            "Support Engineer",
            "Singapore",
            "2120",
            "2011\/02\/03",
            "$234,500"
        ],
        [
            "Bruno Nash",
            "Software Engineer",
            "London",
            "6222",
            "2011\/05\/03",
            "$163,500"
        ],
        [
            "Sakura Yamamoto",
            "Support Engineer",
            "Tokyo",
            "9383",
            "2009\/08\/19",
            "$139,575"
        ],
        [
            "Thor Walton",
            "Developer",
            "New York",
            "8327",
            "2013\/08\/11",
            "$98,540"
        ],
        [
            "Finn Camacho",
            "Support Engineer",
            "San Francisco",
            "2927",
            "2009\/07\/07",
            "$87,500"
        ],
        [
            "Serge Baldwin",
            "Data Coordinator",
            "Singapore",
            "8352",
            "2012\/04\/09",
            "$138,575"
        ],
        [
            "Zenaida Frank",
            "Software Engineer",
            "New York",
            "7439",
            "2010\/01\/04",
            "$125,250"
        ],
        [
            "Zorita Serrano",
            "Software Engineer",
            "San Francisco",
            "4389",
            "2012\/06\/01",
            "$115,000"
        ],
        [
            "Jennifer Acosta",
            "Junior Javascript Developer",
            "Edinburgh",
            "3431",
            "2013\/02\/01",
            "$75,650"
        ],
        [
            "Cara Stevens",
            "Sales Assistant",
            "New York",
            "3990",
            "2011\/12\/06",
            "$145,600"
        ],
        [
            "Hermione Butler",
            "Regional Director",
            "London",
            "1016",
            "2011\/03\/21",
            "$356,250"
        ],
        [
            "Lael Greer",
            "Systems Administrator",
            "London",
            "6733",
            "2009\/02\/27",
            "$103,500"
        ],
        [
            "Jonas Alexander",
            "Developer",
            "San Francisco",
            "8196",
            "2010\/07\/14",
            "$86,500"
        ],
        [
            "Shad Decker",
            "Regional Director",
            "Edinburgh",
            "6373",
            "2008\/11\/13",
            "$183,000"
        ],
        [
            "Michael Bruce",
            "Javascript Developer",
            "Singapore",
            "5384",
            "2011\/06\/27",
            "$183,000"
        ],
        [
            "Donna Snider",
            "Customer Support",
            "New York",
            "4226",
            "2011\/01\/25",
            "$112,000"
        ]
    ]


$scope.dataTableOpt = {
  //if any ajax call 
  };
});
</script>
<div class="container" ng-app="formvalid">
      <div class="panel" data-ng-controller="validationCtrl">
      <div class="panel-heading border">    
        <h2>Data table using jquery datatable in Angularjs </h2>
      </div>
      <div class="panel-body">
          <table class="table table-bordered bordered table-striped table-condensed datatable" ui-jq="dataTable" ui-options="dataTableOpt">
          <thead>
            <tr>
              <th>#</th>
              <th>Name</th>
              <th>Position</th>
              <th>Office</th>
              <th>Age</th>
              <th>Start Date</th>
            </tr>
          </thead>
            <tbody>
              <tr ng-repeat="n in data">
                <td>{{$index+1}}</td>
                <td>{{n[0]}}</td>
                <td>{{n[1]}}</td>
                <td>{{n[2]}}</td>
                <td>{{n[3]}}</td>
                <td>{{n[4] | date:'dd/MM/yyyy'}}</td>
              </tr>
            </tbody>
        </table>
      </div>
    </div>
    </div>

How to initialize var?

var just tells the compiler to infer the type you wanted at compile time...it cannot infer from null (though there are cases it could).

So, no you are not allowed to do this.

When you say "some empty value"...if you mean:

var s = string.Empty;
//
var s = "";

Then yes, you may do that, but not null.

Find and Replace string in all files recursive using grep and sed

grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'

Getting around the Max String size in a vba function?

Are you sure? This forum thread suggests it might be your watch window. Try outputting the string to a MsgBox, which can display a maximum of 1024 characters:

MsgBox RunMacros

/bin/sh: pushd: not found

Synthesizing from the other responses: pushd is bash-specific and you are make is using another POSIX shell. There is a simple workaround to use separate shell for the part that needs different directory, so just try changing it to:

test -z gen || mkdir -p gen \
 && ( cd $(CURRENT_DIRECTORY)/genscript > /dev/null \
 && perl genmakefile.pl \
 && mv Makefile ../gen/ ) \
 && echo "" > $(CURRENT_DIRECTORY)/gen/SvcGenLog

(I substituted the long path with a variable expansion. I probably is one in the makefile and it clearly expands to the current directory).

Since you are running it from make, I would probably replace the test with a make rule, too. Just

gen/SvcGenLog :
    mkdir -p gen
    cd genscript > /dev/null \
     && perl genmakefile.pl \
     && mv Makefile ../gen/ \
    echo "" > gen/SvcGenLog

(dropped the current directory prefix; you were using relative path at some points anyway) And than just make the rule depend on gen/SvcGenLog. It would be a bit more readable and you can make it depend on the genscript/genmakefile.pl too, so the Makefile in gen will be regenerated if you modify the script. Of course if anything else affects the content of the Makefile, you can make the rule depend on that too.

How to create an empty DataFrame with a specified schema?

As of Spark 2.4.3

val df = SparkSession.builder().getOrCreate().emptyDataFrame

Do fragments really need an empty constructor?

Yes they do.

You shouldn't really be overriding the constructor anyway. You should have a newInstance() static method defined and pass any parameters via arguments (bundle)

For example:

public static final MyFragment newInstance(int title, String message) {
    MyFragment f = new MyFragment();
    Bundle bdl = new Bundle(2);
    bdl.putInt(EXTRA_TITLE, title);
    bdl.putString(EXTRA_MESSAGE, message);
    f.setArguments(bdl);
    return f;
}

And of course grabbing the args this way:

@Override
public void onCreate(Bundle savedInstanceState) {
    title = getArguments().getInt(EXTRA_TITLE);
    message = getArguments().getString(EXTRA_MESSAGE);

    //...
    //etc
    //...
}

Then you would instantiate from your fragment manager like so:

@Override
public void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState == null){
        getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.content, MyFragment.newInstance(
                R.string.alert_title,
                "Oh no, an error occurred!")
            )
            .commit();
    }
}

This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.

Reason - Extra reading

I thought I would explain why for people wondering why.

If you check: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Fragment.java

You will see the instantiate(..) method in the Fragment class calls the newInstance method:

public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
    try {
        Class<?> clazz = sClassMap.get(fname);
        if (clazz == null) {
            // Class not found in the cache, see if it's real, and try to add it
            clazz = context.getClassLoader().loadClass(fname);
            if (!Fragment.class.isAssignableFrom(clazz)) {
                throw new InstantiationException("Trying to instantiate a class " + fname
                        + " that is not a Fragment", new ClassCastException());
            }
            sClassMap.put(fname, clazz);
        }
        Fragment f = (Fragment) clazz.getConstructor().newInstance();
        if (args != null) {
            args.setClassLoader(f.getClass().getClassLoader());
            f.setArguments(args);
        }
        return f;
    } catch (ClassNotFoundException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (java.lang.InstantiationException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (IllegalAccessException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (NoSuchMethodException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": could not find Fragment constructor", e);
    } catch (InvocationTargetException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": calling Fragment constructor caused an exception", e);
    }
}

http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance() Explains why, upon instantiation it checks that the accessor is public and that that class loader allows access to it.

It's a pretty nasty method all in all, but it allows the FragmentManger to kill and recreate Fragments with states. (The Android subsystem does similar things with Activities).

Example Class

I get asked a lot about calling newInstance. Do not confuse this with the class method. This whole class example should show the usage.

/**
 * Created by chris on 21/11/2013
 */
public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener {

    public static final StationInfoAccessibilityFragment newInstance(String crsCode) {
        StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment();

        final Bundle args = new Bundle(1);
        args.putString(EXTRA_CRS_CODE, crsCode);
        fragment.setArguments(args);

        return fragment;
    }

    // Views
    LinearLayout mLinearLayout;

    /**
     * Layout Inflater
     */
    private LayoutInflater mInflater;
    /**
     * Station Crs Code
     */
    private String mCrsCode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCrsCode = getArguments().getString(EXTRA_CRS_CODE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mInflater = inflater;
        return inflater.inflate(R.layout.fragment_station_accessibility, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLinearLayout = (LinearLayout)view.findViewBy(R.id.station_info_accessibility_linear);
        //Do stuff
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().getSupportActionBar().setTitle(R.string.station_info_access_mobility_title);
    }

    // Other methods etc...
}

How do I shrink my SQL Server Database?

Delete data, make sure recovery model is simple, then skrink (either shrink database or shrink files works). If the data file is still too big, AND you use heaps to store data -- that is, no clustered index on large tables -- then you might have this problem regarding deleting data from heaps: http://support.microsoft.com/kb/913399

How to get the error message from the error code returned by GetLastError()?

GetLastError returns a numerical error code. To obtain a descriptive error message (e.g., to display to a user), you can call FormatMessage:

// This functions fills a caller-defined character buffer (pBuffer)
// of max length (cchBufferLength) with the human-readable error message
// for a Win32 error code (dwErrorCode).
// 
// Returns TRUE if successful, or FALSE otherwise.
// If successful, pBuffer is guaranteed to be NUL-terminated.
// On failure, the contents of pBuffer are undefined.
BOOL GetErrorMessage(DWORD dwErrorCode, LPTSTR pBuffer, DWORD cchBufferLength)
{
    if (cchBufferLength == 0)
    {
        return FALSE;
    }

    DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                                 NULL,  /* (not used with FORMAT_MESSAGE_FROM_SYSTEM) */
                                 dwErrorCode,
                                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                                 pBuffer,
                                 cchBufferLength,
                                 NULL);
    return (cchMsg > 0);
}

In C++, you can simplify the interface considerably by using the std::string class:

#include <Windows.h>
#include <system_error>
#include <memory>
#include <string>
typedef std::basic_string<TCHAR> String;

String GetErrorMessage(DWORD dwErrorCode)
{
    LPTSTR psz{ nullptr };
    const DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
                                         | FORMAT_MESSAGE_IGNORE_INSERTS
                                         | FORMAT_MESSAGE_ALLOCATE_BUFFER,
                                       NULL, // (not used with FORMAT_MESSAGE_FROM_SYSTEM)
                                       dwErrorCode,
                                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                                       reinterpret_cast<LPTSTR>(&psz),
                                       0,
                                       NULL);
    if (cchMsg > 0)
    {
        // Assign buffer to smart pointer with custom deleter so that memory gets released
        // in case String's c'tor throws an exception.
        auto deleter = [](void* p) { ::LocalFree(p); };
        std::unique_ptr<TCHAR, decltype(deleter)> ptrBuffer(psz, deleter);
        return String(ptrBuffer.get(), cchMsg);
    }
    else
    {
        auto error_code{ ::GetLastError() };
        throw std::system_error( error_code, std::system_category(),
                                 "Failed to retrieve error message string.");
    }
}

NOTE: These functions also work for HRESULT values. Just change the first parameter from DWORD dwErrorCode to HRESULT hResult. The rest of the code can remain unchanged.


These implementations provide the following improvements over the existing answers:

  • Complete sample code, not just a reference to the API to call.
  • Provides both C and C++ implementations.
  • Works for both Unicode and MBCS project settings.
  • Takes the error code as an input parameter. This is important, as a thread's last error code is only valid at well defined points. An input parameter allows the caller to follow the documented contract.
  • Implements proper exception safety. Unlike all of the other solutions that implicitly use exceptions, this implementation will not leak memory in case an exception is thrown while constructing the return value.
  • Proper use of the FORMAT_MESSAGE_IGNORE_INSERTS flag. See The importance of the FORMAT_MESSAGE_IGNORE_INSERTS flag for more information.
  • Proper error handling/error reporting, unlike some of the other answers, that silently ignore errors.


This answer has been incorporated from Stack Overflow Documentation. The following users have contributed to the example: stackptr, Ajay, Cody Gray?, IInspectable.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Not really answer to the question, but one-liners for foldl and foldr:

a = [8,3,4]

## Foldl
reduce(lambda x,y: x**y, a)
#68719476736

## Foldr
reduce(lambda x,y: y**x, a[::-1])
#14134776518227074636666380005943348126619871175004951664972849610340958208L

Find size of Git repository

Note that, since git 1.8.3 (April, 22d 2013):

"git count-objects" learned "--human-readable" aka "-H" option to show various large numbers in Ki/Mi/GiB scaled as necessary.

That could be combined with the -v option mentioned by Jack Morrison in his answer.

git gc
git count-objects -vH

(git gc is important, as mentioned by A-B-B's answer)

Plus (still git 1.8.3), the output is more complete:

"git count-objects -v" learned to report leftover temporary packfiles and other garbage in the object store.

How to remove duplicates from a list?

I suspect you might not have Customer.equals() implemented properly (or at all).

List.contains() uses equals() to verify whether any of its elements is identical to the object passed as parameter. However, the default implementation of equals tests for physical identity, not value identity. So if you have not overwritten it in Customer, it will return false for two distinct Customer objects having identical state.

Here are the nitty-gritty details of how to implement equals (and hashCode, which is its pair - you must practically always implement both if you need to implement either of them). Since you haven't shown us the Customer class, it is difficult to give more concrete advice.

As others have noted, you are better off using a Set rather than doing the job by hand, but even for that, you still need to implement those methods.

IsNullOrEmpty with Object

You can simply compare it with System.DBNull.Value

scroll up and down a div on button click using jquery

Scrolling div on click of button.

Html Code:-

 <div id="textBody" style="height:200px; width:600px; overflow:auto;">
    <!------Your content---->
 </div>

JQuery code for scrolling div:-

$(function() {
   $( "#upBtn" ).click(function(){
      $('#textBody').scrollTop($('#textBody').scrollTop()-20);
 }); 

 $( "#downBtn" ).click(function(){
     $('#textBody').scrollTop($('#textBody').scrollTop()+20);;
 }); 

});