Programs & Examples On #Jna

Java Native Access (JNA) provides pure Java access to native shared libraries without the need for additional native or JNI code.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

You did not post the code generated by the compiler, so there' some guesswork here, but even without having seen it, one can say that this:

test rax, 1
jpe even

... has a 50% chance of mispredicting the branch, and that will come expensive.

The compiler almost certainly does both computations (which costs neglegibly more since the div/mod is quite long latency, so the multiply-add is "free") and follows up with a CMOV. Which, of course, has a zero percent chance of being mispredicted.

Min / Max Validator in Angular 2 Final

In latest Angular versions, min and max are already added. Here is the link: https://angular.io/api/forms/Validators#max

This is how I used Max validator in my project:

<mat-form-field class="globalInput">
          <input (change)="CalculateAmount()" matInput placeholder="Quantity" name="productQuantity" type="number" [formControl]="quantityFormControl">
        </mat-form-field>
        <mat-error *ngIf="quantityFormControl.hasError('max')">
          Only <strong>{{productQuantity}}</strong> available!
        </mat-error>

Initialize the form control and add the validator in the component:

  quantityFormControl = new FormControl('', Validators.max(15));

You can also set validator dynamically on an event like this:

  quantityFormControl = new FormControl();

OnProductSelected(){
    this.quantityFormControl.setValidators(Validators.max(this.someVariable));
  }

Hope it helps.

Django: OperationalError No Such Table

This happened to me and for me it was because I added db.sqlite3 as untracked from repository. I added it and pushed it to server so it worked properly. Also run makemigartions and migrate after doing this.

Sonar properties files

Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem

Putty: Getting Server refused our key Error

I have this issue where sshd only reads from authorized_keys2.

Copying or renaming the file fixed the problem for me.

cd  ~/.ssh
sudo cat authorized_keys >> authorized_keys2

P.S. I'm using Putty from Windows and used PuTTyKeygen for key pair generation.

Jinja2 template variable if None Object set a default value

You can simply add "default none" to your variable as the form below mentioned:

{{ your_var | default('NONE', boolean=true) }}

"java.lang.OutOfMemoryError : unable to create new native Thread"

If your Job is failing because of OutOfMemmory on nodes you can tweek your number of max maps and reducers and the JVM opts for each. mapred.child.java.opts (the default is 200Xmx) usually has to be increased based on your data nodes specific hardware.

This link might be helpful... pls check

Entity Framework Migrations renaming tables and columns

Nevermind. I was making this way more complicated than it really needed to be.

This was all that I needed. The rename methods just generate a call to the sp_rename system stored procedure and I guess that took care of everything, including the foreign keys with the new column name.

public override void Up()
{
    RenameTable("ReportSections", "ReportPages");
    RenameTable("ReportSectionGroups", "ReportSections");
    RenameColumn("ReportPages", "Group_Id", "Section_Id");
}

public override void Down()
{
    RenameColumn("ReportPages", "Section_Id", "Group_Id");
    RenameTable("ReportSections", "ReportSectionGroups");
    RenameTable("ReportPages", "ReportSections");
}

How does Java import work?

javac (or java during runtime) looks for the classes being imported in the classpath. If they are not there in the classpath then classnotfound exceptions are thrown.

classpath is just like the path variable in a shell, which is used by the shell to find a command or executable.

Entire directories or individual jar files can be put in the classpath. Also, yes a classpath can perhaps include a path which is not local but is somewhere on the internet. Please read more about classpath to resolve your doubts.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

It's been a while, but last time I had something similar:

ROLLBACK TRAN

or trying to

COMMIT

what had allready been done free'd everything up so I was able to clear things out and start again.

Javascript use variable as object name

Use square bracket around variable name.

var objname = 'myobject';
{[objname]}.value = 'value';

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

I tried every possible solution on this web site and nothing worked for me. I ended up doing in the design mode. Right click on the table name and then click design. Then I changed the name and saved here. Worked simply.

Memory address of variables in Java

In Java when you are making an object from a class like Person p = new Person();, p is actually an address of a memory location which is pointing to a type of Person.

When use a statemenet to print p you will see an address. The new key word makes a new memory location containing all the instance variables and methods which are included in class Person and p is the reference variable pointing to that memory location.

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

@RequestParam is the HTTP GET or POST parameter sent by client, request mapping is a segment of URL which's variable:

http:/host/form_edit?param1=val1&param2=val2

var1 & var2 are request params.

http:/host/form/{params}

{params} is a request mapping. you could call your service like : http:/host/form/user or http:/host/form/firm where firm & user are used as Pathvariable.

Classes vs. Functions

Classes (or rather their instances) are for representing things. Classes are used to define the operations supported by a particular class of objects (its instances). If your application needs to keep track of people, then Person is probably a class; the instances of this class represent particular people you are tracking.

Functions are for calculating things. They receive inputs and produce an output and/or have effects.

Classes and functions aren't really alternatives, as they're not for the same things. It doesn't really make sense to consider making a class to "calculate the age of a person given his/her birthday year and the current year". You may or may not have classes to represent any of the concepts of Person, Age, Year, and/or Birthday. But even if Age is a class, it shouldn't be thought of as calculating a person's age; rather the calculation of a person's age results in an instance of the Age class.

If you are modelling people in your application and you have a Person class, it may make sense to make the age calculation be a method of the Person class. A method is basically a function which is defined as part of a class; this is how you "define the operations supported by a particular class of objects" as I mentioned earlier.

So you could create a method on your person class for calculating the age of the person (it would probably retrieve the birthday year from the person object and receive the current year as a parameter). But the calculation is still done by a function (just a function that happens to be a method on a class).

Or you could simply create a stand-alone function that receives arguments (either a person object from which to retrieve a birth year, or simply the birth year itself). As you note, this is much simpler if you don't already have a class where this method naturally belongs! You should never create a class simply to hold an operation; if that's all there is to the class then the operation should just be a stand-alone function.

In a unix shell, how to get yesterday's date into a variable?

On Linux, you can use

date -d "-1 days" +"%a %d/%m/%Y"

SQL Query to fetch data from the last 30 days?

select status, timeplaced 
from orders 
where TIMEPLACED>'2017-06-12 00:00:00' 

JSON formatter in C#?

Fixed it... somewhat.

public class JsonFormatter
{
    #region class members
    const string Space = " ";
    const int DefaultIndent = 0;
    const string Indent = Space + Space + Space + Space;
    static readonly string NewLine = Environment.NewLine;
    #endregion

    private enum JsonContextType
    {
        Object, Array
    }

    static void BuildIndents(int indents, StringBuilder output)
    {
        indents += DefaultIndent;
        for (; indents > 0; indents--)
            output.Append(Indent);
    }


    bool inDoubleString = false;
    bool inSingleString = false;
    bool inVariableAssignment = false;
    char prevChar = '\0';

    Stack<JsonContextType> context = new Stack<JsonContextType>();

    bool InString()
    {
        return inDoubleString || inSingleString;
    }

    public string PrettyPrint(string input)
    {
        var output = new StringBuilder(input.Length * 2);
        char c;

        for (int i = 0; i < input.Length; i++)
        {
            c = input[i];

            switch (c)
            {
                case '{':
                    if (!InString())
                    {
                        if (inVariableAssignment || (context.Count > 0 && context.Peek() != JsonContextType.Array))
                        {
                            output.Append(NewLine);
                            BuildIndents(context.Count, output);
                        }
                        output.Append(c);
                        context.Push(JsonContextType.Object);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                    }
                    else
                        output.Append(c);

                    break;

                case '}':
                    if (!InString())
                    {
                        output.Append(NewLine);
                        context.Pop();
                        BuildIndents(context.Count, output);
                        output.Append(c);
                    }
                    else
                        output.Append(c);

                    break;

                case '[':
                    output.Append(c);

                    if (!InString())
                        context.Push(JsonContextType.Array);

                    break;

                case ']':
                    if (!InString())
                    {
                        output.Append(c);
                        context.Pop();
                    }
                    else
                        output.Append(c);

                    break;

                case '=':
                    output.Append(c);
                    break;

                case ',':
                    output.Append(c);

                    if (!InString() && context.Peek() != JsonContextType.Array)
                    {
                        BuildIndents(context.Count, output);
                        output.Append(NewLine);
                        BuildIndents(context.Count, output);
                        inVariableAssignment = false;
                    }

                    break;

                case '\'':
                    if (!inDoubleString && prevChar != '\\')
                        inSingleString = !inSingleString;

                    output.Append(c);
                    break;

                case ':':
                    if (!InString())
                    {
                        inVariableAssignment = true;
                        output.Append(Space);
                        output.Append(c);
                        output.Append(Space);
                    }
                    else
                        output.Append(c);

                    break;

                case '"':
                    if (!inSingleString && prevChar != '\\')
                        inDoubleString = !inDoubleString;

                    output.Append(c);
                    break;
                case ' ':
                    if (InString())
                        output.Append(c);
                    break;

                default:
                    output.Append(c);
                    break;
            }
            prevChar = c;
        }

        return output.ToString();
    }
}

credit [dead link]

What is the technology behind wechat, whatsapp and other messenger apps?

To my knowledge, Ejabberd (http://www.ejabberd.im/) is the parent, this is XMPP server which provide quite good features of open source, Whatsapp uses some modified version of this, facebook messaging also uses a modified version of this. Some more chat applications likes Samsung's ChatOn, Nimbuzz messenger all use ejabberd based ones and Erlang solutions also have modified version of this ejabberd which they claim to be highly scalable and well tested with more performance improvements and renamed as MongooseIM.

Ejabberd is the server which has most of the featured implemented when compared to other. Since it is build in Erlang it is highly scalable horizontally.

Access to file download dialog in Firefox

I have a solution for this issue, check the code:

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

WebDriver driver = new FirefoxDriver(firefoxProfile);//new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);

driver.navigate().to("http://www.myfile.com/hey.csv");

MassAssignmentException in Laravel

To make all fields fillable, just declare on your class:

protected $guarded = array();

This will enable you to call fill method without declare each field.

How to auto-reload files in Node.js?

I have tried pm2 : installation is easy and easy to use too; the result is satisfying. However, we have to take care of which edition of pm2 that we want. pm 2 runtime is the free edition, whereas pm2 plus and pm2 enterprise are not free.

As for Strongloop, my installation failed or was not complete, so I couldn't use it.

Can't install Scipy through pip

I face same problem when install Scipy under ubuntu.
I had to use command:

$ sudo apt-get install libatlas-base-dev gfortran
$ sudo pip3 install scipy

You can get more details here Installing SciPy with pip
Sorry don't know how to do it under OS X Yosemite.

Remove the string on the beginning of an URL

Depends on what you need, you have a couple of choices, you can do:

// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");

// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);

// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");

How to give Jenkins more heap space when it´s started as a service under Windows?

In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).

SQL: Group by minimum value in one field while selecting distinct rows

This does it simply:

select t2.id,t2.record_date,t2.other_cols 
from (select ROW_NUMBER() over(partition by id order by record_date)as rownum,id,record_date,other_cols from MyTable)t2 
where t2.rownum = 1

CSS set li indent

Also try:

ul {
  list-style-position: inside;
}

Setting up SSL on a local xampp/apache server

I did all of the suggested stuff here and my code still did not work because I was using curl

If you are using curl in the php file, curl seems to reject all ssl traffic by default. A quick-fix that worked for me was to add:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

before calling:

 curl_exec():

in the php file.

I believe that this disables all verification of SSL certificates.

Merge two array of objects based on a key

This is a version when you have an object and an array and you want to merge them and give the array a key value so it fits into the object nicely.

_x000D_
_x000D_
var fileData = [_x000D_
    { "id" : "1", "filename" : "myfile1", "score" : 33.1 }, _x000D_
    { "id" : "2", "filename" : "myfile2", "score" : 31.4 }, _x000D_
    { "id" : "3", "filename" : "myfile3", "score" : 36.3 }, _x000D_
    { "id" : "4", "filename" : "myfile4", "score" : 23.9 }_x000D_
];_x000D_
_x000D_
var fileQuality = [0.23456543,0.13413131,0.1941344,0.7854522];_x000D_
_x000D_
var newOjbect = fileData.map((item, i) => Object.assign({}, item, {fileQuality:fileQuality[i]}));_x000D_
_x000D_
console.log(newOjbect);
_x000D_
_x000D_
_x000D_

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

How to use particular CSS styles based on screen size / device

Detection is automatic. You must specify what css can be used for each screen resolution:

/* for all screens, use 14px font size */
body {  
    font-size: 14px;    
}
/* responsive, form small screens, use 13px font size */
@media (max-width: 479px) {
    body {
        font-size: 13px;
    }
}

How to render an array of objects in React?

Shubham's answer explains very well. This answer is addition to it as per to avoid some pitfalls and refactoring to a more readable syntax

Pitfall : There is common misconception in rendering array of objects especially if there is an update or delete action performed on data. Use case would be like deleting an item from table row. Sometimes when row which is expected to be deleted, does not get deleted and instead other row gets deleted.

To avoid this, use key prop in root element which is looped over in JSX tree of .map(). Also adding React's Fragment will avoid adding another element in between of ul and li when rendered via calling method.

state = {
    userData: [
        { id: '1', name: 'Joe', user_type: 'Developer' },
        { id: '2', name: 'Hill', user_type: 'Designer' }
    ]
};

deleteUser = id => {
    // delete operation to remove item
};

renderItems = () => {
    const data = this.state.userData;

    const mapRows = data.map((item, index) => (
        <Fragment key={item.id}>
            <li>
                {/* Passing unique value to 'key' prop, eases process for virtual DOM to remove specific element and update HTML tree  */}
                <span>Name : {item.name}</span>
                <span>User Type: {item.user_type}</span>
                <button onClick={() => this.deleteUser(item.id)}>
                    Delete User
                </button>
            </li>
        </Fragment>
    ));
    return mapRows;
};

render() {
    return <ul>{this.renderItems()}</ul>;
}

Important : Decision to use which value should we pass to key prop also matters as common way is to use index parameter provided by .map().

TLDR; But there's a drawback to it and avoid it as much as possible and use any unique id from data which is being iterated such as item.id. There's a good article on this - https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

How to make <div> fill <td> height

This questions is already answered here. Just put height: 100% in both the div and the container td.

Cannot read configuration file due to insufficient permissions

check if the file is not marked as read-only, despite of the IIS_IUSRS permission it will display the same message.

format a Date column in a Data Frame

try this package, works wonders, and was made for date/time...

library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)

Android basics: running code in the UI thread

The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.

TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
    private String txt;
    @Override
    public void run() {
        searchResultTextView.setText(txt);
    }
    public void setText(String txt){
        this.txt = txt;
    }

}

It can be used from anywhere like this:

textViewUpdater.setText("Hello");
        textViewUpdaterHandler.post(textViewUpdater);

SELECT last id, without INSERT

I think to add timestamp to every record and get the latest. In this situation you can get any ids, pack rows and other ops.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

casting Object array to Integer array error

Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.

Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);

Here the reason to hitting an ClassCastException is you can't treat an array of Integer as an array of Object. Integer[] is a subtype of Object[] but Object[] is not a Integer[].

And the following also will not give an ClassCastException.

Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;

onClick function of an input type="button" not working

You've forgot to define an onclick attribute to do something when the button is clicked, so nothing happening is the correct execution, see below;

<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!"  />
                                     ----------------------

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I was getting the same error after adding an unnecessary reference to System.Web.Mvc. I removed all the references I could find, but nothing seemed to work. I finally deleted the project's bin folder and the error went away after a rebuild.

Add horizontal scrollbar to html table

This is an improvement of Serge Stroobandt's answer and works perfectly. It solves the issue of the table not filling the whole page width if it has less columns.

<style> 
 .table_wrapper{
    display: block;
    overflow-x: auto;
    white-space: nowrap;
}
</style>

<div class="table_wrapper">
<table>
...
</table>
</div>

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

unique combinations of values in selected columns in pandas data frame and count

I haven't done time test with this but it was fun to try. Basically convert two columns to one column of tuples. Now convert that to a dataframe, do 'value_counts()' which finds the unique elements and counts them. Fiddle with zip again and put the columns in order you want. You can probably make the steps more elegant but working with tuples seems more natural to me for this problem

b = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})

b['count'] = pd.Series(zip(*[b.A,b.B]))
df = pd.DataFrame(b['count'].value_counts().reset_index())
df['A'], df['B'] = zip(*df['index'])
df = df.drop(columns='index')[['A','B','count']]

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Linux cmd to search for a class file among jars irrespective of jar path

Use deepgrep and deepfind. On debian-based systems you can install them by:

sudo apt-get install strigi-utils

Both commands search for nested archives as well. In your case the command would look like:

find . -name "*.jar" | xargs -I {} deepfind {} | grep Hello.class

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

Easiest way to copy a table from one database to another?

Here is another easy way:

  1. use DB1; show create table TB1;
    • copy the syntax here in clipboard to create TB1 in DB2
  2. use DB2;
    • paste the syntax here to create the table TB1

INSERT INTO DB2.TB1 SELECT * from DB1.TB1;

How does one target IE7 and IE8 with valid CSS?

Explicitly Target IE versions without hacks using HTML and CSS

Use this approach if you don't want hacks in your CSS. Add a browser-unique class to the <html> element so you can select based on browser later.

Example

<!doctype html>
<!--[if IE]><![endif]-->
<!--[if lt IE 7 ]> <html lang="en" class="ie6">    <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="ie7">    <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="ie8">    <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="ie9">    <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
    <head></head>
    <body></body>
</html>

Then in your CSS you can very strictly access your target browser.

Example

.ie6 body { 
    border:1px solid red;
}
.ie7 body { 
    border:1px solid blue;
}

For more information check out http://html5boilerplate.com/

Target IE versions with CSS "Hacks"

More to your point, here are the hacks that let you target IE versions.

Use "\9" to target IE8 and below.
Use "*" to target IE7 and below.
Use "_" to target IE6.

Example:

body { 
border:1px solid red; /* standard */
border:1px solid blue\9; /* IE8 and below */
*border:1px solid orange; /* IE7 and below */
_border:1px solid blue; /* IE6 */
}

Update: Target IE10

IE10 does not recognize the conditional statements so you can use this to apply an "ie10" class to the <html> element

<!doctype html>
    <html lang="en">
    <!--[if !IE]><!--><script>if (/*@cc_on!@*/false) {document.documentElement.className+=' ie10';}</script><!--<![endif]-->
        <head></head>
        <body></body>
</html>

How to display an alert box from C# in ASP.NET?

Hey Try This Code.

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "Data has been saved", true);

Cheers

Undefined symbols for architecture x86_64 on Xcode 6.1

I simply wasn't linking the libraries in the "Link Binary with Libraries" section.

How to check Network port access and display useful message?

Great answer by mshutov & Salselvaprabu. I needed something a little bit more robust, and that checked all IPAddresses that was provided instead of checking only the first one.

I also wanted to replicate some of the parameter names and functionality than the Test-Connection function.

This new function allows you to set a Count for the number of retries, and the Delay between each try. Enjoy!

function Test-Port {

    [CmdletBinding()]
    Param (
        [string] $ComputerName,
        [int] $Port,
        [int] $Delay = 1,
        [int] $Count = 3
    )

    function Test-TcpClient ($IPAddress, $Port) {

        $TcpClient = New-Object Net.Sockets.TcpClient
        Try { $TcpClient.Connect($IPAddress, $Port) } Catch {}

        If ($TcpClient.Connected) { $TcpClient.Close(); Return $True }
        Return $False

    }

    function Invoke-Test ($ComputerName, $Port) {

        Try   { [array]$IPAddress = [System.Net.Dns]::GetHostAddresses($ComputerName) | Select-Object -Expand IPAddressToString } 
        Catch { Return $False }

        [array]$Results = $IPAddress | % { Test-TcpClient -IPAddress $_ -Port $Port }
        If ($Results -contains $True) { Return $True } Else { Return $False }

    }

    for ($i = 1; ((Invoke-Test -ComputerName $ComputerName -Port $Port) -ne $True); $i++)
    {
        if ($i -ge $Count) {
            Write-Warning "Timed out while waiting for port $Port to be open on $ComputerName!"
            Return $false
        }

        Write-Warning "Port $Port not open, retrying..."
        Sleep $Delay
    }

    Return $true

}

Insert variable values in the middle of a string

There's now (C# 6) a more succinct way to do it: string interpolation.

From another question's answer:

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

Filter items which array contains any of given values

There's also terms query which should save you some work. Here example from docs:

{
  "terms" : {
      "tags" : [ "blue", "pill" ],
      "minimum_should_match" : 1
  }
}

Under hood it constructs boolean should. So it's basically the same thing as above but shorter.

There's also a corresponding terms filter.

So to summarize your query could look like this:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tags": ["c", "d"]
      }
    }
  }
}

With greater number of tags this could make quite a difference in length.

how to get the attribute value of an xml node using java

try something like this :

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dDoc = builder.parse("d://utf8test.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        System.out.println(node.getTextContent());
    }

please note the changes :

  • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
  • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()

PS: can you add the tag java to your question ? thanks.

No mapping found for HTTP request with URI Spring MVC

Try passing the Model object in your index method and it will work-

@RequestMapping("/")

public String index(org.springframework.ui.Model model) {

 return "index";

    }

Actually the spring container looks for a Model object in the mapping method. If it finds the same it will pass the returning String as view to the View resolver.

Hope this helps.

How to loop through a plain JavaScript object with the objects as members?

I couldn't get the above posts to do quite what I was after.

After playing around with the other replies here, I made this. It's hacky, but it works!

For this object:

var myObj = {
    pageURL    : "BLAH",
    emailBox   : {model:"emailAddress", selector:"#emailAddress"},
    passwordBox: {model:"password"    , selector:"#password"}
};

... this code:

// Get every value in the object into a separate array item ...
function buildArray(p_MainObj, p_Name) {
    var variableList = [];
    var thisVar = "";
    var thisYes = false;
    for (var key in p_MainObj) {
       thisVar = p_Name + "." + key;
       thisYes = false;
       if (p_MainObj.hasOwnProperty(key)) {
          var obj = p_MainObj[key];
          for (var prop in obj) {
            var myregex = /^[0-9]*$/;
            if (myregex.exec(prop) != prop) {
                thisYes = true;
                variableList.push({item:thisVar + "." + prop,value:obj[prop]});
            }
          }
          if ( ! thisYes )
            variableList.push({item:thisVar,value:obj});
       }
    }
    return variableList;
}

// Get the object items into a simple array ...
var objectItems = buildArray(myObj, "myObj");

// Now use them / test them etc... as you need to!
for (var x=0; x < objectItems.length; ++x) {
    console.log(objectItems[x].item + " = " + objectItems[x].value);
}

... produces this in the console:

myObj.pageURL = BLAH
myObj.emailBox.model = emailAddress
myObj.emailBox.selector = #emailAddress
myObj.passwordBox.model = password
myObj.passwordBox.selector = #password

array_push() with key value pair

For Example:

$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');

For changing key value:

$data['firstKey'] = 'changedValue'; 
//this will change value of firstKey because firstkey is available in array

output:

Array ( [firstKey] => changedValue [secondKey] => secondValue )

For adding new key value pair:

$data['newKey'] = 'newValue'; 
//this will add new key and value because newKey is not available in array

output:

Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue )

Accessing bash command line args $@ vs $*

$@ is same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.

Of course, "$@" should be quoted.

http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST

Java string to date conversion

Try this

String date = get_pump_data.getString("bond_end_date");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date datee = (Date)format.parse(date);

How to fix Python indentation

I have a simple solution for this problem. You can first type ":retab" and then ":retab!", then everything would be fine

MySQL integer field is returned as string in PHP

I like mastermind's technique, but the coding can be simpler:

function cast_query_results($result): array
{
    if ($result === false)
      return null;

    $data = array();
    $fields = $result->fetch_fields();
    while ($row = $result->fetch_assoc()) {
      foreach ($fields as $field) {
        $fieldName = $field->name;
        $fieldValue = $row[$fieldName];
        if (!is_null($fieldValue))
            switch ($field->type) {
              case 3:
                $row[$fieldName] = (int)$fieldValue;
                break;
              case 4:
                $row[$fieldName] = (float)$fieldValue;
                break;
              // Add other type conversions as desired.
              // Strings are already strings, so don't need to be touched.
            }
      }
      array_push($data, $row);
    }

    return $data;
}

I also added checking for query returning false rather than a result-set.
And checking for a row with a field that has a null value.
And if the desired type is a string, I don't waste any time on it - its already a string.


I don't bother using this in most php code; I just rely on php's automatic type conversion. But if querying a lot of data, to then perform arithmetic computations, it is sensible to cast to the optimal types up front.

android listview item height

The trick for me was not setting the height -- but instead setting the minHeight. This must be applied to the root view of whatever layout your custom adapter is using to render each row.

Bash syntax error: unexpected end of file

Missing a closing brace on a function definition will cause this error as I just discovered.

function whoIsAnIidiot() {
    echo "you are for forgetting the closing brace just below this line !"

Which of course should be like this...

function whoIsAnIidiot() {
    echo "not you for sure"
}

Update a submodule to the latest commit

If you update a submodule and commit to it, you need to go to the containing, or higher level repo and add the change there.

git status

will show something like:

modified:
   some/path/to/your/submodule

The fact that the submodule is out of sync can also be seen with

git submodule

the output will show:

+afafaffa232452362634243523 some/path/to/your/submodule

The plus indicates that the your submodule is pointing ahead of where the top repo expects it to point to.

simply add this change:

git add some/path/to/your/submodule

and commit it:

git commit -m "referenced newer version of my submodule"

When you push up your changes, make sure you push up the change in the submodule first and then push the reference change in the outer repo. This way people that update will always be able to successfully run

git submodule update

More info on submodules can be found here http://progit.org/book/ch6-6.html.

python location on mac osx

installed with 'brew install python3', found it here enter image description here

How to add dll in c# project

Have you added the dll into your project references list? If not right click on the project "References" folder and selecet "Add Reference" then use browse to locate your science.dll, select it and click ok.

edit

I can't see the image of your VS instance that some people are referring to and I note that you now say that it works in Net4.0 and VS2010.

VS2008 projects support NET 3.5 by default. I expect that is the problem as your DLL may be NET 4.0 compliant but not NET 3.5.

CHECK constraint in MySQL is not working

MySQL 8.0.16 is the first version that supports CHECK constraints.

Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html

If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:

The CHECK clause is parsed but ignored by all storage engines.

Try a trigger...

mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer 
    -> FOR EACH ROW 
    -> BEGIN 
    -> IF NEW.SD<0 THEN 
    -> SET NEW.SD=0; 
    -> END IF; 
    -> END
    -> //
mysql> delimiter ;

Hope that helps.

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

When is JavaScript synchronous?

JavaScript is single threaded and has a synchronous execution model. Single threaded means that one command is being executed at a time. Synchronous means one at a time i.e. one line of code is being executed at time in order the code appears. So in JavaScript one thing is happening at a time.

Execution Context

The JavaScript engine interacts with other engines in the browser. In the JavaScript execution stack there is global context at the bottom and then when we invoke functions the JavaScript engine creates new execution contexts for respective functions. When the called function exits its execution context is popped from the stack, and then next execution context is popped and so on...

For example

function abc()
{
   console.log('abc');
}


function xyz()
{
   abc()
   console.log('xyz');
}
var one = 1;
xyz();

In the above code a global execution context will be created and in this context var one will be stored and its value will be 1... when the xyz() invocation is called then a new execution context will be created and if we had defined any variable in xyz function those variables would be stored in the execution context of xyz(). In the xyz function we invoke abc() and then the abc() execution context is created and put on the execution stack... Now when abc() finishes its context is popped from stack, then the xyz() context is popped from stack and then global context will be popped...

Now about asynchronous callbacks; asynchronous means more than one at a time.

Just like the execution stack there is the Event Queue. When we want to be notified about some event in the JavaScript engine we can listen to that event, and that event is placed on the queue. For example an Ajax request event, or HTTP request event.

Whenever the execution stack is empty, like shown in above code example, the JavaScript engine periodically looks at the event queue and sees if there is any event to be notified about. For example in the queue there were two events, an ajax request and a HTTP request. It also looks to see if there is a function which needs to be run on that event trigger... So the JavaScript engine is notified about the event and knows the respective function to execute on that event... So the JavaScript engine invokes the handler function, in the example case, e.g. AjaxHandler() will be invoked and like always when a function is invoked its execution context is placed on the execution context and now the function execution finishes and the event ajax request is also removed from the event queue... When AjaxHandler() finishes the execution stack is empty so the engine again looks at the event queue and runs the event handler function of HTTP request which was next in queue. It is important to remember that the event queue is processed only when execution stack is empty.

For example see the code below explaining the execution stack and event queue handling by Javascript engine.

function waitfunction() {
    var a = 5000 + new Date().getTime();
    while (new Date() < a){}
    console.log('waitfunction() context will be popped after this line');
}

function clickHandler() {
    console.log('click event handler...');   
}

document.addEventListener('click', clickHandler);


waitfunction(); //a new context for this function is created and placed on the execution stack
console.log('global context will be popped after this line');

And

<html>
    <head>

    </head>
    <body>

        <script src="program.js"></script>
    </body>
</html>

Now run the webpage and click on the page, and see the output on console. The output will be

waitfunction() context will be popped after this line
global context will be emptied after this line
click event handler...

The JavaScript engine is running the code synchronously as explained in the execution context portion, the browser is asynchronously putting things in event queue. So the functions which take a very long time to complete can interrupt event handling. Things happening in a browser like events are handled this way by JavaScript, if there is a listener supposed to run, the engine will run it when the execution stack is empty. And events are processed in the order they happen, so the asynchronous part is about what is happening outside the engine i.e. what should the engine do when those outside events happen.

So JavaScript is always synchronous.

Foreach value from POST from form

If your post keys have to be parsed and the keys are sequences with data, you can try this:

Post data example: Storeitem|14=data14

foreach($_POST as $key => $value){
    $key=Filterdata($key); $value=Filterdata($value);
    echo($key."=".$value."<br>");
}

then you can use strpos to isolate the end of the key separating the number from the key.

How do I use Assert to verify that an exception has been thrown?

I do not recommend using the ExpectedException attribute (since it's too constraining and error-prone) or to write a try/catch block in each test (since it's too complicated and error-prone). Use a well-designed assert method -- either provided by your test framework or write your own. Here's what I wrote and use.

public static class ExceptionAssert
{
    private static T GetException<T>(Action action, string message="") where T : Exception
    {
        try
        {
            action();
        }
        catch (T exception)
        {
            return exception;
        }
        throw new AssertFailedException("Expected exception " + typeof(T).FullName + ", but none was propagated.  " + message);
    }

    public static void Propagates<T>(Action action) where T : Exception
    {
        Propagates<T>(action, "");
    }

    public static void Propagates<T>(Action action, string message) where T : Exception
    {
        GetException<T>(action, message);
    }

    public static void Propagates<T>(Action action, Action<T> validation) where T : Exception
    {
        Propagates(action, validation, "");
    }

    public static void Propagates<T>(Action action, Action<T> validation, string message) where T : Exception
    {
        validation(GetException<T>(action, message));
    }
}

Example uses:

    [TestMethod]
    public void Run_PropagatesWin32Exception_ForInvalidExeFile()
    {
        (test setup that might propagate Win32Exception)
        ExceptionAssert.Propagates<Win32Exception>(
            () => CommandExecutionUtil.Run(Assembly.GetExecutingAssembly().Location, new string[0]));
        (more asserts or something)
    }

    [TestMethod]
    public void Run_PropagatesFileNotFoundException_ForExecutableNotFound()
    {
        (test setup that might propagate FileNotFoundException)
        ExceptionAssert.Propagates<FileNotFoundException>(
            () => CommandExecutionUtil.Run("NotThere.exe", new string[0]),
            e => StringAssert.Contains(e.Message, "NotThere.exe"));
        (more asserts or something)
    }

NOTES

Returning the exception instead of supporting a validation callback is a reasonable idea except that doing so makes the calling syntax of this assert very different than other asserts I use.

Unlike others, I use 'propagates' instead of 'throws' since we can only test whether an exception propagates from a call. We can't test directly that an exception is thrown. But I suppose you could image throws to mean: thrown and not caught.

FINAL THOUGHT

Before switching to this sort of approach I considered using the ExpectedException attribute when a test only verified the exception type and using a try/catch block if more validation was required. But, not only would I have to think about which technique to use for each test, but changing the code from one technique to the other as needs changed was not trivial effort. Using one consistent approach saves mental effort.

So in summary, this approach sports: ease-of-use, flexibility and robustness (hard to do it wrong).

XSD - how to allow elements in any order any number of times?

You should find that the following schema allows the what you have proposed.

  <xs:element name="foo">
    <xs:complexType>
      <xs:sequence minOccurs="0" maxOccurs="unbounded">
        <xs:choice>
          <xs:element maxOccurs="unbounded" name="child1" type="xs:unsignedByte" />
          <xs:element maxOccurs="unbounded" name="child2" type="xs:string" />
        </xs:choice>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

This will allow you to create a file such as:

<?xml version="1.0" encoding="utf-8" ?>
<foo>
  <child1>2</child1>
  <child1>3</child1>
  <child2>test</child2>
  <child2>another-test</child2>
</foo>

Which seems to match your question.

Get Mouse Position

In my scenario, I was supposed to open a dialog box in the mouse position based on a GUI operation done with the mouse. The following code worked for me:

    public Object open() {
    //create the contents of the dialog
    createContents();
    //setting the shell location based on the curent position
    //of the mouse
    PointerInfo a = MouseInfo.getPointerInfo();
    Point pt = a.getLocation();
    shellEO.setLocation (pt.x, pt.y);

    //once the contents are created and location is set-
    //open the dialog
    shellEO.open();
    shellEO.layout();
    Display display = getParent().getDisplay();
    while (!shellEO.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    return result;
}

Unsigned keyword in C++

Yes, it means unsigned int. It used to be that if you didn't specify a data type in C there were many places where it just assumed int. This was try, for example, of function return types.

This wart has mostly been eradicated, but you are encountering its last vestiges here. IMHO, the code should be fixed to say unsigned int to avoid just the sort of confusion you are experiencing.

PHPmailer sending HTML CODE

Calling the isHTML() method after the instance Body property (I mean $mail->Body) has been set solved the problem for me:

$mail->Subject = $Subject;
$mail->Body    = $Body;
$mail->IsHTML(true);       // <=== call IsHTML() after $mail->Body has been set.

long long in C/C++

your code compiles here fine (even with that line uncommented. had to change it to

num3 = 100000000000000000000;

to start getting the warning.

Login failed for user 'DOMAIN\MACHINENAME$'

A colleague had the same error and it was due to a little configuration error in IIS.
The wrong Application Pool was assigned for the web application.

Indeed we use a custom Application Pool with a specific Identity to meet our needs.

In his local IIS Manager -> Sites -> Default Web Site -> Our Web App Name -> Basic Settings... The Application Pool was "DefaultAppPool" instead of our custom Application Pool.

Setting the correct application pool solved the problem.

How to store a list in a column of a database table

Simple answer: If, and only if, you're certain that the list will always be used as a list, then join the list together on your end with a character (such as '\0') that will not be used in the text ever, and store that. Then when you retrieve it, you can split by '\0'. There are of course other ways of going about this stuff, but those are dependent on your specific database vendor.

As an example, you can store JSON in a Postgres database. If your list is text, and you just want the list without further hassle, that's a reasonable compromise.

Others have ventured suggestions of serializing, but I don't really think that serializing is a good idea: Part of the neat thing about databases is that several programs written in different languages can talk to one another. And programs serialized using Java's format would not do all that well if a Lisp program wanted to load it.

If you want a good way to do this sort of thing there are usually array-or-similar types available. Postgres for instance, offers array as a type, and lets you store an array of text, if that's what you want, and there are similar tricks for MySql and MS SQL using JSON, and IBM's DB2 offer an array type as well (in their own helpful documentation). This would not be so common if there wasn't a need for this.

What you do lose by going that road is the notion of the list as a bunch of things in sequence. At least nominally, databases treat fields as single values. But if that's all you want, then you should go for it. It's a value judgement you have to make for yourself.

Override back button to act like home button

Use the following code:

public void onBackPressed() {    
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}

Remove Elements from a HashSet while Iterating

The reason you get a ConcurrentModificationException is because an entry is removed via Set.remove() as opposed to Iterator.remove(). If an entry is removed via Set.remove() while an iteration is being done, you will get a ConcurrentModificationException. On the other hand, removal of entries via Iterator.remove() while iteration is supported in this case.

The new for loop is nice, but unfortunately it does not work in this case, because you can't use the Iterator reference.

If you need to remove an entry while iteration, you need to use the long form that uses the Iterator directly.

for (Iterator<Integer> it = set.iterator(); it.hasNext();) {
    Integer element = it.next();
    if (element % 2 == 0) {
        it.remove();
    }
}

Java string replace and the NUL (NULL, ASCII 0) character?

I think it should be the case. To erase the character, you should use replace(".", "") instead.

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

Combining Two Images with OpenCV

import numpy as np, cv2

img1 = cv2.imread(fn1, 0)
img2 = cv2.imread(fn2, 0)
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
vis = np.zeros((max(h1, h2), w1+w2), np.uint8)
vis[:h1, :w1] = img1
vis[:h2, w1:w1+w2] = img2
vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)

cv2.imshow("test", vis)
cv2.waitKey()

or if you prefer legacy way:

import numpy as np, cv

img1 = cv.LoadImage(fn1, 0)
img2 = cv.LoadImage(fn2, 0)

h1, w1 = img1.height,img1.width
h2, w2 = img2.height,img2.width
vis = np.zeros((max(h1, h2), w1+w2), np.uint8)
vis[:h1, :w1] = cv.GetMat(img1)
vis[:h2, w1:w1+w2] = cv.GetMat(img2)
vis2 = cv.CreateMat(vis.shape[0], vis.shape[1], cv.CV_8UC3)
cv.CvtColor(cv.fromarray(vis), vis2, cv.CV_GRAY2BGR)

cv.ShowImage("test", vis2)
cv.WaitKey()

How to check if activity is in foreground or in visible background?

If targeting API level 14 or above, one can use android.app.Application.ActivityLifecycleCallbacks

public class MyApplication extends Application implements ActivityLifecycleCallbacks {
    private static boolean isInterestingActivityVisible;

    @Override
    public void onCreate() {
        super.onCreate();

        // Register to be notified of activity state changes
        registerActivityLifecycleCallbacks(this);
        ....
    }

    public boolean isInterestingActivityVisible() {
        return isInterestingActivityVisible;
    }

    @Override
    public void onActivityResumed(Activity activity) {
        if (activity instanceof MyInterestingActivity) {
             isInterestingActivityVisible = true;
        }
    }

    @Override
    public void onActivityStopped(Activity activity) {
        if (activity instanceof MyInterestingActivity) {
             isInterestingActivityVisible = false;
        }
    }

    // Other state change callback stubs
    ....
}

How to set the title text color of UIButton?

func setTitleColor(_ color: UIColor?, 
               for state: UIControl.State)

Parameters:

color:
The color of the title to use for the specified state.

state:
The state that uses the specified color. The possible values are described in UIControl.State.

Sample:

let MyButton = UIButton()
MyButton.setTitle("Click Me..!", for: .normal)
MyButton.setTitleColor(.green, for: .normal)

Jquery submit form

Try this lets say your form id is formID

$(".nextbutton").click(function() { $("form#formID").submit(); });

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

How to deploy a war file in JBoss AS 7?

Actually, for the latest JBOSS 7 AS, we need a .dodeploy marker even for archives. So add a marker to trigger the deployment.

In my case, I added a Hello.war.deployed file in the same directory and then everything worked fine.

Hope this helps someone!

Get and Set Screen Resolution

For retrieving the screen resolution, you're going to want to use the System.Windows.Forms.Screen class. The Screen.AllScreens property can be used to access a collection of all of the displays on the system, or you can use the Screen.PrimaryScreen property to access the primary display.

The Screen class has a property called Bounds, which you can use to determine the resolution of the current instance of the class. For example, to determine the resolution of the current screen:

Rectangle resolution = Screen.PrimaryScreen.Bounds;

For changing the resolution, things get a little more complicated. This article (or this one) provides a detailed implementation and explanation. Hope this helps.

How to install PostgreSQL's pg gem on Ubuntu?

After reading and thrashing around for 2 days, and trying many things found in other notes the following single line was the cure for me on Ubuntu Lucid 10.04 mixed with some Maverick packages and RVM (ruby 1.9.2-p290, rvm 1.10.2 rubygems 1.8.15, rails 3.0.1, postgres 8.4.10) :

gem install pg  --   --with-pg-lib=/usr/lib   

the result:

Building native extensions.  This could take a while...  
Successfully installed pg-0.13.1  
1 gem installed  
Installing ri documentation for pg-0.13.1...  
Installing RDoc documentation for pg-0.13.1...  

{yea - finally success} !! !note that the output from running pg_config lacks the item -lpq in the LIBS variable on my Ubuntu / Postresql install!!

and why the switch from pq to pg in certain places -- confusing to newbie ??

the thing I still do not understand is the double set of -- and --with(option but I'm way beyond my depth anyway

Checkbox angular material checked by default

The chosen answer does work however I wanted to make a comment that having 'ngModel' on the html tag causes the checkbox checked to not be set to true.

This occurs when you are trying to do bind using the checked property. i.e.

<mat-checkbox [checked]='var' ngModel name='some_name'></mat-checkbox>

And then inside your app.component.ts file

var = true;

will not work.

TLDR: Remove ngModel if you are setting the checked through the [checked] property

    <mat-checkbox [checked]='var' name='some_name'></mat-checkbox>

How to increase application heap size in Eclipse?

  1. Go to Eclipse Folder
  2. Find Eclipse Icon in Eclipse Folder
  3. Right Click on it you will get option "Show Package Content"
  4. Contents folder will open on screen
  5. If you are on Mac then you'll find "MacOS"
  6. Open MacOS folder you'll find eclipse.ini file
  7. Open it in word or any file editor for edit

    ...

    -XX:MaxPermSize=256m
    
    -Xms40m
    
    -Xmx512m
    

    ...

  8. Replace -Xmx512m to -Xmx1024m

  9. Save the file and restart your Eclipse
  10. Have a Nice time :)

Adding minutes to date time in PHP

I thought this would help some when dealing with time zones too. My modified solution is based off of @Tim Cooper's solution, the correct answer above.

$minutes_to_add = 10;
$time = new DateTime();
**$time->setTimezone(new DateTimeZone('America/Toronto'));**
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$timestamp = $time->format("Y/m/d G:i:s");

The bold line, line 3, is the addition. I hope this helps some folks as well.

How do I create a right click context menu in Java Swing?

There's a section on Bringing Up a Popup Menu in the How to Use Menus article of The Java Tutorials which explains how to use the JPopupMenu class.

The example code in the tutorial shows how to add MouseListeners to the components which should display a pop-up menu, and displays the menu accordingly.

(The method you describe is fairly similar to the way the tutorial presents the way to show a pop-up menu on a component.)

Create an empty data.frame

I created empty data frame using following code

df = data.frame(id = numeric(0), jobs = numeric(0));

and tried to bind some rows to populate the same as follows.

newrow = c(3, 4)
df <- rbind(df, newrow)

but it started giving incorrect column names as follows

  X3 X4
1  3  4

Solution to this is to convert newrow to type df as follows

newrow = data.frame(id=3, jobs=4)
df <- rbind(df, newrow)

now gives correct data frame when displayed with column names as follows

  id nobs
1  3   4 

Django Reverse with arguments '()' and keyword arguments '{}' not found

This problems gave me great headache when i tried to use reverse for generating activation link and send it via email of course. So i think from tests.py it will be same. The correct way to do this is following:

from django.test import Client
from django.core.urlresolvers import reverse

#app name - name of the app where the url is defined
client= Client()
response = client.get(reverse('app_name:edit_project', project_id=4)) 

How to set environment variables in PyCharm?

This is what you can do to source an .env (and .flaskenv) file in the pycharm flask/django console. It would also work for a normal python console of course.

  1. Do pip install python-dotenv in your environment (the same as being pointed to by pycharm).

  2. Go to: Settings > Build ,Execution, Deployment > Console > Flask/django Console

  3. In "starting script" include something like this near the top:

    from dotenv import load_dotenv load_dotenv(verbose=True)

The .env file can look like this: export KEY=VALUE

It doesn't matter if one includes export or not for dotenv to read it.

As an alternative you could also source the .env file in the activate shell script for the respective virtual environement.

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

In angular $http service, How can I catch the "status" of error?

Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.

Taken from the angular docs:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

So you'd need to change your code to:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status); 
  }); 

Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.

When to use extern in C++

It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.

For example:

in file1.cpp:

int global_int = 1;

in file2.cpp:

extern int global_int;
//in some function
cout << "global_int = " << global_int;

How to dynamically create a class?

Wow! Thank you for that answer! I added some features to it to create a "datatable to json" converter that I share with you.

    Public Shared Sub dt2json(ByVal _dt As DataTable, ByVal _sb As StringBuilder)
    Dim t As System.Type

    Dim oList(_dt.Rows.Count - 1) As Object
    Dim jss As New JavaScriptSerializer()
    Dim i As Integer = 0

    t = CompileResultType(_dt)

    For Each dr As DataRow In _dt.Rows
        Dim o As Object = Activator.CreateInstance(t)

        For Each col As DataColumn In _dt.Columns
            setvalue(o, col.ColumnName, dr.Item(col.ColumnName))
        Next

        oList(i) = o
        i += 1
    Next

    jss = New JavaScriptSerializer()
    jss.Serialize(oList, _sb)


End Sub

And in "compileresulttype" sub, I changed that:

    For Each column As DataColumn In _dt.Columns
        CreateProperty(tb, column.ColumnName, column.DataType)
    Next


Private Shared Sub setvalue(ByVal _obj As Object, ByVal _propName As String, ByVal _propValue As Object)
    Dim pi As PropertyInfo
    pi = _obj.GetType.GetProperty(_propName)
    If pi IsNot Nothing AndAlso pi.CanWrite Then
        If _propValue IsNot DBNull.Value Then
            pi.SetValue(_obj, _propValue, Nothing)

        Else
            Select Case pi.PropertyType.ToString
                Case "System.String"
                    pi.SetValue(_obj, String.Empty, Nothing)
                Case Else
                    'let the serialiser use javascript "null" value.
            End Select

        End If
    End If

End Sub

Execute PHP script in cron job

I had the same problem... I had to run it as a user.

00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php

mysql query result in php variable

$query="SELECT * FROM contacts";
$result=mysql_query($query);

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

It may have been because I am still new to VS and definitely new to C, but the only thing that allowed me to build was adding

#pragma warning(disable:4996)

At the top of my file, this suppressed the C4996 error I was getting with sprintf

A bit annoying but perfect for my tiny bit of code and by far the easiest.

I read about it here: https://msdn.microsoft.com/en-us/library/2c8f766e.aspx

Converting Dictionary to List?

Your problem is that you have key and value in quotes making them strings, i.e. you're setting aKey to contain the string "key" and not the value of the variable key. Also, you're not clearing out the temp list, so you're adding to it each time, instead of just having two items in it.

To fix your code, try something like:

for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

You don't need to copy the loop variables key and value into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value]) if we wanted to be as brief as possible.

Or just use dict.items() as has been suggested.

How to do the Recursive SELECT query in MySQL?

Edit

Solution mentioned by @leftclickben is also effective. We can also use a stored procedure for the same.

CREATE PROCEDURE get_tree(IN id int)
 BEGIN
 DECLARE child_id int;
 DECLARE prev_id int;
 SET prev_id = id;
 SET child_id=0;
 SELECT col3 into child_id 
 FROM table1 WHERE col1=id ;
 create TEMPORARY  table IF NOT EXISTS temp_table as (select * from table1 where 1=0);
 truncate table temp_table;
 WHILE child_id <> 0 DO
   insert into temp_table select * from table1 WHERE col1=prev_id;
   SET prev_id = child_id;
   SET child_id=0;
   SELECT col3 into child_id
   FROM TABLE1 WHERE col1=prev_id;
 END WHILE;
 select * from temp_table;
 END //

We are using temp table to store results of the output and as the temp tables are session based we wont there will be not be any issue regarding output data being incorrect.

SQL FIDDLE Demo

Try this query:

SELECT 
    col1, col2, @pv := col3 as 'col3' 
FROM 
    table1
JOIN 
    (SELECT @pv := 1) tmp
WHERE 
    col1 = @pv

SQL FIDDLE Demo:

| COL1 | COL2 | COL3 |
+------+------+------+
|    1 |    a |    5 |
|    5 |    d |    3 |
|    3 |    k |    7 |

Note
parent_id value should be less than the child_id for this solution to work.

How to write a large buffer into a binary file in C++, fast?

The best solution is to implement an async writing with double buffering.

Look at the time line:

------------------------------------------------>
FF|WWWWWWWW|FF|WWWWWWWW|FF|WWWWWWWW|FF|WWWWWWWW|

The 'F' represents time for buffer filling, and 'W' represents time for writing buffer to disk. So the problem in wasting time between writing buffers to file. However, by implementing writing on a separate thread, you can start filling the next buffer right away like this:

------------------------------------------------> (main thread, fills buffers)
FF|ff______|FF______|ff______|________|
------------------------------------------------> (writer thread)
  |WWWWWWWW|wwwwwwww|WWWWWWWW|wwwwwwww|

F - filling 1st buffer
f - filling 2nd buffer
W - writing 1st buffer to file
w - writing 2nd buffer to file
_ - wait while operation is completed

This approach with buffer swaps is very useful when filling a buffer requires more complex computation (hence, more time). I always implement a CSequentialStreamWriter class that hides asynchronous writing inside, so for the end-user the interface has just Write function(s).

And the buffer size must be a multiple of disk cluster size. Otherwise, you'll end up with poor performance by writing a single buffer to 2 adjacent disk clusters.

Writing the last buffer.
When you call Write function for the last time, you have to make sure that the current buffer is being filled should be written to disk as well. Thus CSequentialStreamWriter should have a separate method, let's say Finalize (final buffer flush), which should write to disk the last portion of data.

Error handling.
While the code start filling 2nd buffer, and the 1st one is being written on a separate thread, but write fails for some reason, the main thread should be aware of that failure.

------------------------------------------------> (main thread, fills buffers)
FF|fX|
------------------------------------------------> (writer thread)
__|X|

Let's assume the interface of a CSequentialStreamWriter has Write function returns bool or throws an exception, thus having an error on a separate thread, you have to remember that state, so next time you call Write or Finilize on the main thread, the method will return False or will throw an exception. And it does not really matter at which point you stopped filling a buffer, even if you wrote some data ahead after the failure - most likely the file would be corrupted and useless.

Replace HTML page with contents retrieved via AJAX

The simplest way is to set the new HTML content using:

document.open();
document.write(newContent);
document.close();

Count the occurrences of DISTINCT values

SELECT name,COUNT(*) as count 
FROM tablename 
GROUP BY name 
ORDER BY count DESC;

I can not find my.cnf on my windows computer

Here is my answer:

  1. Win+R (shortcut for 'run'), type services.msc, Enter
  2. You should find an entry like 'MySQL56', right click on it, select properties
  3. You should see something like "D:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="D:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56

Full answer here: https://stackoverflow.com/a/20136523/1316649

Why does the Google Play store say my Android app is incompatible with my own device?

I have a couple of suggestions:

  1. First of all, you seem to be using API 4 as your target. AFAIK, it's good practice to always compile against the latest SDK and setup your android:minSdkVersion accordingly.

  2. With that in mind, remember that android:required attribute was added in API 5:

The feature declaration can include an android:required=["true" | "false"] attribute (if you are compiling against API level 5 or higher), which lets you specify whether the application (...)

Thus, I'd suggest that you compile against SDK 15, set targetSdkVersion to 15 as well, and provide that functionality.

It also shows here, on the Play site, as incompatible with any device that I have that is (coincidence?) Gingerbread (Galaxy Ace and Galaxy Y here). But it shows as compatible with my Galaxy Tab 10.1 (Honeycomb), Nexus S and Galaxy Nexus (both on ICS).

That also left me wondering, and this is a very wild guess, but since android.hardware.faketouch is API11+, why don't you try removing it just to see if it works? Or perhaps that's all related anyway, since you're trying to use features (faketouch) and the required attribute that are not available in API 4. And in this case you should compile against the latest API.

I would try that first, and remove the faketouch requirement only as last resort (of course) --- since it works when developing, I'd say it's just a matter of the compiled app not recognizing the feature (due to the SDK requirements), thus leaving unexpected filtering issues on Play.

Sorry if this guess doesn't answer your question, but it's very difficult to diagnose those kind of problems and pinpoint the solution without actually testing. Or at least for me without all the proper knowledge of how Play really filters apps.

Good luck.

Convert a negative number to a positive one in JavaScript

var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ... 

I find this solution easy to understand.

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

What worked for me was just typing the command passive and ftp went into passive mode from active mode.

How should strace be used?

Minimal runnable example

If a concept is not clear, there is a simpler example that you haven't seen that explains it.

In this case, that example is the Linux x86_64 assembly freestanding (no libc) hello world:

hello.S

.text
.global _start
_start:
    /* write */
    mov $1, %rax    /* syscall number */
    mov $1, %rdi    /* stdout */
    mov $msg, %rsi  /* buffer */
    mov $len, %rdx  /* buffer len */
    syscall

    /* exit */
    mov $60, %rax   /* exit status */
    mov $0, %rdi    /* syscall number */
    syscall
msg:
    .ascii "hello\n"
len = . - msg

GitHub upstream.

Assemble and run:

as -o hello.o hello.S
ld -o hello.out hello.o
./hello.out

Outputs the expected:

hello

Now let's use strace on that example:

env -i ASDF=qwer strace -o strace.log -s999 -v ./hello.out arg0 arg1
cat strace.log

We use:

strace.log now contains:

execve("./hello.out", ["./hello.out", "arg0", "arg1"], ["ASDF=qwer"]) = 0
write(1, "hello\n", 6)                  = 6
exit(0)                                 = ?
+++ exited with 0 +++

With such a minimal example, every single character of the output is self evident:

  • execve line: shows how strace executed hello.out, including CLI arguments and environment as documented at man execve

  • write line: shows the write system call that we made. 6 is the length of the string "hello\n".

    = 6 is the return value of the system call, which as documented in man 2 write is the number of bytes written.

  • exit line: shows the exit system call that we've made. There is no return value, since the program quit!

More complex examples

The application of strace is of course to see which system calls complex programs are actually doing to help debug / optimize your program.

Notably, most system calls that you are likely to encounter in Linux have glibc wrappers, many of them from POSIX.

Internally, the glibc wrappers use inline assembly more or less like this: How to invoke a system call via sysenter in inline assembly?

The next example you should study is a POSIX write hello world:

main.c

#define _XOPEN_SOURCE 700
#include <unistd.h>

int main(void) {
    char *msg = "hello\n";
    write(1, msg, 6);
    return 0;
}

Compile and run:

gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out

This time, you will see that a bunch of system calls are being made by glibc before main to setup a nice environment for main.

This is because we are now not using a freestanding program, but rather a more common glibc program, which allows for libc functionality.

Then, at the every end, strace.log contains:

write(1, "hello\n", 6)                  = 6
exit_group(0)                           = ?
+++ exited with 0 +++

So we conclude that the write POSIX function uses, surprise!, the Linux write system call.

We also observe that return 0 leads to an exit_group call instead of exit. Ha, I didn't know about this one! This is why strace is so cool. man exit_group then explains:

This system call is equivalent to exit(2) except that it terminates not only the calling thread, but all threads in the calling process's thread group.

And here is another example where I studied which system call dlopen uses: https://unix.stackexchange.com/questions/226524/what-system-call-is-used-to-load-libraries-in-linux/462710#462710

Tested in Ubuntu 16.04, GCC 6.4.0, Linux kernel 4.4.0.

How to copy files between two nodes using ansible

A simple way to used copy module to transfer the file from one server to another

Here is playbook

---
- hosts: machine1 {from here file will be transferred to another remote machine}
  tasks:
  - name: transfer data from machine1 to machine2

    copy:
     src=/path/of/machine1

     dest=/path/of/machine2

    delegate_to: machine2 {file/data receiver machine}

TypeError: 'float' object is not subscriptable

PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))      
for i,price in enumerate(PriceList):
  PriceList[i] = PizzaChange + 3*int(i>=7)

A button to start php script, how?

I know this question is 5 years old, but for anybody wondering how to do this without re-rendering the main page. This solution uses the dart editor/scripting language.

You could have an <object> tag that contains a data attribute. Make the <object> 1px by 1px and then use something like dart to dynamically change the <object>'s data attribute which re-renders the data in the 1px by 1px object.

HTML Script:

<object id="external_source" type="text/html" data="" width="1px" height="1px">
</object>

<button id="button1" type="button">Start Script</button>

<script async type="application/dart" src="dartScript.dart"></script>
<script async src="packages/browser/dart.js"></script>

someScript.php:

<?php
echo 'hello world';
?>

dartScript.dart:

import 'dart:html';

InputElement button1;
ObjectElement externalSource;

void main() {
    button1 = querySelector('#button1')
        ..onClick.listen(runExternalSource);

    externalSource = querySelector('#external_source');
}

void runExternalSource(Event e) {
    externalSource.setAttribute('data', 'someScript.php');
}

So long as you aren't posting any information and you are just looking to run a script, this should work just fine.

Just build the dart script using "pub Build(generate JS)" and then upload the package onto your server.

How to set time delay in javascript

For sync calls you can use the method below:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

Load HTML page dynamically into div with jQuery

There's a jQuery plugin out there called pjax it states: "It's ajax with real permalinks, page titles, and a working back button that fully degrades."

The plugin uses HTML5 pushState and AJAX to dynamically change pages without a full load. If pushState isn't supported, PJAX performs a full page load, ensuring backwards compatibility.

What pjax does is that it listens on specified page elements such as <a>. Then when the <a href=""></a> element is invoked, the target page is fetched with either the X-PJAX header, or a specified fragment.

Example:

<script type="text/javascript">
  $(document).pjax('a', '#pjax-container');
</script>

Putting this code in the page header will listen on all links in the document and set the element that you are both fetching from the new page and replacing on the current page.

(meaning you want to replace #pjax-container on the current page with #pjax-container from the remote page)

When <a> is invoked, it will fetch the link with the request header X-PJAX and will look for the contents of #pjax-container in the result. If the result is #pjax-container, the container on the current page will be replaced with the new result.

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="jquery.min.js"></script>
  <script type="text/javascript" src="jquery.pjax.js"></script> 
  <script type="text/javascript">
    $(document).pjax('a', '#pjax-container');
  </script> 
</head>
<body>
  <h1>My Site</h1>
  <div class="container" id="pjax-container">
    Go to <a href="/page2">next page</a>.
  </div>
</body>
</html>

If #pjax-container is not the first element found in the response, PJAX will not recognize the content and perform a full page load on the requested link. To fix this, the server backend code would need to be set to only send #pjax-container.

Example server side code of page2:

//if header X-PJAX == true in request headers, send
<div class="container" id="pjax-container">
  Go to <a href="/page1">next page</a>.
</div>
//else send full page

If you can't change server-side code, then the fragment option is an alternative.

$(document).pjax('a', '#pjax-container', { 
  fragment: '#pjax-container' 
});

Note that fragment is an older pjax option and appears to fetch the child element of requested element.

JPA OneToMany not deleting child

In addition to cletus' answer, JPA 2.0, final since december 2010, introduces an orphanRemoval attribute on @OneToMany annotations. For more details see this blog entry.

Note that since the spec is relatively new, not all JPA 1 provider have a final JPA 2 implementation. For example, the Hibernate 3.5.0-Beta-2 release does not yet support this attribute.

Why won't bundler install JSON gem?

I installed the latest version of json:

gem install json

Then deleted the line json(1.8.1) from the Gemfile.lock and did a

bundle install

And then the Gemfile.lock file uses json(1.8.3) without erros

Windows service on Local Computer started and then stopped error

In our case, nothing was added in the Windows Event Logs except logs that the problematic service has been started and then stopped.

It turns out that the service's CONFIG file was invalid. Correcting the invalid CONFIG file fixed the issue.

No submodule mapping found in .gitmodule for a path that's not a submodule

in the file .gitmodules, I replaced string

"path = thirdsrc\boost" 

with

"path = thirdsrc/boost", 

and it solved! - -

Android - How to download a file from a webserver

Run these codes in thread or AsyncTask. In order to avoid duplicated callings of same _url(one time for getContentLength(), one time of openStream()), use IOUtils.toByteArray of Apache.

void downloadFile(String _url, String _name) {
    try {
        URL u = new URL(_url);
        DataInputStream stream = new DataInputStream(u.openStream());
        byte[] buffer = IOUtils.toByteArray(stream);
        FileOutputStream fos = mContext.openFileOutput(_name, Context.MODE_PRIVATE);
        fos.write(buffer);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

Service vs IntentService in the Android platform

Tejas Lagvankar wrote a nice post about this subject. Below are some key differences between Service and IntentService.

When to use?

  • The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.

  • The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).

How to trigger?

  • The Service is triggered by calling method startService().

  • The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.

Triggered From

  • The Service and IntentService may be triggered from any thread, activity or other application component.

Runs On

  • The Service runs in background but it runs on the Main Thread of the application.

  • The IntentService runs on a separate worker thread.

Limitations / Drawbacks

  • The Service may block the Main Thread of the application.

  • The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.

When to stop?

  • If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method).

  • The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf().

Return JSON with error status code MVC

The neatest solution I've found is to create your own JsonResult that extends the original implementation and allows you to specify a HttpStatusCode:

public class JsonHttpStatusResult : JsonResult
{
    private readonly HttpStatusCode _httpStatus;

    public JsonHttpStatusResult(object data, HttpStatusCode httpStatus)
    {
        Data = data;
        _httpStatus = httpStatus;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.RequestContext.HttpContext.Response.StatusCode = (int)_httpStatus;
        base.ExecuteResult(context);
    }
}

You can then use this in your controller action like so:

if(thereWereErrors)
{
    var errorModel = new { error = "There was an error" };
    return new JsonHttpStatusResult(errorModel, HttpStatusCode.InternalServerError);
}

JQuery DatePicker ReadOnly

by making date picker input disabled achieve this but if you want to submit form data then its a problem.

so after lot of juggling this seems to me a perfect solution

1.make your HTML input readonly on some condition.

<input class="form-control date-picker" size="16" data-date-format="dd/mm/yyyy"
                       th:autocomplete="off"
                       th:name="birthDate" th:id="birthDate"
                       type="text" placeholder="dd/mm/jjjj"
                       th:value="*{#dates.format(birthDate,'dd/MM/yyyy')}"
                       th:readonly="${client?.isDisableForAoicStatus()}"/>

2. in your js in ready function check for readonly attribute.

 $(document).ready(function (e) {

            if( $(".date-picker").attr('readonly') == 'readonly') {
                $("#birthDate").removeClass('date-picker');
            }
     });

this will stop the calendar pop up invoking when you click on the readonly field.also this will not make any problem in submit data. But if you make the field disable this will not allow you to submit value.

New line character in VB.Net?

The proper way to do this in VB is to use on of the VB constants for newlines. The main three are

  • vbCrLf = "\r\n"
  • vbCr = "\r"
  • vbLf = "\n"

VB by default doesn't allow for any character escape codes in strings which is different than languages like C# and C++ which do. One of the reasons for doing this is ease of use when dealing with file paths.

  • C++ file path string: "c:\\foo\\bar.txt"
  • VB file path string: "c:\foo\bar.txt"
  • C# file path string: C++ way or @"c:\foo\bar.txt"

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

Get the value in an input text box

You can only select a value with the following two ways:

// First way to get a value
value = $("#txt_name").val(); 

// Second way to get a value
value = $("#txt_name").attr('value');

If you want to use straight JavaScript to get the value, here is how:

document.getElementById('txt_name').value 

Connect to SQL Server through PDO using SQL Server Driver

Figured this out. Pretty simple:

 new PDO("sqlsrv:server=[sqlservername];Database=[sqlserverdbname]",  "[username]", "[password]");

Cannot read property 'addEventListener' of null

It's just bcz your JS gets loaded before the HTML part and so it can't find that element. Just put your whole JS code inside a function which will be called when the window gets loaded.

You can also put your Javascript code below the html.

How to create a multi line body in C# System.Net.Mail.MailMessage

Try using a StringBuilder object and use the appendline method. That might work.

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

How many significant digits do floats and doubles have in java?

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.

Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.

Sources:

http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers

http://en.wikipedia.org/wiki/Binary64

http://en.wikipedia.org/wiki/Binary32

How to display a Windows Form in full screen on top of the taskbar?

My simple fix it turned out to be calling the form's Activate() method, so there's no need to use TopMost (which is what I was aiming at).

batch file Copy files with certain extensions from multiple directories into one directory

you can also use vbscript

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder = "c:\test"
strDestination = "c:\tmp\"
Set objFolder = objFS.GetFolder(strFolder)

Go(objFolder)

Sub Go(objDIR)
  If objDIR <> "\System Volume Information" Then
    For Each eFolder in objDIR.SubFolders       
        Go eFolder
    Next
    For Each strFile In objDIR.Files
        strFileName = strFile.Name
        strExtension = objFS.GetExtensionName(strFile)
        If strExtension = "doc" Then
            objFS.CopyFile strFile , strDestination & strFileName
        End If 
    Next    
  End If  
End Sub 

save as mycopy.vbs and on command line

c:\test> cscript /nologo mycopy.vbs

Convert string (without any separator) to list

You mean that you want something like:

''.join(n for n in phone_str if n.isdigit())

This uses the fact that strings are iterable. They yield 1 character at a time when you iterate over them.


Regarding your efforts,

This one actually removes all of the digits from the string leaving you with only non-digits.

x = row.translate(None, string.digits)

This one splits the string on runs of whitespace, not after each character:

list = x.split()

Insert all values of a table into another table in SQL

The insert statement actually has a syntax for doing just that. It's a lot easier if you specify the column names rather than selecting "*" though:

INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
-- optionally WHERE ...

I'd better clarify this because for some reason this post is getting a few down-votes.

The INSERT INTO ... SELECT FROM syntax is for when the table you're inserting into ("new_table" in my example above) already exists. As others have said, the SELECT ... INTO syntax is for when you want to create the new table as part of the command.

You didn't specify whether the new table needs to be created as part of the command, so INSERT INTO ... SELECT FROM should be fine if your destination table already exists.

How do I count occurrence of duplicate items in array

If you have a multi-dimensional array you can use on PHP 5.5+ this:

array_count_values(array_column($array, 'key'))

which returns e.g.

 [
   'keyA' => 4,
   'keyB' => 2,
 ]

#if DEBUG vs. Conditional("DEBUG")

Usually you would need it in Program.cs where you want to decide to run either Debug on Non-Debug code and that too mostly in Windows Services. So I created a readonly field IsDebugMode and set its value in static constructor as shown below.

static class Program
{

    #region Private variable
    static readonly bool IsDebugMode = false;
    #endregion Private variable

    #region Constrcutors
    static Program()
    {
 #if DEBUG
        IsDebugMode = true;
 #endif
    }
    #endregion

    #region Main

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main(string[] args)
    {

        if (IsDebugMode)
        {
            MyService myService = new MyService(args);
            myService.OnDebug();             
        }
        else
        {
            ServiceBase[] services = new ServiceBase[] { new MyService (args) };
            services.Run(args);
        }
    }

    #endregion Main        
}

How to update (append to) an href in jquery?

var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');

To loop with each()

$("a.directions-link").each(function() {
   var $this = $(this);       
   var _href = $this.attr("href"); 
   $this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});

git status shows fatal: bad object HEAD

I solved this by copying the branch data (with the errors) to my apple laptop local git folder.

Somehow in the terminal and when running: git status, tells me more specific data where the error occurs. If you look under the errors, hopefully you see a list of folders with error. In my case GIT showed the folder which was responsible for the error. Deleting that folder and commiting the branche, I succeeded. git status was working again the other devices updating by git pull; everything working again on every machine.

Hopefully this will work for you also.

Ruby on Rails: Clear a cached page

If you're doing fragment caching, you can manually break the cache by updating your cache key, like so:

Version #1

<% cache ['cool_name_for_cache_key', 'v1'] do %>

Version #2

<% cache ['cool_name_for_cache_key', 'v2'] do %>

Or you can have the cache automatically reset based on the state of a non-static object, such as an ActiveRecord object, like so:

<% cache @user_object do %>

With this ^ method, any time the user object is updated, the cache will automatically be reset.

Delete branches in Bitbucket

in Bitbucket go to branches in left hand side menu.

  1. Select your branch you want to delete.
  2. Go to action column, click on three dots (...) and select delete.

Copying formula to the next row when inserting a new row

One other key thing that I found regarding copying rows within a table, is that the worksheet you are working on needs to be activated. If you have a workbook with multiple sheets, you need to save the sheet you called the macro from, and then activate the sheet with the table. Once you are done, you can re-activate the original sheet.

You can use Application.ScreenUpdating = False to make sure the user doesn't see that you are switching worksheets within your macro.

If you don't have the worksheet activated, the copy doesn't seem to work properly, i.e. some stuff seem to work, and other stuff doesn't ??

How to convert MySQL time to UNIX timestamp using PHP?

Use strtotime(..):

$timestamp = strtotime($mysqltime);
echo date("Y-m-d H:i:s", $timestamp);

Also check this out (to do it in MySQL way.)

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

How to center-justify the last line of text in CSS?

Most of the solutions here don't take into account any kind of responsive text box.

The amount of text on the last line of the paragraph is dictated by the size of the viewers browser, and so it becomes very difficult.

I think in short, if you want any kind of browser/mobile responsiveness, this isn't possible :(

Is it possible to add an HTML link in the body of a MAILTO link

I have implement following it working for iOS devices but failed on android devices

<a  href="mailto:?subject=Your mate might be interested...&body=<div style='padding: 0;'><div style='padding: 0;'><p>I found this on the site I think you might find it interesting.  <a href='@(Request.Url.ToString())' >Click here </a></p></div></div>">Share This</a>

Format a Go string without printing?

1. Simple strings

For "simple" strings (typically what fits into a line) the simplest solution is using fmt.Sprintf() and friends (fmt.Sprint(), fmt.Sprintln()). These are analogous to the functions without the starter S letter, but these Sxxx() variants return the result as a string instead of printing them to the standard output.

For example:

s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)

The variable s will be initialized with the value:

Hi, my name is Bob and I'm 23 years old.

Tip: If you just want to concatenate values of different types, you may not automatically need to use Sprintf() (which requires a format string) as Sprint() does exactly this. See this example:

i := 23
s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"

For concatenating only strings, you may also use strings.Join() where you can specify a custom separator string (to be placed between the strings to join).

Try these on the Go Playground.

2. Complex strings (documents)

If the string you're trying to create is more complex (e.g. a multi-line email message), fmt.Sprintf() becomes less readable and less efficient (especially if you have to do this many times).

For this the standard library provides the packages text/template and html/template. These packages implement data-driven templates for generating textual output. html/template is for generating HTML output safe against code injection. It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML.

Using the template packages basically requires you to provide a static template in the form of a string value (which may be originating from a file in which case you only provide the file name) which may contain static text, and actions which are processed and executed when the engine processes the template and generates the output.

You may provide parameters which are included/substituted in the static template and which may control the output generation process. Typical form of such parameters are structs and map values which may be nested.

Example:

For example let's say you want to generate email messages that look like this:

Hi [name]!

Your account is ready, your user name is: [user-name]

You have the following roles assigned:
[role#1], [role#2], ... [role#n]

To generate email message bodies like this, you could use the following static template:

const emailTmpl = `Hi {{.Name}}!

Your account is ready, your user name is: {{.UserName}}

You have the following roles assigned:
{{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}
`

And provide data like this for executing it:

data := map[string]interface{}{
    "Name":     "Bob",
    "UserName": "bob92",
    "Roles":    []string{"dbteam", "uiteam", "tester"},
}

Normally output of templates are written to an io.Writer, so if you want the result as a string, create and write to a bytes.Buffer (which implements io.Writer). Executing the template and getting the result as string:

t := template.Must(template.New("email").Parse(emailTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
    panic(err)
}
s := buf.String()

This will result in the expected output:

Hi Bob!

Your account is ready, your user name is: bob92

You have the following roles assigned:
dbteam, uiteam, tester

Try it on the Go Playground.

Also note that since Go 1.10, a newer, faster, more specialized alternative is available to bytes.Buffer which is: strings.Builder. Usage is very similar:

builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
    panic(err)
}
s := builder.String()

Try this one on the Go Playground.

Note: you may also display the result of a template execution if you provide os.Stdout as the target (which also implements io.Writer):

t := template.Must(template.New("email").Parse(emailTmpl))
if err := t.Execute(os.Stdout, data); err != nil {
    panic(err)
}

This will write the result directly to os.Stdout. Try this on the Go Playground.

ORA-01882: timezone region not found

This issue happens as the code which is trying to connect to db, has a timezone which is not in db. It can also be resolved by setting the time zone as below or any valid time zone available in oracle db. valid time zone which can be found select * from v$version;

System.setProperty("user.timezone", "America/New_York"); TimeZone.setDefault(null);

How to make input type= file Should accept only pdf and xls

If you want the file upload control to Limit the types of files user can upload on a button click then this is the way..

<script type="text/JavaScript">
<!-- Begin
function TestFileType( fileName, fileTypes ) {
if (!fileName) return;

dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];

return (fileTypes.join(".").indexOf(fileType) != -1) ?
alert('That file is OK!') : 
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
}
// -->
</script>

You can then call the function from an event like the onClick of the above button, which looks like:

onClick="TestFileType(this.form.uploadfile.value, ['gif', 'jpg', 'png', 'jpeg']);"

You can change this to: PDF and XLS

You can see it implemented over here: Demo

Can I call an overloaded constructor from another constructor of the same class in C#?

In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().

When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that

SQL JOIN - WHERE clause vs. ON clause

Let's consider those tables :

A

id | SomeData

B

id | id_A | SomeOtherData

id_A being a foreign key to table A

Writting this query :

SELECT *
FROM A
LEFT JOIN B
ON A.id = B.id_A;

Will provide this result :

/ : part of the result
                                       B
                      +---------------------------------+
            A         |                                 |
+---------------------+-------+                         |
|/////////////////////|///////|                         |
|/////////////////////|///////|                         |
|/////////////////////|///////|                         |
|/////////////////////|///////|                         |
|/////////////////////+-------+-------------------------+
|/////////////////////////////|
+-----------------------------+

What is in A but not in B means that there is null values for B.


Now, let's consider a specific part in B.id_A, and highlight it from the previous result :

/ : part of the result
* : part of the result with the specific B.id_A
                                       B
                      +---------------------------------+
            A         |                                 |
+---------------------+-------+                         |
|/////////////////////|///////|                         |
|/////////////////////|///////|                         |
|/////////////////////+---+///|                         |
|/////////////////////|***|///|                         |
|/////////////////////+---+---+-------------------------+
|/////////////////////////////|
+-----------------------------+

Writting this query :

SELECT *
FROM A
LEFT JOIN B
ON A.id = B.id_A
AND B.id_A = SpecificPart;

Will provide this result :

/ : part of the result
* : part of the result with the specific B.id_A
                                       B
                      +---------------------------------+
            A         |                                 |
+---------------------+-------+                         |
|/////////////////////|       |                         |
|/////////////////////|       |                         |
|/////////////////////+---+   |                         |
|/////////////////////|***|   |                         |
|/////////////////////+---+---+-------------------------+
|/////////////////////////////|
+-----------------------------+

Because this removes in the inner join the values that aren't in B.id_A = SpecificPart


Now, let's change the query to this :

SELECT *
FROM A
LEFT JOIN B
ON A.id = B.id_A
WHERE B.id_A = SpecificPart;

The result is now :

/ : part of the result
* : part of the result with the specific B.id_A
                                       B
                      +---------------------------------+
            A         |                                 |
+---------------------+-------+                         |
|                     |       |                         |
|                     |       |                         |
|                     +---+   |                         |
|                     |***|   |                         |
|                     +---+---+-------------------------+
|                             |
+-----------------------------+

Because the whole result is filtered against B.id_A = SpecificPart removing the parts B.id_A IS NULL, that are in the A that aren't in B

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
    //old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

Use string.Contains() with switch()

switch(message)
{
  case "test":
    Console.WriteLine("yes");
    break;                
  default:
    if (Contains("test2")) {
      Console.WriteLine("yes for test2");
    }
    break;
}

How to find files that match a wildcard string in Java?

Might not help you right now, but JDK 7 is intended to have glob and regex file name matching as part of "More NIO Features".

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

Place API key in Headers or URL

If you want an argument that might appeal to a boss: Think about what a URL is. URLs are public. People copy and paste them. They share them, they put them on advertisements. Nothing prevents someone (knowingly or not) from mailing that URL around for other people to use. If your API key is in that URL, everybody has it.

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

Simple explanation about SOAP and REST

SOAP - "Simple Object Access Protocol"

SOAP is a method of transferring messages, or small amounts of information, over the Internet. SOAP messages are formatted in XML and are typically sent using HTTP (hypertext transfer protocol).


Rest - Representational state transfer

Rest is a simple way of sending and receiving data between client and server and it doesn't have very many standards defined. You can send and receive data as JSON, XML or even plain text. It's light weighted compared to SOAP.


enter image description here

Converting file into Base64String and back again

private String encodeFileToBase64Binary(File file){    
String encodedfile = null;  
try {  
    FileInputStream fileInputStreamReader = new FileInputStream(file);  
    byte[] bytes = new byte[(int)file.length()];
    fileInputStreamReader.read(bytes);  
    encodedfile = Base64.encodeBase64(bytes).toString();  
} catch (FileNotFoundException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
} catch (IOException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
}  
    return encodedfile;  
}

Regex to test if string begins with http:// or https://

^https?://

You might have to escape the forward slashes though, depending on context.

twitter bootstrap typeahead ajax example

I am using this method

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
},
    {
    name: 'options',
    displayKey: 'value',
    source: function (query, process) {
        return $.get('/weather/searchCity/?q=%QUERY', { query: query }, function (data) {
            var matches = [];
            $.each(data, function(i, str) {
                matches.push({ value: str });
            });
            return process(matches);

        },'json');
    }
});

How to search a Git repository by commit message?

first to list the commits use

git log --oneline

then find the SHA of the commit (Message), then I used

 git log --stat 8zad24d

(8zad24d) is the SHA assosiated with the commit you are intrested in (the first couples sha example (8zad24d) you can select 4 char or 6 or 8 or the entire sha) to find the right info

Where is NuGet.Config file located in Visual Studio project?

There are multiple nuget packages read in the following order:

  1. First the NuGetDefaults.Config file. You will find this in %ProgramFiles(x86)%\NuGet\Config.
  2. The computer-level file.
  3. The user-level file. You will find this in %APPDATA%\NuGet\nuget.config.
  4. Any file named nuget.config beginning from the root of your drive up to the directory where nuget.exe is called.
  5. The config file you specify in the -configfile option when calling nuget.exe

You can find more information here.

How do I extend a class with c# extension methods?

Extension methods are syntactic sugar for making static methods whose first parameter is an instance of type T look as if they were an instance method on T.

As such the benefit is largely lost where you to make 'static extension methods' since they would serve to confuse the reader of the code even more than an extension method (since they appear to be fully qualified but are not actually defined in that class) for no syntactical gain (being able to chain calls in a fluent style within Linq for example).

Since you would have to bring the extensions into scope with a using anyway I would argue that it is simpler and safer to create:

public static class DateTimeUtils
{
    public static DateTime Tomorrow { get { ... } }
}

And then use this in your code via:

WriteLine("{0}", DateTimeUtils.Tomorrow)

Cannot assign requested address using ServerSocket.socketBind

Just for others who may look at this answer in the hope of solving a similar problem, I got a similar message because my ip address changed.

java.net.BindException: Cannot assign requested address: bind
    at sun.nio.ch.Net.bind(Native Method)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:126)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:59)
    at org.eclipse.jetty.server.nio.SelectChannelConnector.open(SelectChannelConnector.java:182)
    at org.eclipse.jetty.server.AbstractConnector.doStart(AbstractConnector.java:311)
    at org.eclipse.jetty.server.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:260)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
    at org.eclipse.jetty.server.Server.doStart(Server.java:273)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)

How to get text box value in JavaScript

This should be simple using jquery:

HTML:

  <input type="text" name="txtJob" value="software engineer">

JS:

  var jobValue = $('#txtJob').val(); //Get the text field value
  $('#txtJob').val(jobValue);        //Set the text field value

How to select first child with jQuery?

$('div.alldivs :first-child');

Or you can just refer to the id directly:

$('#div1');

As suggested, you might be better of using the child selector:

$('div.alldivs > div:first-child')

If you dont have to use first-child, you could use :first as also suggested, or $('div.alldivs').children(0).

How to represent a DateTime in Excel

The underlying data type of a datetime in Excel is a 64-bit floating point number where the length of a day equals 1 and 1st Jan 1900 00:00 equals 1. So 11th June 2009 17:30 is about 39975.72917.

If a cell contains a numeric value such as this, it can be converted to a datetime simply by applying a datetime format to the cell.

So, if you can convert your datetimes to numbers using the above formula, output them to the relevant cells and then set the cell formats to the appropriate datetime format, e.g. yyyy-mm-dd hh:mm:ss, then it should be possible to achieve what you want.

Also Stefan de Bruijn has pointed out that there is a bug in Excel in that it incorrectly assumes 1900 is a leap year so you need to take that into account when making your calculations (Wikipedia).

When do you use POST and when do you use GET?

I use POST when I don't want people to see the QueryString or when the QueryString gets large. Also, POST is needed for file uploads.

I don't see a problem using GET though, I use it for simple things where it makes sense to keep things on the QueryString.

Using GET will allow linking to a particular page possible too where POST would not work.

Add resources, config files to your jar using gradle

Thanks guys, I was migrating an existing project to Gradle and didn't like the idea of changing the project structure that much.

I have figured it out, thought this information could be useful to beginners.

Here is a sample task from my 'build.gradle':

version = '1.0.0'

jar {
   baseName = 'analytics'
   from('src/main/java') {
      include 'config/**/*.xml'
   }

   manifest {
       attributes 'Implementation-Title': 'Analytics Library', 'Implementation-Version': version
   }
}

How to download a folder from github?

If you want to automate the steps, the suggestions here will work only to an extent.

I came across this tool called fetch and it worked quite fine for me. You can even specify the release. So, it takes a step to download and set it as executable, then fetch the required folder:

curl -sSLfo ./fetch \
https://github.com/gruntwork-io/fetch/releases/download/v0.3.12/fetch_linux_amd64
chmod +x ./fetch
./fetch --repo="https://github.com/foo/bar" --tag="${VERSION}" --source-path="/baz" /tmp/baz

Why is the Android emulator so slow? How can we speed up the Android emulator?

Try to reduce the screen size of the emulator while creating a new Android virtual device.

I have seen that this will launch the emulator very fast compared to the default options provided in AVD manager.

How to calculate the sum of all columns of a 2D numpy array (efficiently)

a.sum(0)

should solve the problem. It is a 2d np.array and you will get the sum of all column. axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

ORA-00907: missing right parenthesis

Firstly, in histories_T, you are referencing table T_customer (should be T_customers) and secondly, you are missing the FOREIGN KEY clause that REFERENCES orders; which is not being created (or dropped) with the code you provided.

There may be additional errors as well, and I admit Oracle has never been very good at describing the cause of errors - "Mutating Tables" is a case in point.

Let me know if there additional problems you are missing.

PHP display current server path

You can also use the following alternative realpath.

Create a file called path.php

Put the following code inside by specifying the name of the created file.

<?php 
    echo realpath('path.php'); 
?>

A php file that you can move to all your folders to always have the absolute path from where the executed file is located.

;-)

In Python, how do I create a string of n characters in one line of code?

if you just want any letters:

 'a'*10  # gives 'aaaaaaaaaa'

if you want consecutive letters (up to 26):

 ''.join(['%c' % x for x in range(97, 97+10)])  # gives 'abcdefghij'

Kill a Process by Looking up the Port being used by it from a .BAT

Here's a command to get you started:

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO @ECHO TaskKill.exe /PID %%P

When you're confident in your batch file, remove @ECHO.

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /PID %%P

Note that you might need to change this slightly for different OS's. For example, on Windows 7 you might need tokens=5 instead of tokens=4.

How this works

FOR /F ... %variable IN ('command') DO otherCommand %variable...

This lets you execute command, and loop over its output. Each line will be stuffed into %variable, and can be expanded out in otherCommand as many times as you like, wherever you like. %variable in actual use can only have a single-letter name, e.g. %V.

"tokens=4 delims= "

This lets you split up each line by whitespace, and take the 4th chunk in that line, and stuffs it into %variable (in our case, %%P). delims looks empty, but that extra space is actually significant.

netstat -a -n -o

Just run it and find out. According to the command line help, it "Displays all connections and listening ports.", "Displays addresses and port numbers in numerical form.", and "Displays the owning process ID associated with each connection.". I just used these options since someone else suggested it, and it happened to work :)

^|

This takes the output of the first command or program (netstat) and passes it onto a second command program (findstr). If you were using this directly on the command line, instead of inside a command string, you would use | instead of ^|.

findstr :8080

This filters any output that is passed into it, returning only lines that contain :8080.

TaskKill.exe /PID <value>

This kills a running task, using the process ID.

%%P instead of %P

This is required in batch files. If you did this on the command prompt, you would use %P instead.

Foreign Key to multiple tables

CREATE TABLE dbo.OwnerType
(
    ID int NOT NULL,
    Name varchar(50) NULL
)

insert into OwnerType (Name) values ('User');
insert into OwnerType (Name) values ('Group');

I think that would be the most general way to represent what you want instead of using a flag.

Switch/toggle div (jQuery)

Use this:

<script type="text/javascript" language="javascript">
    $("#toggle").click(function() { $("#login-form, #recover-password").toggle(); });
</script>

Your HTML should look like:

<a id="toggle" href="javascript:void(0);">forgot password?</a>
<div id="login-form"></div>
<div id="recover-password" style="display:none;"></div>

Hey, all right! One line! I <3 jQuery.

Creating C formatted strings (not printing them)

http://www.gnu.org/software/hello/manual/libc/Variable-Arguments-Output.html gives the following example to print to stderr. You can modify it to use your log function instead:

 #include <stdio.h>
 #include <stdarg.h>

 void
 eprintf (const char *template, ...)
 {
   va_list ap;
   extern char *program_invocation_short_name;

   fprintf (stderr, "%s: ", program_invocation_short_name);
   va_start (ap, template);
   vfprintf (stderr, template, ap);
   va_end (ap);
 }

Instead of vfprintf you will need to use vsprintf where you need to provide an adequate buffer to print into.

Disable Rails SQL logging in console

This might not be a suitable solution for the console, but Rails has a method for this problem: Logger#silence

ActiveRecord::Base.logger.silence do
  # the stuff you want to be silenced
end

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

Changing the interval of SetInterval while it's running

Here is yet another way to create a decelerating/accelerating interval timer. The interval gets multiplied by a factor until a total time is exceeded.

function setChangingInterval(callback, startInterval, factor, totalTime) {
    let remainingTime = totalTime;
    let interval = startInterval;

    const internalTimer = () => {
        remainingTime -= interval ;
        interval *= factor;
        if (remainingTime >= 0) {
            setTimeout(internalTimer, interval);
            callback();
        }
    };
    internalTimer();
}

Check free disk space for current partition in bash

  1. df command : Report file system disk space usage
  2. du command : Estimate file space usage

Type df -h or df -k to list free disk space:

 $ df -h

OR

 $ df -k

du shows how much space one or more files or directories is using:

 $ du -sh

The -s option summarizes the space a directory is using and -h option provides Human-readable output.

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

Column count doesn't match value count at row 1

You can resolve the error by providing the column names you are affecting.

> INSERT INTO table_name (column1,column2,column3)
 `VALUES(50,'Jon Snow','Eye');`

please note that the semi colon should be added only after the statement providing values

PHP check if date between two dates

Use directly

$paymentDate = strtotime(date("d-m-Y"));
$contractDateBegin = strtotime("01-01-2001");
$contractDateEnd = strtotime("01-01-2015");

Then comparison will be ok cause your 01-01-2015 is valid for PHP's 32bit date-range, stated in strtotime's manual.

git checkout master error: the following untracked working tree files would be overwritten by checkout

Try git checkout -f master.

-f or --force

Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

How to update primary key

If you are sure that this change is suitable for the environment you're working in: set the FK conditions on the secondary tables to UPDATE CASCADING.

For example, if using SSMS as GUI:

  1. right click on the key
  2. select Modify
  3. Fold out 'INSERT And UPDATE Specific'
  4. For 'Update Rule', select Cascade.
  5. Close the dialog and save the key.

When you then update a value in the PK column in your primary table, the FK references in the other tables will be updated to point at the new value, preserving data integrity.

good postgresql client for windows?

I recommend Navicat strongly. What I found particularly excellent are it's import functions - you can import almost any data format (Access, Excel, DBF, Lotus ...), define a mapping between the source and destination which can be saved and is repeatable (I even keep my mappings under version control).

I have tried SQLMaestro and found it buggy (particularly for data import); PGAdmin is limited.

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

You can write your query like this.

var query = from t1 in myTABLE1List // List<TABLE_1>
            join t2 in myTABLE1List
               on t1.ColumnA equals t2.ColumnA
               and t1.ColumnB equals t2.ColumnA

If you want to compare your column with multiple columns.

Random row selection in Pandas dataframe

With pandas version 0.16.1 and up, there is now a DataFrame.sample method built-in:

import pandas

df = pandas.DataFrame(pandas.np.random.random(100))

# Randomly sample 70% of your dataframe
df_percent = df.sample(frac=0.7)

# Randomly sample 7 elements from your dataframe
df_elements = df.sample(n=7)

For either approach above, you can get the rest of the rows by doing:

df_rest = df.loc[~df.index.isin(df_percent.index)]

Angular: Cannot Get /

Just figured out the reason when we type "ng serve" INSIDE OUR PROJECT..
for example C:\Users\EdgeTech1\Desktop\CSharp\WebAPI\MyProject>ng serve

could not resolve module C:\Users\EdgeTech1\Desktop\C
results: failed compiled

root cause:
My folder name was C# Project..

Note: I tried to remove the # in my Project Name, I rename C# Project to CSharp instead and I tried to open cmd prompt again, typed the same thing..

for example:

C:\Users\EdgeTech1\Desktop\CSharp\WebAPI\MyProject>ng serve

and my project compiled successfully.. so as much as possible avoid ASCII characters in naming projects files.

How to convert from []byte to int in Go Programming

If []byte is ASCII byte numbers then first convert the []byte to string and use the strconv package Atoi method which convert string to int.

package main
import (
    "fmt"
    "strconv"
)

func main() {
    byteNumber := []byte("14")
    byteToInt, _ := strconv.Atoi(string(byteNumber))
    fmt.Println(byteToInt)
}

go playground - https://play.golang.org/p/gEzxva8-BGP

Get a list of distinct values in List

Distinct the Note class by Author

var DistinctItems = Note.GroupBy(x => x.Author).Select(y => y.First());

foreach(var item in DistinctItems)
{
    //Add to other List
}

Basic authentication for REST API using spring restTemplate

(maybe) the easiest way without importing spring-boot.

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));

TortoiseSVN icons not showing up under Windows 7

If you want to use Tortoise from within a 32 bit Application on Windows 7 64 bit, you need to install both the 64bit and the 32bit versions of Tortoise. According to Tortoise's makers, this works fine. (source)

How do I check if an element is hidden in jQuery?

if($(element).is(":visible")) {
  console.log('element is visible');
} else {
  console.log('element is not visible');
}

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

Initializing select with AngularJS and ng-repeat

The fact that angular is injecting an empty option element to the select is that the model object binded to it by default comes with an empty value in when initialized.

If you want to select a default option then you can probably can set it on the scope in the controller

$scope.filterCondition.operator = "your value here";

If you want to an empty option placeholder, this works for me

<select ng-model="filterCondition.operator" ng-options="operator.id as operator.name for operator in operators">
  <option value="">Choose Operator</option>
</select>

How to disable the parent form when a child form is active?

ChildForm child = new ChildForm();
child.Owner = this;
child.Show();

// In ChildForm_Load:

private void ChildForm_Load(object sender, EventArgs e) 
{
  this.Owner.Enabled = false;
}

private void ChildForm_Closed(object sender, EventArgs e) 
{
  this.Owner.Enabled = true;
} 

source : http://social.msdn.microsoft.com/Forums/vstudio/en-US/ae8ef4ef-3ac9-43d2-b883-20abd34f0e55/how-can-i-open-a-child-window-and-block-the-parent-window-only

Why is using onClick() in HTML a bad practice?

If you are using jQuery then:

HTML:

 <a id="openMap" href="/map/">link</a>

JS:

$(document).ready(function() {
    $("#openMap").click(function(){
        popup('/map/', 300, 300, 'map');
        return false;
    });
});

This has the benefit of still working without JS, or if the user middle clicks the link.

It also means that I could handle generic popups by rewriting again to:

HTML:

 <a class="popup" href="/map/">link</a>

JS:

$(document).ready(function() {
    $(".popup").click(function(){
        popup($(this).attr("href"), 300, 300, 'map');
        return false;
    });
});

This would let you add a popup to any link by just giving it the popup class.

This idea could be extended even further like so:

HTML:

 <a class="popup" data-width="300" data-height="300" href="/map/">link</a>

JS:

$(document).ready(function() {
    $(".popup").click(function(){
        popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
        return false;
    });
});

I can now use the same bit of code for lots of popups on my whole site without having to write loads of onclick stuff! Yay for reusability!

It also means that if later on I decide that popups are bad practice, (which they are!) and that I want to replace them with a lightbox style modal window, I can change:

popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');

to

myAmazingModalWindow($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');

and all my popups on my whole site are now working totally differently. I could even do feature detection to decide what to do on a popup, or store a users preference to allow them or not. With the inline onclick, this requires a huge copy and pasting effort.

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you are using CORS middleware and you want to send withCredential boolean true, you can configure CORS like this:

var cors = require('cors');    
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

How to make an ImageView with rounded corners?

Try this

Bitmap finalBitmap;
        if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
            finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                    false);
        else
            finalBitmap = bitmap;
        Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                finalBitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                finalBitmap.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f,
                finalBitmap.getHeight() / 2 + 0.7f,
                finalBitmap.getWidth() / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(
                android.graphics.PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(finalBitmap, rect, rect, paint);

        return output;

display data from SQL database into php/ html table

refer to http://www.w3schools.com/php/php_mysql_select.asp . If you are a beginner and want to learn, w3schools is a good place.

<?php
    $con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    $result = mysqli_query($con,"SELECT * FROM employee");

    while($row = mysqli_fetch_array($result))
      {
      echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
      echo "<br />";
      }

    mysqli_close($con);
    ?>

You can similarly echo it inside your table

<?php
 echo "<table>";
 while($row = mysqli_fetch_array($result))
          {
          echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
          }
 echo "</table>";
 mysqli_close($con);
?>