Programs & Examples On #Integration testing

A form of software testing where individual software modules (or components) are combined and tested as a group. Integration testing happens after unit testing, and before system testing.

Before and After Suite execution hook in jUnit 4.x

As for "Note: we're using maven 2 for our build. I've tried using maven's pre- & post-integration-test phases, but, if a test fails, maven stops and doesn't run post-integration-test, which is no help."

you can try the failsafe-plugin instead, I think it has the facility to ensure cleanup occurs regardless of setup or intermediate stage status

What's the difference between unit tests and integration tests?

A unit test tests code that you have complete control over whereas an integration test tests how your code uses or "integrates" with some other code.

So you would write unit tests to make sure your own libraries work as intended, and then write integration tests to make sure your code plays nicely with other code you are making use of, for instance a library.

Functional tests are related to integration tests, but refer more specifically to tests that test an entire system or application with all of the code running together, almost a super integration test.

How do I add a new sourceset to Gradle?

Update for 2021:

A lot has changed in 8ish years. Gradle continues to be a great tool. Now there's a whole section in the docs dedicated to configuring Integration Tests. I recommend you read the docs now.

Original Answer:

This took me a while to figure out and the online resources weren't great. So I wanted to document my solution.

This is a simple gradle build script that has an intTest source set in addition to the main and test source sets:

apply plugin: "java"

sourceSets {
    // Note that just declaring this sourceset creates two configurations.
    intTest {
        java {
            compileClasspath += main.output
            runtimeClasspath += main.output
        }
    }
}

configurations {
    intTestCompile.extendsFrom testCompile
    intTestRuntime.extendsFrom testRuntime
}

task intTest(type:Test){
    description = "Run integration tests (located in src/intTest/...)."
    testClassesDir = project.sourceSets.intTest.output.classesDir
    classpath = project.sourceSets.intTest.runtimeClasspath
}

Integration Testing POSTing an entire object to Spring MVC controller

One of the main purposes of integration testing with MockMvc is to verify that model objects are correclty populated with form data.

In order to do it you have to pass form data as they're passed from actual form (using .param()). If you use some automatic conversion from NewObject to from data, your test won't cover particular class of possible problems (modifications of NewObject incompatible with actual form).

Testing Spring's @RequestBody using Spring MockMVC

Use this one

public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

@Test
public void testInsertObject() throws Exception { 
    String url = BASE_URL + "/object";
    ObjectBean anObject = new ObjectBean();
    anObject.setObjectId("33");
    anObject.setUserId("4268321");
    //... more
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
    String requestJson=ow.writeValueAsString(anObject );

    mockMvc.perform(post(url).contentType(APPLICATION_JSON_UTF8)
        .content(requestJson))
        .andExpect(status().isOk());
}

As described in the comments, this works because the object is converted to json and passed as the request body. Additionally, the contentType is defined as Json (APPLICATION_JSON_UTF8).

More info on the HTTP request body structure

How to make an array of arrays in Java

try

String[][] arrays = new String[5][];

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

AngularJS : Factory and Service?

Factory and Service is a just wrapper of a provider.

Factory

Factory can return anything which can be a class(constructor function), instance of class, string, number or boolean. If you return a constructor function, you can instantiate in your controller.

 myApp.factory('myFactory', function () {

  // any logic here..

  // Return any thing. Here it is object
  return {
    name: 'Joe'
  }
}

Service

Service does not need to return anything. But you have to assign everything in this variable. Because service will create instance by default and use that as a base object.

myApp.service('myService', function () {

  // any logic here..

  this.name = 'Joe';
}

Actual angularjs code behind the service

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

It just a wrapper around the factory. If you return something from service, then it will behave like Factory.

IMPORTANT: The return result from Factory and Service will be cache and same will be returned for all controllers.

When should i use them?

Factory is mostly preferable in all cases. It can be used when you have constructor function which needs to be instantiated in different controllers.

Service is a kind of Singleton Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application. Eg: Authenticated user details.

For further understanding, read

http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

Replace special characters in a string with _ (underscore)

string = string.replace(/[\W_]/g, "_");

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Bottom Line

Use either COUNT(field) or COUNT(*), and stick with it consistently, and if your database allows COUNT(tableHere) or COUNT(tableHere.*), use that.

In short, don't use COUNT(1) for anything. It's a one-trick pony, which rarely does what you want, and in those rare cases is equivalent to count(*)

Use count(*) for counting

Use * for all your queries that need to count everything, even for joins, use *

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But don't use COUNT(*) for LEFT joins, as that will return 1 even if the subordinate table doesn't match anything from parent table

SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Don't be fooled by those advising that when using * in COUNT, it fetches entire row from your table, saying that * is slow. The * on SELECT COUNT(*) and SELECT * has no bearing to each other, they are entirely different thing, they just share a common token, i.e. *.

An alternate syntax

In fact, if it is not permitted to name a field as same as its table name, RDBMS language designer could give COUNT(tableNameHere) the same semantics as COUNT(*). Example:

For counting rows we could have this:

SELECT COUNT(emp) FROM emp

And they could make it simpler:

SELECT COUNT() FROM emp

And for LEFT JOINs, we could have this:

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But they cannot do that (COUNT(tableNameHere)) since SQL standard permits naming a field with the same name as its table name:

CREATE TABLE fruit -- ORM-friendly name
(
fruit_id int NOT NULL,
fruit varchar(50), /* same name as table name, 
                and let's say, someone forgot to put NOT NULL */
shape varchar(50) NOT NULL,
color varchar(50) NOT NULL
)

Counting with null

And also, it is not a good practice to make a field nullable if its name matches the table name. Say you have values 'Banana', 'Apple', NULL, 'Pears' on fruit field. This will not count all rows, it will only yield 3, not 4

SELECT count(fruit) FROM fruit

Though some RDBMS do that sort of principle (for counting the table's rows, it accepts table name as COUNT's parameter), this will work in Postgresql (if there is no subordinate field in any of the two tables below, i.e. as long as there is no name conflict between field name and table name):

SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

But that could cause confusion later if we will add a subordinate field in the table, as it will count the field(which could be nullable), not the table rows.

So to be on the safe side, use:

SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

count(1): The one-trick pony

In particular to COUNT(1), it is a one-trick pony, it works well only on one table query:

SELECT COUNT(1) FROM tbl

But when you use joins, that trick won't work on multi-table queries without its semantics being confused, and in particular you cannot write:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

So what's the meaning of COUNT(1) here?

SELECT boss.boss_id, COUNT(1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Is it this...?

-- counting all the subordinates only
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Or this...?

-- or is that COUNT(1) will also count 1 for boss regardless if boss has a subordinate
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

By careful thought, you can infer that COUNT(1) is the same as COUNT(*), regardless of type of join. But for LEFT JOINs result, we cannot mold COUNT(1) to work as: COUNT(subordinate.boss_id), COUNT(subordinate.*)

So just use either of the following:

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Works on Postgresql, it's clear that you want to count the cardinality of the set

-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id

Another way to count the cardinality of the set, very English-like (just don't make a column with a name same as its table name) : http://www.sqlfiddle.com/#!1/98515/7

select boss.boss_name, count(subordinate)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You cannot do this: http://www.sqlfiddle.com/#!1/98515/8

select boss.boss_name, count(subordinate.1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

You can do this, but this produces wrong result: http://www.sqlfiddle.com/#!1/98515/9

select boss.boss_name, count(1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name

Root element is missing

I had the same problem when i have trying to read xml that was extracted from archive to memory stream.

 MemoryStream SubSetupStream = new MemoryStream();
        using (ZipFile archive = ZipFile.Read(zipPath))
        {
            archive.Password = "SomePass";
            foreach  (ZipEntry file in archive)
            {
                file.Extract(SubSetupStream);
            }
        }

Problem was in these lines:

XmlDocument doc = new XmlDocument();
    doc.Load(SubSetupStream);

And solution is (Thanks to @Phil):

        if (SubSetupStream.Position>0)
        {
            SubSetupStream.Position = 0;
        }

Angular - POST uploaded file

First, you have to create your own inline TS-Class, since the FormData Class is not well supported at the moment:

var data : {
  name: string;
  file: File;
} = {
  name: "Name",
  file: inputValue.files[0]
  };

Then you send it to the Server with JSON.stringify(data)

let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);

How to auto resize and adjust Form controls with change in resolution

float widthRatio = Screen.PrimaryScreen.Bounds.Width / 1280;
float heightRatio = Screen.PrimaryScreen.Bounds.Height / 800f;
SizeF scale = new SizeF(widthRatio, heightRatio);
this.Scale(scale);
foreach (Control control in this.Controls)
{
control.Font = new Font("Verdana", control.Font.SizeInPoints * heightRatio * widthRatio);
}

Get the Last Inserted Id Using Laravel Eloquent

$objPost = new Post;
$objPost->title = 'Title';
$objPost->description = 'Description';   
$objPost->save();
$recId = $objPost->id; // If Id in table column name if other then id then user the other column name

return Response::json(['success' => true,'id' => $recId], 200);

How to use cURL in Java?

You can make use of java.net.URL and/or java.net.URLConnection.

URL url = new URL("https://stackoverflow.com");

try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
    for (String line; (line = reader.readLine()) != null;) {
        System.out.println(line);
    }
}

Also see the Oracle's simple tutorial on the subject. It's however a bit verbose. To end up with less verbose code, you may want to consider Apache HttpClient instead.

By the way: if your next question is "How to process HTML result?", then the answer is "Use a HTML parser. No, don't use regex for this.".

See also:

How to create a hidden <img> in JavaScript?

How about

<img style="display: none;" src="a.gif">

That will disable the display completely, and not leave a placeholder

Adding a parameter to the URL with JavaScript

Here's a vastly simplified version, making tradeoffs for legibility and fewer lines of code instead of micro-optimized performance (and we're talking about a few miliseconds difference, realistically... due to the nature of this (operating on the current document's location), this will most likely be ran once on a page).

/**
* Add a URL parameter (or changing it if it already exists)
* @param {search} string  this is typically document.location.search
* @param {key}    string  the key to set
* @param {val}    string  value 
*/
var addUrlParam = function(search, key, val){
  var newParam = key + '=' + val,
      params = '?' + newParam;

  // If the "search" string exists, then build params from it
  if (search) {
    // Try to replace an existance instance
    params = search.replace(new RegExp('([?&])' + key + '[^&]*'), '$1' + newParam);

    // If nothing was replaced, then add the new param to the end
    if (params === search) {
      params += '&' + newParam;
    }
  }

  return params;
};

You would then use this like so:

document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');

PyCharm error: 'No Module' when trying to import own module (python script)

Content roots are folders holding your project code while source roots are defined as same too. The only difference i came to understand was that the code in source roots is built before the code in the content root.

Unchecking them wouldn't affect the runtime till the point you're not making separate modules in your package which are manually connected to Django. That means if any of your files do not hold the 'from django import...' or any of the function isn't called via django, unchecking these 2 options will result in a malfunction.

Update - the problem only arises when using Virtual Environmanet, and only when controlling the project via the provided terminal. Cause the terminal still works via the default system pyhtonpath and not the virtual env. while the python django control panel works fine.

Why are Python lambdas useful?

I use it quite often, mainly as a null object or to partially bind parameters to a function.

Here are examples:

to implement null object pattern:

{
    DATA_PACKET: self.handle_data_packets
    NET_PACKET: self.handle_hardware_packets
}.get(packet_type, lambda x : None)(payload)

for parameter binding:

let say that I have the following API

def dump_hex(file, var)
    # some code
    pass

class X(object):
    #...
    def packet_received(data):
        # some kind of preprocessing
        self.callback(data)
    #...

Then, when I wan't to quickly dump the recieved data to a file I do that:

dump_file = file('hex_dump.txt','w')
X.callback = lambda (x): dump_hex(dump_file, x)
...
dump_file.close()

How can I use modulo operator (%) in JavaScript?

That would be the modulo operator, which produces the remainder of the division of two numbers.

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

One option if the number of keys is small is to use chained gets:

value = myDict.get('lastName', myDict.get('firstName', myDict.get('userName')))

But if you have keySet defined, this might be clearer:

value = None
for key in keySet:
    if key in myDict:
        value = myDict[key]
        break

The chained gets do not short-circuit, so all keys will be checked but only one used. If you have enough possible keys that that matters, use the for loop.

Get the previous month's first and last day dates in c#

I use this simple one-liner:

public static DateTime GetLastDayOfPreviousMonth(this DateTime date)
{
    return date.AddDays(-date.Day);
}

Be aware, that it retains the time.

Bootstrap 4, How do I center-align a button?

you can also just wrap with an H class or P class with a text-center attribute

Passing variables through handlebars partial

This is very possible if you write your own helper. We are using a custom $ helper to accomplish this type of interaction (and more):

/*///////////////////////

Adds support for passing arguments to partials. Arguments are merged with 
the context for rendering only (non destructive). Use `:token` syntax to 
replace parts of the template path. Tokens are replace in order.

USAGE: {{$ 'path.to.partial' context=newContext foo='bar' }}
USAGE: {{$ 'path.:1.:2' replaceOne replaceTwo foo='bar' }}

///////////////////////////////*/

Handlebars.registerHelper('$', function(partial) {
    var values, opts, done, value, context;
    if (!partial) {
        console.error('No partial name given.');
    }
    values = Array.prototype.slice.call(arguments, 1);
    opts = values.pop();
    while (!done) {
        value = values.pop();
        if (value) {
            partial = partial.replace(/:[^\.]+/, value);
        }
        else {
            done = true;
        }
    }
    partial = Handlebars.partials[partial];
    if (!partial) {
        return '';
    }
    context = _.extend({}, opts.context||this, _.omit(opts, 'context', 'fn', 'inverse'));
    return new Handlebars.SafeString( partial(context) );
});

How to print last two columns using awk

You can make use of variable NF which is set to the total number of fields in the input record:

awk '{print $(NF-1),"\t",$NF}' file

this assumes that you have at least 2 fields.

Selecting/excluding sets of columns in pandas

In a similar vein, when reading a file, one may wish to exclude columns upfront, rather than wastefully reading unwanted data into memory and later discarding them.

As of pandas 0.20.0, usecols now accepts callables.1 This update allows more flexible options for reading columns:

skipcols = [...]
read_csv(..., usecols=lambda x: x not in skipcols)

The latter pattern is essentially the inverse of the traditional usecols method - only specified columns are skipped.


Given

Data in a file

import numpy as np
import pandas as pd


df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))

filename = "foo.csv"
df.to_csv(filename)

Code

skipcols = ["B", "D"]
df1 = pd.read_csv(filename, usecols=lambda x: x not in skipcols, index_col=0)
df1

Output

          A         C
0  0.062350  0.076924
1 -0.016872  1.091446
2  0.213050  1.646109
3 -1.196928  1.153497
4 -0.628839 -0.856529
...

Details

A DataFrame was written to a file. It was then read back as a separate DataFrame, now skipping unwanted columns (B and D).

Note that for the OP's situation, since data is already created, the better approach is the accepted answer, which drops unwanted columns from an extant object. However, the technique presented here is most useful when directly reading data from files into a DataFrame.

A request was raised for a "skipcols" option in this issue and was addressed in a later issue.

Retrieving JSON Object Literal from HttpServletRequest

make use of the jackson JSON processor

 ObjectMapper mapper = new ObjectMapper();
  Book book = mapper.readValue(request.getInputStream(),Book.class);

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

Can I get "&&" or "-and" to work in PowerShell?

Try this:

$errorActionPreference='Stop'; csc /t:exe /out:a.exe SomeFile.cs; a.exe

How can I get the nth character of a string?

You would do:

char c = str[1];

Or even:

char c = "Hello"[1];

edit: updated to find the "E".

How do I get the path to the current script with Node.js?

When it comes to the main script it's as simple as:

process.argv[1]

From the Node.js documentation:

process.argv

An array containing the command line arguments. The first element will be 'node', the second element will be the path to the JavaScript file. The next elements will be any additional command line arguments.

If you need to know the path of a module file then use __filename.

Grant Select on a view not base table when base table is in a different database

The way I have done this is to give the user permission to the tables that I didn't want them to have access to. Then fine tune the select permission in SSMS by only allowing select permission to the columns that are in my view. This way, the select clause on the table is only limited to the columns that they see in the view anyways.

enter image description here

Shaji

How to do jquery code AFTER page loading?

I am looking for the same problem and here is what help me. Here is the jQuery version 3.1.0 and the load event is deprecated for use since jQuery version 1.8. The load event is removed from jQuery 3.0. Instead, you can use on method and bind the JavaScript load event:

$(window).on('load', function () {
  alert("Window Loaded");
});

Spring - applicationContext.xml cannot be opened because it does not exist

While working with Maven got same issue then I put XML file into src/main/java path and it worked.

ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");

Does hosts file exist on the iPhone? How to change it?

Another option here is to have your iPhone connect via a proxy. Here's an example of how to do it with Fiddler (it's very easy):

http://conceptdev.blogspot.com/2009/01/monitoring-iphone-web-traffic-with.html

In that case any dns lookups your iPhone does will use the hosts file of the machine Fiddler is running on. Note, though, that you must use a name that will be resolved via DNS. example.local, for instance, will not work. example.xyz or example.dev will.

Javascript equivalent of php's strtotime()?

I found this article and tried the tutorial. Basically, you can use the date constructor to parse a date, then write get the seconds from the getTime() method

var d=new Date("October 13, 1975 11:13:00");
document.write(d.getTime() + " milliseconds since 1970/01/01");

Does this work?

Change tab bar item selected color in a storyboard

Add Runtime Color attribute named "tintColor" from StoryBoard. This is working(for Xcode 8 and above).

if you want unselected color.. you can add unselectedItemTintColor too.

setting tintColor as Runtime Attribute

How to set a cookie for another domain

Setting cookies for another domain is not possible.

If you want to pass data to another domain, you can encode this into the url.

a.com  ->  b.com/redirect?info=some+info (and set cookie) -> b.com/other+page

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

Android "elevation" not showing a shadow

In my case, this was caused by a custom parent component setting the rendering layer type to "Software":

setLayerType(View.LAYER_TYPE_SOFTWARE, null);

Removing this line of did the trick. Or course you need to evaluate why this is there in the first place. In my case it was to support Honeycomb, which is well behind the current minimum SDK for my project.

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

What does "Object reference not set to an instance of an object" mean?

Most of the time, when you try to assing value into object, and if the value is null, then this kind of exception occur. Please check this link.

for the sake of self learning, you can put some check condition. like

if (myObj== null)
Console.Write("myObj is NULL");

Given a class, see if instance has method (Ruby)

klass.instance_methods.include :method_name or "method_name", depending on the Ruby version I think.

Add CSS3 transition expand/collapse

this should work, had to try a while too.. :D

_x000D_
_x000D_
function showHide(shID) {_x000D_
  if (document.getElementById(shID)) {_x000D_
    if (document.getElementById(shID + '-show').style.display != 'none') {_x000D_
      document.getElementById(shID + '-show').style.display = 'none';_x000D_
      document.getElementById(shID + '-hide').style.display = 'inline';_x000D_
      document.getElementById(shID).style.height = '100px';_x000D_
    } else {_x000D_
      document.getElementById(shID + '-show').style.display = 'inline';_x000D_
      document.getElementById(shID + '-hide').style.display = 'none';_x000D_
      document.getElementById(shID).style.height = '0px';_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
#example {_x000D_
  background: red;_x000D_
  height: 0px;_x000D_
  overflow: hidden;_x000D_
  transition: height 2s;_x000D_
  -moz-transition: height 2s;_x000D_
  /* Firefox 4 */_x000D_
  -webkit-transition: height 2s;_x000D_
  /* Safari and Chrome */_x000D_
  -o-transition: height 2s;_x000D_
  /* Opera */_x000D_
}_x000D_
_x000D_
a.showLink,_x000D_
a.hideLink {_x000D_
  text-decoration: none;_x000D_
  background: transparent url('down.gif') no-repeat left;_x000D_
}_x000D_
_x000D_
a.hideLink {_x000D_
  background: transparent url('up.gif') no-repeat left;_x000D_
}
_x000D_
Here is some text._x000D_
<div class="readmore">_x000D_
  <a href="#" id="example-show" class="showLink" onclick="showHide('example');return false;">Read more</a>_x000D_
  <div id="example" class="more">_x000D_
    <div class="text">_x000D_
      Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit amet._x000D_
      Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas._x000D_
    </div>_x000D_
    <p>_x000D_
      <a href="#" id="example-hide" class="hideLink" onclick="showHide('example');return false;">Hide</a>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I convert NSMutableArray to NSArray?

Objective-C

Below is way to convert NSMutableArray to NSArray:

//oldArray is having NSMutableArray data-type.
//Using Init with Array method.
NSArray *newArray1 = [[NSArray alloc]initWithArray:oldArray];

//Make copy of array
NSArray *newArray2 = [oldArray copy];

//Make mutablecopy of array
NSArray *newArray3 = [oldArray mutableCopy];

//Directly stored NSMutableArray to NSArray.
NSArray *newArray4 = oldArray;

Swift

In Swift 3.0 there is new data type Array. Declare Array using let keyword then it would become NSArray And if declare using var keyword then it's become NSMutableArray.

Sample code:

let newArray = oldArray as Array

Force sidebar height 100% using CSS (with a sticky bottom image)?

use body background if you are using fixed width sidebar give the same width image as your side bar. also put background-repeat:repeat-y in your css codes.

Removing empty rows of a data file in R

If you have empty rows, not NAs, you can do:

data[!apply(data == "", 1, all),]

To remove both (NAs and empty):

data <- data[!apply(is.na(data) | data == "", 1, all),]

WPF MVVM ComboBox SelectedItem or SelectedValue not working

I had the same problem. The thing is. The selected item doesnt know which object it should use from the collection. So you have to say to the selected item to use the item from the collection.

public MyObject SelectedObject
 {
      get
      {
          Objects.find(x => x.id == _selectedObject.id)
          return _selectedObject;
      }
      set
      {
           _selectedObject = value;
      }
 }

I hope this helps.

how to make negative numbers into positive

You have to use:

abs() for int
fabs() for double
fabsf() for float

Above function will also work but you can also try something like this.

    if(a<0)
    {
         a=-a;
    }

The performance impact of using instanceof in Java

Demian and Paul mention a good point; however, the placement of the code to execute really depends on how you want to use the data...

I'm a big fan of small data objects that can be used in many ways. If you follow the override (polymorphic) approach, your objects can only be used "one way".

This is where patterns come in...

You can use double-dispatch (as in the visitor pattern) to ask each object to "call you" passing itself -- this will resolve the type of the object. However (again) you'll need a class that can "do stuff" with all of the possible subtypes.

I prefer to use a strategy pattern, where you can register strategies for each subtype you want to handle. Something like the following. Note that this only helps for exact type matches, but has the advantage that it's extensible - third-party contributors can add their own types and handlers. (This is good for dynamic frameworks like OSGi, where new bundles can be added)

Hopefully this will inspire some other ideas...

package com.javadude.sample;

import java.util.HashMap;
import java.util.Map;

public class StrategyExample {
    static class SomeCommonSuperType {}
    static class SubType1 extends SomeCommonSuperType {}
    static class SubType2 extends SomeCommonSuperType {}
    static class SubType3 extends SomeCommonSuperType {}

    static interface Handler<T extends SomeCommonSuperType> {
        Object handle(T object);
    }

    static class HandlerMap {
        private Map<Class<? extends SomeCommonSuperType>, Handler<? extends SomeCommonSuperType>> handlers_ =
            new HashMap<Class<? extends SomeCommonSuperType>, Handler<? extends SomeCommonSuperType>>();
        public <T extends SomeCommonSuperType> void add(Class<T> c, Handler<T> handler) {
            handlers_.put(c, handler);
        }
        @SuppressWarnings("unchecked")
        public <T extends SomeCommonSuperType> Object handle(T o) {
            return ((Handler<T>) handlers_.get(o.getClass())).handle(o);
        }
    }

    public static void main(String[] args) {
        HandlerMap handlerMap = new HandlerMap();

        handlerMap.add(SubType1.class, new Handler<SubType1>() {
            @Override public Object handle(SubType1 object) {
                System.out.println("Handling SubType1");
                return null;
            } });
        handlerMap.add(SubType2.class, new Handler<SubType2>() {
            @Override public Object handle(SubType2 object) {
                System.out.println("Handling SubType2");
                return null;
            } });
        handlerMap.add(SubType3.class, new Handler<SubType3>() {
            @Override public Object handle(SubType3 object) {
                System.out.println("Handling SubType3");
                return null;
            } });

        SubType1 subType1 = new SubType1();
        handlerMap.handle(subType1);
        SubType2 subType2 = new SubType2();
        handlerMap.handle(subType2);
        SubType3 subType3 = new SubType3();
        handlerMap.handle(subType3);
    }
}

Better way to remove specific characters from a Perl string

You could use the tr instead:

       $p =~ tr/fo//d;

will delete every f and every o from $p. In your case it should be:

       $p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d

See Perl's tr documentation.

tr/SEARCHLIST/REPLACEMENTLIST/cdsr

Transliterates all occurrences of the characters found (or not found if the /c modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.

[…]

If the /d modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.

How to add a recyclerView inside another recyclerView

I would like to suggest to use a single RecyclerView and populate your list items dynamically. I've added a github project to describe how this can be done. You might have a look. While the other solutions will work just fine, I would like to suggest, this is a much faster and efficient way of showing multiple lists in a RecyclerView.

The idea is to add logic in your onCreateViewHolder and onBindViewHolder method so that you can inflate proper view for the exact positions in your RecyclerView.

I've added a sample project along with that wiki too. You might clone and check what it does. For convenience, I am posting the adapter that I have used.

public class DynamicListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int FOOTER_VIEW = 1;
    private static final int FIRST_LIST_ITEM_VIEW = 2;
    private static final int FIRST_LIST_HEADER_VIEW = 3;
    private static final int SECOND_LIST_ITEM_VIEW = 4;
    private static final int SECOND_LIST_HEADER_VIEW = 5;

    private ArrayList<ListObject> firstList = new ArrayList<ListObject>();
    private ArrayList<ListObject> secondList = new ArrayList<ListObject>();

    public DynamicListAdapter() {
    }

    public void setFirstList(ArrayList<ListObject> firstList) {
        this.firstList = firstList;
    }

    public void setSecondList(ArrayList<ListObject> secondList) {
        this.secondList = secondList;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // List items of first list
        private TextView mTextDescription1;
        private TextView mListItemTitle1;

        // List items of second list
        private TextView mTextDescription2;
        private TextView mListItemTitle2;

        // Element of footer view
        private TextView footerTextView;

        public ViewHolder(final View itemView) {
            super(itemView);

            // Get the view of the elements of first list
            mTextDescription1 = (TextView) itemView.findViewById(R.id.description1);
            mListItemTitle1 = (TextView) itemView.findViewById(R.id.title1);

            // Get the view of the elements of second list
            mTextDescription2 = (TextView) itemView.findViewById(R.id.description2);
            mListItemTitle2 = (TextView) itemView.findViewById(R.id.title2);

            // Get the view of the footer elements
            footerTextView = (TextView) itemView.findViewById(R.id.footer);
        }

        public void bindViewSecondList(int pos) {

            if (firstList == null) pos = pos - 1;
            else {
                if (firstList.size() == 0) pos = pos - 1;
                else pos = pos - firstList.size() - 2;
            }

            final String description = secondList.get(pos).getDescription();
            final String title = secondList.get(pos).getTitle();

            mTextDescription2.setText(description);
            mListItemTitle2.setText(title);
        }

        public void bindViewFirstList(int pos) {

            // Decrease pos by 1 as there is a header view now.
            pos = pos - 1;

            final String description = firstList.get(pos).getDescription();
            final String title = firstList.get(pos).getTitle();

            mTextDescription1.setText(description);
            mListItemTitle1.setText(title);
        }

        public void bindViewFooter(int pos) {
            footerTextView.setText("This is footer");
        }
    }

    public class FooterViewHolder extends ViewHolder {
        public FooterViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class FirstListHeaderViewHolder extends ViewHolder {
        public FirstListHeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class FirstListItemViewHolder extends ViewHolder {
        public FirstListItemViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class SecondListHeaderViewHolder extends ViewHolder {
        public SecondListHeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class SecondListItemViewHolder extends ViewHolder {
        public SecondListItemViewHolder(View itemView) {
            super(itemView);
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v;

        if (viewType == FOOTER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_footer, parent, false);
            FooterViewHolder vh = new FooterViewHolder(v);
            return vh;

        } else if (viewType == FIRST_LIST_ITEM_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list, parent, false);
            FirstListItemViewHolder vh = new FirstListItemViewHolder(v);
            return vh;

        } else if (viewType == FIRST_LIST_HEADER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list_header, parent, false);
            FirstListHeaderViewHolder vh = new FirstListHeaderViewHolder(v);
            return vh;

        } else if (viewType == SECOND_LIST_HEADER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list_header, parent, false);
            SecondListHeaderViewHolder vh = new SecondListHeaderViewHolder(v);
            return vh;

        } else {
            // SECOND_LIST_ITEM_VIEW
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list, parent, false);
            SecondListItemViewHolder vh = new SecondListItemViewHolder(v);
            return vh;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        try {
            if (holder instanceof SecondListItemViewHolder) {
                SecondListItemViewHolder vh = (SecondListItemViewHolder) holder;
                vh.bindViewSecondList(position);

            } else if (holder instanceof FirstListHeaderViewHolder) {
                FirstListHeaderViewHolder vh = (FirstListHeaderViewHolder) holder;

            } else if (holder instanceof FirstListItemViewHolder) {
                FirstListItemViewHolder vh = (FirstListItemViewHolder) holder;
                vh.bindViewFirstList(position);

            } else if (holder instanceof SecondListHeaderViewHolder) {
                SecondListHeaderViewHolder vh = (SecondListHeaderViewHolder) holder;

            } else if (holder instanceof FooterViewHolder) {
                FooterViewHolder vh = (FooterViewHolder) holder;
                vh.bindViewFooter(position);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {

        int firstListSize = 0;
        int secondListSize = 0;

        if (secondList == null && firstList == null) return 0;

        if (secondList != null)
            secondListSize = secondList.size();
        if (firstList != null)
            firstListSize = firstList.size();

        if (secondListSize > 0 && firstListSize > 0)
            return 1 + firstListSize + 1 + secondListSize + 1;   // first list header, first list size, second list header , second list size, footer
        else if (secondListSize > 0 && firstListSize == 0)
            return 1 + secondListSize + 1;                       // second list header, second list size, footer
        else if (secondListSize == 0 && firstListSize > 0)
            return 1 + firstListSize;                            // first list header , first list size
        else return 0;
    }

    @Override
    public int getItemViewType(int position) {

        int firstListSize = 0;
        int secondListSize = 0;

        if (secondList == null && firstList == null)
            return super.getItemViewType(position);

        if (secondList != null)
            secondListSize = secondList.size();
        if (firstList != null)
            firstListSize = firstList.size();

        if (secondListSize > 0 && firstListSize > 0) {
            if (position == 0) return FIRST_LIST_HEADER_VIEW;
            else if (position == firstListSize + 1)
                return SECOND_LIST_HEADER_VIEW;
            else if (position == secondListSize + 1 + firstListSize + 1)
                return FOOTER_VIEW;
            else if (position > firstListSize + 1)
                return SECOND_LIST_ITEM_VIEW;
            else return FIRST_LIST_ITEM_VIEW;

        } else if (secondListSize > 0 && firstListSize == 0) {
            if (position == 0) return SECOND_LIST_HEADER_VIEW;
            else if (position == secondListSize + 1) return FOOTER_VIEW;
            else return SECOND_LIST_ITEM_VIEW;

        } else if (secondListSize == 0 && firstListSize > 0) {
            if (position == 0) return FIRST_LIST_HEADER_VIEW;
            else return FIRST_LIST_ITEM_VIEW;
        }

        return super.getItemViewType(position);
    }
}

There is another way of keeping your items in a single ArrayList of objects so that you can set an attribute tagging the items to indicate which item is from first list and which one belongs to second list. Then pass that ArrayList into your RecyclerView and then implement the logic inside adapter to populate them dynamically.

Hope that helps.

Regular Expressions- Match Anything

For JavaScript the best and simplest answer would seem to be /.\*/.

As suggested by others /(.*?)/ would work as well but /.\*/ is simpler. The () inside the pattern are not needed, as far as I can see nor the ending ? to match absolutely anything (including empty strings)


NON-SOLUTIONS:

  • /[\s\S]/ does NOT match empty strings so it's not the solution.

  • /[\s\S]\*/ DOES match also empty strings. But it has a problem: If you use it in your code then you can't comment out such code because the */ is interpreted as end-of-comment.

/([\s\S]\*)/ works and does not have the comment-problem. But it is longer and more complicated to understand than /.*/.

python NameError: global name '__file__' is not defined

I've run into cases where __file__ doesn't work as expected. But the following hasn't failed me so far:

import inspect
src_file_path = inspect.getfile(lambda: None)

This is the closest thing to a Python analog to C's __FILE__.

The behavior of Python's __file__ is much different than C's __FILE__. The C version will give you the original path of the source file. This is useful in logging errors and knowing which source file has the bug.

Python's __file__ only gives you the name of the currently executing file, which may not be very useful in log output.

How do you debug PHP scripts?

I use Netbeans with XDebug. Check it out at its website for docs on how to configure it. http://php.netbeans.org/

fatal error LNK1169: one or more multiply defined symbols found in game programming

just add /FORCE as linker flag and you're all set.

for instance, if you're working on CMakeLists.txt. Then add following line:

SET(CMAKE_EXE_LINKER_FLAGS  "/FORCE")

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

maybe you have code like this before the jquery:

var $jq=jQuery.noConflict();
$jq('ul.menu').lavaLamp({
    fx: "backout", 
    speed: 700
});

and them was Conflict

you can change $ to (jQuery)

CentOS: Copy directory to another directory

As I understand, you want to recursively copy test directory into /home/server/ path...

This can be done as:

-cp -rf /home/server/folder/test/* /home/server/

Hope this helps

Regex Last occurrence?

Your negative lookahead solution would e.g. be this:

\\(?:.(?!\\))+$

See it here on Regexr

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

Get full path without filename from path that includes filename

Path.GetDirectoryName() returns the directory name, so for what you want (with the trailing reverse solidus character) you could call Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar.

History or log of commands executed in Git

If you are using CentOS or another Linux flavour then just do Ctrl+R at the prompt and type git.

If you keep hitting Ctrl+R this will do a reverse search through your history for commands that start with git

Magento addFieldToFilter: Two fields, match as OR, not AND

Thanks Anda, your post has been a great help!! However the OR sentence didnt' quite work for me and I was getting an error: getCollection() "invalid argument supplied for foreach".

So this is what I ended with (notice the attribute being specified 3 times instead of 2 in this case):

  $collection->addFieldToFilter('attribute', array(  
    array('attribute'=>'my_field1','eq'=>'my_value1'),            
    array('attribute'=>'my_field2','eq'=>'my_value2') ));

addFieldToFilter first requires a field and then condition -> link.

How can I configure Logback to log different levels for a logger to different destinations?

okay, here is my favorite xml way of doing it. I do this for the eclipse version so I can

  • click on stuff to take me to the log statements and
  • see info and below in black and warn/severe in red

and for some reason SO is not showing this all properly but most seems to be there...

<configuration scan="true" scanPeriod="30 seconds">

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">      
          <evaluator class="ch.qos.logback.classic.boolex.GEventEvaluator"> 
            <expression>
               e.level.toInt() &lt;= INFO.toInt()
            </expression>
          </evaluator>
          <OnMismatch>DENY</OnMismatch>
          <OnMatch>NEUTRAL</OnMatch>
        </filter>

        <encoder>
            <pattern>%date{ISO8601} %X{sessionid}-%X{user} %caller{1} %-4level: %message%n</pattern>
        </encoder>
    </appender>

    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> 
            <level>warn</level>
        </filter>

        <encoder>
            <pattern>%date{ISO8601} %X{sessionid}-%X{user} %caller{1} %-4level: %message%n</pattern>
        </encoder>
        <target>System.err</target>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="STDERR"/>
    </root>
</configuration>

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

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

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

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

Try adding an empty failure call, like this:

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

This will prevent the error to appear.

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

Python find elements in one list that are not in the other

Not sure why the above explanations are so complicated when you have native methods available:

main_list = list(set(list_2)-set(list_1))

Excel VBA Macro: User Defined Type Not Defined

Your error is caused by these:

Dim oTable As Table, oRow As Row,

These types, Table and Row are not variable types native to Excel. You can resolve this in one of two ways:

  1. Include a reference to the Microsoft Word object model. Do this from Tools | References, then add reference to MS Word. While not strictly necessary, you may like to fully qualify the objects like Dim oTable as Word.Table, oRow as Word.Row. This is called early-binding. enter image description here
  2. Alternatively, to use late-binding method, you must declare the objects as generic Object type: Dim oTable as Object, oRow as Object. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.

I have not tested your code but I suspect ActiveDocument won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:

Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long

Set wdApp = GetObject(,"Word.Application")

Application.ScreenUpdating = False

For Each oTable In wdApp.ActiveDocument.Tables

pandas: multiple conditions while indexing data frame - unexpected behavior

A little mathematical logic theory here:

"NOT a AND NOT b" is the same as "NOT (a OR b)", so:

"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".

So if you want exact opposite result, df1 and df2 should be as below:

df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]

How can I convert JSON to a HashMap using Gson?

I know this is a fairly old question, but I was searching for a solution to generically deserialize nested JSON to a Map<String, Object>, and found nothing.

The way my yaml deserializer works, it defaults JSON objects to Map<String, Object> when you don't specify a type, but gson doesn't seem to do this. Luckily you can accomplish it with a custom deserializer.

I used the following deserializer to naturally deserialize anything, defaulting JsonObjects to Map<String, Object> and JsonArrays to Object[]s, where all the children are similarly deserialized.

private static class NaturalDeserializer implements JsonDeserializer<Object> {
  public Object deserialize(JsonElement json, Type typeOfT, 
      JsonDeserializationContext context) {
    if(json.isJsonNull()) return null;
    else if(json.isJsonPrimitive()) return handlePrimitive(json.getAsJsonPrimitive());
    else if(json.isJsonArray()) return handleArray(json.getAsJsonArray(), context);
    else return handleObject(json.getAsJsonObject(), context);
  }
  private Object handlePrimitive(JsonPrimitive json) {
    if(json.isBoolean())
      return json.getAsBoolean();
    else if(json.isString())
      return json.getAsString();
    else {
      BigDecimal bigDec = json.getAsBigDecimal();
      // Find out if it is an int type
      try {
        bigDec.toBigIntegerExact();
        try { return bigDec.intValueExact(); }
        catch(ArithmeticException e) {}
        return bigDec.longValue();
      } catch(ArithmeticException e) {}
      // Just return it as a double
      return bigDec.doubleValue();
    }
  }
  private Object handleArray(JsonArray json, JsonDeserializationContext context) {
    Object[] array = new Object[json.size()];
    for(int i = 0; i < array.length; i++)
      array[i] = context.deserialize(json.get(i), Object.class);
    return array;
  }
  private Object handleObject(JsonObject json, JsonDeserializationContext context) {
    Map<String, Object> map = new HashMap<String, Object>();
    for(Map.Entry<String, JsonElement> entry : json.entrySet())
      map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class));
    return map;
  }
}

The messiness inside the handlePrimitive method is for making sure you only ever get a Double or an Integer or a Long, and probably could be better, or at least simplified if you're okay with getting BigDecimals, which I believe is the default.

You can register this adapter like:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();

And then call it like:

Object natural = gson.fromJson(source, Object.class);

I'm not sure why this is not the default behavior in gson, since it is in most other semi-structured serialization libraries...

AngularJS - difference between pristine/dirty and touched/untouched

AngularJS Developer Guide - CSS classes used by AngularJS

  • @property {boolean} $untouched True if control has not lost focus yet.
  • @property {boolean} $touched True if control has lost focus.
  • @property {boolean} $pristine True if user has not interacted with the control yet.
  • @property {boolean} $dirty True if user has already interacted with the control.

CMake link to external library

arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:

You could add an "imported" library target, instead of a link-directory. Something like:

# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )

And then link as if this library was built by your project:

TARGET_LINK_LIBRARIES(GLBall mylib)

Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.

I do not know if this will solve your problem with "updated versions of libs".

How to select all textareas and textboxes using jQuery?

Password boxes are also textboxes, so if you need them too:

$("input[type='text'], textarea, input[type='password']").css({width: "90%"});

and while file-input is a bit different, you may want to include them too (eg. for visual consistency):

$("input[type='text'], textarea, input[type='password'], input[type='file']").css({width: "90%"});

How do I add a simple onClick event handler to a canvas element?

Probably very late to the answer but I just read this while preparing for my 70-480 exam, and found this to work -

var elem = document.getElementById('myCanvas');
elem.onclick = function() { alert("hello world"); }

Notice the event as onclick instead of onClick.

JS Bin example.

Visual studio equivalent of java System.out

Try: Console.WriteLine (type out for a Visual Studio snippet)

Console.WriteLine(stuff);

Another way is to use System.Diagnostics.Debug.WriteLine:

System.Diagnostics.Debug.WriteLine(stuff);

Debug.WriteLine may suit better for Output window in IDE because it will be rendered for both Console and Windows applications. Whereas Console.WriteLine won't be rendered in Output window but only in the Console itself in case of Console Application type.

Another difference is that Debug.WriteLine will not print anything in Release configuration.

Input button target="_blank" isn't causing the link to load in a new window/tab

The formtarget attribute is only used for buttons with type="submit".

That is from this reference.

Here is an answer using JavaScript:

<input type="button" onClick="openNewTab()" value="facebook">

<script type="text/javascript">
    function openNewTab() {
        window.open("http://www.facebook.com/");
    }
</script>

How to fit a smooth curve to my data in R?

In ggplot2 you can do smooths in a number of ways, for example:

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "gam", formula = y ~ poly(x, 2)) 
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "loess", span = 0.3, se = FALSE) 

enter image description here enter image description here

Is there a stopwatch in Java?

Try this...

import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;

public class StopwatchTest {
     
    public static void main(String[] args) throws Exception {
        Stopwatch stopwatch = Stopwatch.createStarted();
        Thread.sleep(1000 * 60);
        stopwatch.stop(); // optional
        long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        System.out.println("Time in milliseconds "+millis);
        System.out.println("that took: " + stopwatch);
    }
}

Blurring an image via CSS?

This code is working for blur effect for all browsers.

filter: blur(10px);
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);

How to get CSS to select ID that begins with a string (not in Javascript)?

[id^=product]

^= indicates "starts with". Conversely, $= indicates "ends with".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

See the specs for full information.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

Check your .ssh config for heroku. Go to the .ssh folder and open the config file

cd ~/.ssh
subl config

The 'subl' is for Sublime Text, but you can use whatever editor you wish. Look for the line "IdentityFile" and make sure it has the non public key listed:

IdentityFile "/Users/ircmullaney/.ssh/my_ssh"

not

IdentityFile "/Users/ircmullaney/.ssh/my_ssh.pub"

That did it for me. I'm not sure why mine had the public version in the config file, but it did and it was throwing the error:

Permissions 0644 for '/Users/ircmullaney/.ssh/my_ssh.pub' are too open.

Vue.js getting an element within a component

The answers are not making it clear:

Use this.$refs.someName, but, in order to use it, you must add ref="someName" in the parent.

See demo below.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  mounted: function() {_x000D_
    var childSpanClassAttr = this.$refs.someName.getAttribute('class');_x000D_
    _x000D_
    console.log('<span> was declared with "class" attr -->', childSpanClassAttr);_x000D_
  }_x000D_
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  Parent._x000D_
  <span ref="someName" class="abc jkl xyz">Child Span</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$refs and v-for

Notice that when used in conjunction with v-for, the this.$refs.someName will be an array:

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    ages: [11, 22, 33]_x000D_
  },_x000D_
  mounted: function() {_x000D_
    console.log("<span> one's text....:", this.$refs.mySpan[0].innerText);_x000D_
    console.log("<span> two's text....:", this.$refs.mySpan[1].innerText);_x000D_
    console.log("<span> three's text..:", this.$refs.mySpan[2].innerText);_x000D_
  }_x000D_
})
_x000D_
span { display: inline-block; border: 1px solid red; }
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  Parent._x000D_
  <div v-for="age in ages">_x000D_
    <span ref="mySpan">Age is {{ age }}</span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using bootstrap with bower

assuming you have npm installed and bower installed globally

  1. navigate to your project
  2. bower init (this will generate the bower.json file in your directory)
  3. (then keep clicking yes)...
  4. to set the path where bootstrap will be installed:
    manually create a .bowerrc file next to the bower.json file and add the following to it:

    { "directory" : "public/components" }

  5. bower install bootstrap --save

Note: to install other components:

 bower search {component-name-here}

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

The following simple steps help me:

First, initialize the repository to work with Git, so that any file changes are tracked:

git init

Then, check that the remote repository that you want to associate with the alias origin exists, if not create it in git first.

$ git ls-remote https://github.com/repo-owner/repo-name.git/

If it exists, associate it with the remote "origin":

git remote add origin https://github.com:/repo-owner/repo-name.git

and check to which URL, the remote "origin" belongs to by using git remote -v:

$ git remote -v
origin  https://github.com:/repo-owner/repo-name.git (fetch)
origin  https://github.com:/repo-owner/repo-name.git (push)

Next, verify if your origin is properly aliased as follows:

$ cat ./.git/config
:
[remote "origin"]
        url = https://github.com:/repo-owner/repo-name.git
        fetch = +refs/heads/*:refs/remotes/origin/*
:

You need to see this section [remote "origin"]. You can consider to use GitHub Desktop available for both Windows and MacOS, which help me to automatically populate the missing section/s in ~./git/config file OR you can manually add it, not great, but hey it works!

[Optional]
You might also want to change the origin alias to make it more intuitive, especially if you are working with multiple origin:

git remote rename origin mynewalias

or even remove it:

git remote rm origin

Finally, on your first push, if you want master in that repository to be your default upstream. you may want to add the -u parameter

git add .
git commit -m 'First commit'
git push -u origin master

How to resolve this System.IO.FileNotFoundException

I've been mislead by this error more than once. After spending hours googling, updating nuget packages, version checking, then after sitting with a completely updated solution I re-realize a perfectly valid, simpler reason for the error.

If in a threaded enthronement (UI Dispatcher.Invoke for example), System.IO.FileNotFoundException is thrown if the thread manager dll (file) fails to return. So if your main UI thread A, calls the system thread manager dll B, and B calls your thread code C, but C throws for some unrelated reason (such as null Reference as in my case), then C does not return, B does not return, and A only blames B with FileNotFoundException for being lost...

Before going down the dll version path... Check closer to home and verify your thread code is not throwing.

Returning boolean if set is empty

If c is a set then you can check whether it's empty by doing: return not c.

If c is empty then not c will be True.

Otherwise, if c contains any elements not c will be False.

How do I set the maximum line length in PyCharm?

For PyCharm 2017

We can follow below: File >> Settings >> Editor >> Code Style.

Then provide values for Hard Wrap & Visual Guides for wrapping while typing, tick the checkbox.

NB: look at other tabs as well, viz. Python, HTML, JSON etc.

AngularJS - Attribute directive input value change

To watch out the runtime changes in value of a custom directive, use $observe method of attrs object, instead of putting $watch inside a custom directive. Here is the documentation for the same ... $observe docs

How to check if the docker engine and a docker container are running?

I ended up using

docker info

to check with a bash script if docker engine is running.

Why am I getting tree conflicts in Subversion?

What's happening here is the following: You create a new file on your trunk, then you merge it into your branch. In the merge commit this file will be created in your branch also.

When you merge your branch back into the trunk, SVN tries to do the same again: It sees that a file was created in your branch, and tries to create it in your trunk in the merge commit, but it already exists! This creates a tree conflict.

The way to avoid this, is to do a special merge, a reintegration. You can achieve this with the --reintegrate switch.

You can read about this in the documentation: http://svnbook.red-bean.com/en/1.7/svn.branchmerge.basicmerging.html#svn.branchemerge.basicmerging.reintegrate

When merging your branch back to the trunk, however, the underlying mathematics are quite different. Your feature branch is now a mishmash of both duplicated trunk changes and private branch changes, so there's no simple contiguous range of revisions to copy over. By specifying the --reintegrate option, you're asking Subversion to carefully replicate only those changes unique to your branch. (And in fact, it does this by comparing the latest trunk tree with the latest branch tree: the resulting difference is exactly your branch changes!)

After reintegrating a branch it is highly advisable to remove it, otherwise you will keep getting treeconflicts whenever you merge in the other direction: from the trunk to your branch. (For exactly the same reason as described before.)

There is a way around this too, but I never tried it. You can read it in this post: Subversion branch reintegration in v1.6

Typescript input onchange event.target.value

Here is a way with ES6 object destructuring, tested with TS 3.3.
This example is for a text input.

name: string = '';

private updateName({ target }: { target: HTMLInputElement }) {
    this.name = target.value;
}

open the file upload dialogue box onclick the image

you need to add a little hack to achieve this.

You can hide a file upload(input type=file) behind your button.

and onclick of your button you can trigger your file upload click.

It will open a file upload window on click of button

<button id="btnfile"> 
 <img src='".$cfet['productimage']."' width='50' height='40'>
</button> 
<div class="wrapper"> //set wrapper `display:hidden`
     <input type="file" id="uploadfile" /> 
</div>

and some javascript

$("#btnfile").click(function () {
    $("#uploadfile").click();
});

here is a fiddle for this example: http://jsfiddle.net/ravi441988/QmyHV/1/embedded/result/

How to get every first element in 2 dimensional list

use zip

columns = zip(*rows) #transpose rows to columns
print columns[0] #print the first column
#you can also do more with the columns
print columns[1] # or print the second column
columns.append([7,7,7]) #add a new column to the end
backToRows = zip(*columns) # now we are back to rows with a new column
print backToRows

you can also use numpy

a = numpy.array(a)
print a[:,0]

Edit: zip object is not subscriptable. It need to be converted to list to access as list:

column = list(zip(*row))

How to send POST request?

If you really want to handle with HTTP using Python, I highly recommend Requests: HTTP for Humans. The POST quickstart adapted to your question is:

>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Issue 12524: change httplib docs POST example - Python tracker

</title>
<link rel="shortcut i...
>>> 

using awk with column value conditions

This is more readable for me

awk '{if ($2 ~ /findtext/) print $3}' <infile>

Redirect output of mongo query to a csv file

Have a look at this

for outputing from mongo shell to file. There is no support for outputing csv from mongos shell. You would have to write the javascript yourself or use one of the many converters available. Google "convert json to csv" for example.

Moment.js - tomorrow, today and yesterday

From 2.10.5 moment supports specifying calendar output formats per invocation For a more detailed documentation check Moment - Calendar.

**Moment 2.10.5**
moment().calendar(null, {
  sameDay: '[Today]',
  nextDay: '[Tomorrow]',
  nextWeek: 'dddd',
  lastDay: '[Yesterday]',
  lastWeek: '[Last] dddd',
  sameElse: 'DD/MM/YYYY'
});

From 2.14.0 calendar can also take a callback to return values.

**Moment 2.14.0**
    moment().calendar(null, {
     sameDay: function (now) {
       if (this.isBefore(now)) {
         return '[Will Happen Today]';
       } else {
        return '[Happened Today]';
       }
       /* ... */
      }
    });

What is the difference between XML and XSD?

SIMPLE XML EXAMPLE:

<school>
  <firstname>John</firstname>
  <lastname>Smith</lastname>
</school>

XSD OF ABOVE XML(Explained):

<xs:element name="school">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

Here:

xs:element : Defines an element.

xs:sequence : Denotes child elements only appear in the order mentioned.

xs:complexType : Denotes it contains other elements.

xs:simpleType : Denotes they do not contain other elements.

type: string, decimal, integer, boolean, date, time,

  • In simple words, xsd is another way to represent and validate XML data with the specific type.
  • With the help of extra attributes, we can perform multiple operations.

  • Performing any task on xsd is simpler than xml.

How to get the file path from URI?

Here is the answer to the question here

Actually we have to get it from the sharable ContentProvider of Camera Application.

EDIT . Copying answer that worked for me

private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;

}

Redirecting a page using Javascript, like PHP's Header->Location

The PHP code is executed on the server, so your redirect is executed before the browser even sees the JavaScript.

You need to do the redirect in JavaScript too

$('.entry a:first').click(function()
{
    window.location.replace("http://www.google.com");
});

How to set JAVA_HOME environment variable on Mac OS X 10.9?

Literally all you have to do is:

echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile

and restart your shell.

If you have multiple JDK versions installed and you want it to be a specific one, you can use the -v flag to java_home like so:

echo export "JAVA_HOME=\$(/usr/libexec/java_home -v 1.7)" >> ~/.bash_profile

Make anchor link go some pixels above where it's linked to

Working only with css you can add a padding to the anchored element (as in a solution above) To avoid unnecessary whitespace you can add a negative margin of the same height:

#anchor {
    padding-top: 50px;
    margin-top: -50px;
}

I am not sure if this is the best solution in any case, but it works fine for me.

How to load URL in UIWebView in Swift?

UIWebView in Swift

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
        let url = URL (string: "url here")
        let requestObj = URLRequest(url: url!)
        webView.loadRequest(requestObj)
    // Do any additional setup after loading the view.
}

/////////////////////////////////////////////////////////////////////// if you want to use webkit

@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
    super.viewDidLoad()

    let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
    self.view.addSubview(webView)
    let url = URL(string: "your URL")
    webView.load(URLRequest(url: url!))`

Error:java: invalid source release: 8 in Intellij. What does it mean?

Check your pom.xml first (if you have one)
Check your module's JDK dependancy. Make sure that it is 1.8
To do this,go to Project Structure -> SDK's
Add the path to where you have stored 1.8 (jdk1.8.0_45.jdk in my case)
Apply the changes
Now, go to Project Structure ->Modules
Change the Module SDK to 1.8
Apply the changes

Voila! You're done

Mongoose: findOneAndUpdate doesn't return updated document

This is the updated code for findOneAndUpdate. It works.

db.collection.findOneAndUpdate(    
  { age: 17 },      
  { $set: { name: "Naomi" } },      
  {
     returnNewDocument: true
  }    
)

Setting a width and height on an A tag

It's not an exact duplicate (so far as I can find), but this is a common problem.

display:block is what you need. but you should read the spec to understand why.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

SWT by itself is pretty low-level, and it uses the platform's native widgets through JNI. It is not related to Swing and AWT at all. The Eclipse IDE and all Eclipse-based Rich Client Applications, like the Vuze BitTorrent client, are built using SWT. Also, if you are developing Eclipse plugins, you will typically use SWT.
I have been developing Eclipse-based applications and plugins for almost 5 years now, so I'm clearly biased. However, I also have extensive experience in working with SWT and the JFace UI toolkit, which is built on top of it. I have found JFace to be very rich and powerful; in some cases it might even be the main reason for choosing SWT. It enables you to whip up a working UI quite quickly, as long as it is IDE-like (with tables, trees, native controls, etc). Of course you can integrate your custom controls as well, but that takes some extra effort.

How to loop through all enum values in C#?

 Enum.GetValues(typeof(Foos))

How to stop VBA code running?

Add another button called "CancelButton" that sets a flag, and then check for that flag.

If you have long loops in the "stuff" then check for it there too and exit if it's set. Use DoEvents inside long loops to ensure that the UI works.

Bool Cancel
Private Sub CancelButton_OnClick()
    Cancel=True
End Sub
...
Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If Cancel Then Exit Sub
    DoAnotherStuff
    If Cancel Then Exit Sub
    AndFinallyDothis
End Sub

How to send email attachments?

Here's another:

import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate


def send_mail(send_from, send_to, subject, text, files=None,
              server="127.0.0.1"):
    assert isinstance(send_to, list)

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)


    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

It's much the same as the first example... But it should be easier to drop in.

How do I use Apache tomcat 7 built in Host Manager gui?

Host Manager is a web application inside of Tomcat that creates/removes Virtual Hosts within Tomcat.

A Virtual Host allows you to define multiple hostnames on a single server, so you can use the same server to handles requests to, for example, ren.myserver.com and stimpy.myserver.com.

Unfortunately documentation on the GUI side of the Host Manager doesn't appear to exist, but documentation on configuring the virtual hosts manually in context.xml is here:

http://tomcat.apache.org/tomcat-7.0-doc/virtual-hosting-howto.html.

The full explanation of the Host parameters you can find here:

http://tomcat.apache.org/tomcat-7.0-doc/config/host.html.

Adding a virtual host

Once you have access to the host-manager (see other answers on setting up the permissions, the GUI will let you add a (temporary - see edit at the end of this post) virtual host.

Tomcat Host Manager - Add Virtual Host Panel

At a minimum you need the Name and App Base fields defined. Tomcat will then create the following directories:

{CATALINA_HOME}\conf\Catalina\{Name}
{CATALINA_HOME}\{App Base}
  • App Base will be where web applications will be deployed to the virtual host. Can be relative or absolute.
  • Name is usually the fully-qualified domain name (e.g. ren.myserver.com)
  • Alias can be used to extend the Name also where two addresses should resolve to the same host (e.g. www.ren.myserver.com). Note that this needs to be reflected in DNS records.

The checkboxes are as follows:

  • Auto Deploy: Automatically redeploy applications placed into App Base. Dangerous for Production environments!
  • Deploy On Startup: Automatically boot up applications under App Base when Tomcat starts
  • Deploy XML: Determines whether to parse the application's /META-INF/context.xml
  • Unpack WARs: Unpack WAR files placed or uploaded to the App Base, as opposed to running them directly from the WAR.
  • Tomcat 8 Copy XML: Copy an application's META-INF/context.xml to the App Base/XML Base on deployment, and use that exclusively, regardless of whether the application is updated. Irrelevant if Deploy XML is false.
  • Manager App: Add the manager application to the Virtual Host (Useful for controlling the applications you might have underneath ren.myserver.com)

Update: After playing around with this same process on Tomcat8, the behaviour I'm seeing is that adding a virtual host via the GUI isn't persistent - it doesn't get written to server.xml, even on shutdown. Therefore (unless I'm doing something terribly wrong), you can create it in the GUI, but you'll need to edit server.xml anyway, as per the first link above, to make it stick.

How to strip HTML tags from a string in SQL Server?

There is a UDF that will do that described here:

User Defined Function to Strip HTML

CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS
BEGIN
    DECLARE @Start INT
    DECLARE @End INT
    DECLARE @Length INT
    SET @Start = CHARINDEX('<',@HTMLText)
    SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
    SET @Length = (@End - @Start) + 1
    WHILE @Start > 0 AND @End > 0 AND @Length > 0
    BEGIN
        SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
        SET @Start = CHARINDEX('<',@HTMLText)
        SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
        SET @Length = (@End - @Start) + 1
    END
    RETURN LTRIM(RTRIM(@HTMLText))
END
GO

Edit: note this is for SQL Server 2005, but if you change the keyword MAX to something like 4000, it will work in SQL Server 2000 as well.

Pass path with spaces as parameter to bat file

"%~1" will work most of the time. However there are a few things you need to note for this:

  1. It's not supported in Windows NT 4.0. You need Windows 2000 or later. (If you are coding a script compatible with old OS, beware.)
  2. It does not make parameters secure and sanitized. My observation is that there is no way to properly sanitize the command line arguments in CMD scripts.

To demonstrate second point, let me give an example:

REM example.cmd
ECHO %~1

Run with example.cmd dummy^&DIR . The ampersand is escaped here ( ^& ) to prevent shell from interpreting as a command delimiter, so that it becomes part of the argument passed to the script. The DIR is interpreted as a command inside the sub-shell running the script, where it shouldn't.

Quoting it might work some time, but still insecure:

REM example2.cmd
SETLOCAL EnableExtensions EnableDelayedExpansion
SET "arg1=%~1"
ECHO "%~1"
ECHO !arg1:"=!

example2.cmd foo^"^&DIR^&^"bar will break it. DIR command will be run two times, one right after SET and the other right after the first ECHO. You see that the "%~1" you think is quoted well gets unquoted by the argument itself.

So, no way to make parsing arguments secure.

(EDIT: EnableDelayedExpansion doesn't work in Windows NT 4 either. Thanks to the info here: http://www.robvanderwoude.com/local.php)

How to move or copy files listed by 'find' command in unix?

Adding to Eric Jablow's answer, here is a possible solution (it worked for me - linux mint 14 /nadia)

find /path/to/search/ -type f -name "glob-to-find-files" | xargs cp -t /target/path/

You can refer to "How can I use xargs to copy files that have spaces and quotes in their names?" as well.

Correct way to load a Nib for a UIView subclass

Follow the following steps

  1. Create a class named MyView .h/.m of type UIView.
  2. Create a xib of same name MyView.xib.
  3. Now change the File Owner class to UIViewController from NSObject in xib. See the image below enter image description here
  4. Connect the File Owner View to your View. See the image below enter image description here

  5. Change the class of your View to MyView. Same as 3.

  6. Place controls create IBOutlets.

Here is the code to load the View:

UIViewController *controller=[[UIViewController alloc] initWithNibName:@"MyView" bundle:nil];
MyView* view=(MyView*)controller.view;
[self.view addSubview:myview];

Hope it helps.

Clarification:

UIViewController is used to load your xib and the View which the UIViewController has is actually MyView which you have assigned in the MyView xib..

Demo I have made a demo grab here

How do I run a terminal inside of Vim?

Updated answer (11 years later...):

  • I would recommend using tmux instead of screen as suggested in the original answer below, if you choose to use that solution.
  • Vim 8.1 now has a built in terminal that can be opened with the :term command. This provides much more complete integration with the rest of the Vim features.

I would definitely recommend screen for something like this. Vim is a text editor, not a shell.

I would use Ctrl+AS to split the current window horizontally, or in Ubuntu's screen and other patched versions, you can use Ctrl+A|(pipe) to split vertically. Then use Ctrl+ATab (or equivalently on some systems, Ctrl+ACtrl+I which may be easier to type) to switch between the windows. There are other commands to change the size and arrangement of the windows.

Or a less advanced use of screen is just to open multiple full-screen windows and toggle between them. This is what I normally do, I only use the split screen feature occasionally.

The GNU Screen Survival Guide question has a number of good tips if you're unfamiliar with its use.

How can I convert JSON to CSV?

import json,csv
t=''
t=(type('a'))
json_data = []
data = None
write_header = True
item_keys = []
try:
with open('kk.json') as json_file:
    json_data = json_file.read()

    data = json.loads(json_data)
except Exception as e:
    print( e)

with open('bar.csv', 'at') as csv_file:
    writer = csv.writer(csv_file)#, quoting=csv.QUOTE_MINIMAL)
    for item in data:
        item_values = []
        for key in item:
            if write_header:
                item_keys.append(key)
            value = item.get(key, '')
            if (type(value)==t):
                item_values.append(value.encode('utf-8'))
            else:
                item_values.append(value)
        if write_header:
            writer.writerow(item_keys)
            write_header = False
        writer.writerow(item_values)

Convert string to integer type in Go?

Converting Simple strings

The easiest way is to use the strconv.Atoi() function.

Note that there are many other ways. For example fmt.Sscan() and strconv.ParseInt() which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation of strconv.Atoi():

Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

Here's an example using the mentioned functions (try it on the Go Playground):

flag.Parse()
s := flag.Arg(0)

if i, err := strconv.Atoi(s); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

if i, err := strconv.ParseInt(s, 10, 64); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

var i int
if _, err := fmt.Sscan(s, &i); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

Output (if called with argument "123"):

i=123, type: int
i=123, type: int64
i=123, type: int

Parsing Custom strings

There is also a handy fmt.Sscanf() which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the input string.

This is great for parsing custom strings holding a number. For example if your input is provided in a form of "id:00123" where you have a prefix "id:" and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:

s := "id:00123"

var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
    fmt.Println(i) // Outputs 123
}

Running Command Line in Java

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

Convert Mercurial project to Git

If you want to import your existing mercurial repository into a 'GitHub' repository, you can now simply use GitHub Importer available here [Login required]. No more messing around with fast-export etc. (although its a very good tool)

You will get all your commits, branches and tags intact. One more cool thing is that you can change the author's email-id as well. Check out below screenshots:

enter image description here

enter image description here

How can I determine if a date is between two dates in Java?

Here's a couple ways to do this using the Joda-Time 2.3 library.

One way is to use the simple isBefore and isAfter methods on DateTime instances. By the way, DateTime in Joda-Time is similar in concept to a java.util.Date (a moment in time on the timeline of the Universe) but includes a time zone.

Another way is to build an Interval in Joda-Time. The contains method tests if a given DateTime occurs within the span of time covered by the Interval. The beginning of the Interval is inclusive, but the endpoint is exclusive. This approach is known as "Half-Open", symbolically [).

See both ways in the following code example.

Convert the java.util.Date instances to Joda-Time DateTime instances. Simply pass the Date instance to constructor of DateTime. In practice you should also pass a specific DateTimeZone object rather than rely on JVM’s default time zone.

DateTime dateTime1 = new DateTime( new java.util.Date() ).minusWeeks( 1 );
DateTime dateTime2 = new DateTime( new java.util.Date() );
DateTime dateTime3 = new DateTime( new java.util.Date() ).plusWeeks( 1 );

Compare by testing for before/after…

boolean is1After2 = dateTime1.isAfter( dateTime2 );
boolean is2Before3 = dateTime2.isBefore( dateTime3 );

boolean is2Between1And3 = ( ( dateTime2.isAfter( dateTime1 ) ) && ( dateTime2.isBefore( dateTime3 ) ) );

Using the Interval approach instead of isAfter/isBefore…

Interval interval = new Interval( dateTime1, dateTime3 );
boolean intervalContainsDateTime2 = interval.contains( dateTime2 );

Dump to console…

System.out.println( "DateTimes: " + dateTime1 + " " + dateTime1 + " " + dateTime1 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
System.out.println( "is2Between1And3 " + is2Between1And3 );
System.out.println( "intervalContainsDateTime2 " + intervalContainsDateTime2 );

When run…

DateTimes: 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00
is1After2 false
is2Before3 true
is2Between1And3 true
intervalContainsDateTime2 true

HTML5 Form Input Pattern Currency Format

The best we could come up with is this:

^\\$?(([1-9](\\d*|\\d{0,2}(,\\d{3})*))|0)(\\.\\d{1,2})?$

I realize it might seem too much, but as far as I can test it matches anything that a human eye would accept as valid currency value and weeds out everything else.

It matches these:

1 => true
1.00 => true
$1 => true
$1000 => true
0.1 => true
1,000.00 => true
$1,000,000 => true
5678 => true

And weeds out these:

1.001 => false
02.0 => false
22,42 => false
001 => false
192.168.1.2 => false
, => false
.55 => false
2000,000 => false

How to change the CHARACTER SET (and COLLATION) throughout a database?

Beware that in Mysql, the utf8 character set is only a subset of the real UTF8 character set. In order to save one byte of storage, the Mysql team decided to store only three bytes of a UTF8 characters instead of the full four-bytes. That means that some east asian language and emoji aren't fully supported. To make sure you can store all UTF8 characters, use the utf8mb4 data type, and utf8mb4_bin or utf8mb4_general_ci in Mysql.

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

Extension exists but uuid_generate_v4 fails

Looks like the extension is not installed in the particular database you require it.

You should connect to this particular database with

 \CONNECT my_database

Then install the extension in this database

 CREATE EXTENSION "uuid-ossp";

CSS How to set div height 100% minus nPx

This doesn't exactly answer the question as posed, but it does create the same visual effect that you are trying to achieve.

<style>

body {
  border:0;
  padding:0;
  margin:0;
  padding-top:60px;
}

#header {
  position:absolute;
  top:0;
  height:60px;
  width:100%;
}

#wrapper {
  height:100%;
  width:100%;
}
</style>

How to show matplotlib plots in python

You have to use show() methode when you done all initialisations in your code in order to see the complet version of plot:

import matplotlib.pyplot as plt

plt.plot(x, y)
................
................
plot.show()

Environment variables for java installation

For Windows:

  • Right click on 'My Computers' and open 'Properties'.
  • In Windows Vista or Windows 7, go to "Advanced System Settings". Else go to next step.
  • Go to 'Advanced Tab' and click on Environment Variables button.
  • Select 'Path' under the list of 'System Variables', and press Edit and add C:\Program Files\java\jdk\bin after a semicolon.
  • Now click on 'new' button under system variables and enter 'JAVA_HOME' as variable name and path to jdk home directory (ex. 'C:\Program Files\Java\jdk1.6.0_24' if you are installing java version 6. Directory name may change with diff. java versions) as variable_value.

QByteArray to QString

you can use QString::fromAscii()

QByteArray data = entity->getData();
QString s_data = QString::fromAscii(data.data());

with data() returning a char*

for QT5, you should use fromCString() instead, as fromAscii() is deprecated, see https://bugreports.qt-project.org/browse/QTBUG-21872 https://bugreports.qt.io/browse/QTBUG-21872

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Disable keyboard on EditText

editText.setShowSoftInputOnFocus(false);

How can you debug a CORS request with cURL?

Here's how you can debug CORS requests using curl.

Sending a regular CORS request using cUrl:

curl -H "Origin: http://example.com" --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

The -H "Origin: http://example.com" flag is the third party domain making the request. Substitute in whatever your domain is.

The --verbose flag prints out the entire response so you can see the request and response headers.

The url I'm using above is a sample request to a Google API that supports CORS, but you can substitute in whatever url you are testing.

The response should include the Access-Control-Allow-Origin header.

Sending a preflight request using cUrl:

curl -H "Origin: http://example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

This looks similar to the regular CORS request with a few additions:

The -H flags send additional preflight request headers to the server

The -X OPTIONS flag indicates that this is an HTTP OPTIONS request.

If the preflight request is successful, the response should include the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers response headers. If the preflight request was not successful, these headers shouldn't appear, or the HTTP response won't be 200.

You can also specify additional headers, such as User-Agent, by using the -H flag.

How to get the onclick calling object?

http://docs.jquery.com/Events/jQuery.Event

Try with event.target

Contains the DOM element that issued the event. This can be the element that registered for the event or a child of it.

Enable CORS in Web API 2

I didn't need to install any package. Just a simple change in your WebAPI project's web.config is working great:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

Credit goes to: Using CORS in ASP.NET WebAPI Without Being a Rocket Scientist

MySQL Event Scheduler on a specific time everyday

My use case is similar, except that I want a log cleanup event to run at 2am every night. As I said in the comment above, the DAY_HOUR doesn't work for me. In my case I don't really mind potentially missing the first day (and, given it is to run at 2am then 2am tomorrow is almost always the next 2am) so I use:

CREATE EVENT applog_clean_event
ON SCHEDULE 
    EVERY 1 DAY
    STARTS str_to_date( date_format(now(), '%Y%m%d 0200'), '%Y%m%d %H%i' ) + INTERVAL 1 DAY
COMMENT 'Test'
DO 

How to access the value of a promise?

There are some good answer above and here is the ES6 Arrow function version

var something = async() => {
   let result = await functionThatReturnsPromiseA();
   return result + 1;
}

2D arrays in Python

Depending what you're doing, you may not really have a 2-D array.

80% of the time you have simple list of "row-like objects", which might be proper sequences.

myArray = [ ('pi',3.14159,'r',2), ('e',2.71828,'theta',.5) ]

myArray[0][1] == 3.14159
myArray[1][1] == 2.71828

More often, they're instances of a class or a dictionary or a set or something more interesting that you didn't have in your previous languages.

myArray = [ {'pi':3.1415925,'r':2}, {'e':2.71828,'theta':.5} ]

20% of the time you have a dictionary, keyed by a pair

myArray = { (2009,'aug'):(some,tuple,of,values), (2009,'sep'):(some,other,tuple) }

Rarely, will you actually need a matrix.

You have a large, large number of collection classes in Python. Odds are good that you have something more interesting than a matrix.

c++ bool question

Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values

When do I need to use AtomicBoolean in Java?

Excerpt from the package description

Package java.util.concurrent.atomic description: A small toolkit of classes that support lock-free thread-safe programming on single variables.[...]

The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors.[...]

Instances of classes AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference each provide access and updates to a single variable of the corresponding type.[...]

The memory effects for accesses and updates of atomics generally follow the rules for volatiles:

  • get has the memory effects of reading a volatile variable.
  • set has the memory effects of writing (assigning) a volatile variable.
  • weakCompareAndSet atomically reads and conditionally writes a variable, is ordered with respect to other memory operations on that variable, but otherwise acts as an ordinary non-volatile memory operation.
  • compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.

T-SQL to list all the user mappings with database roles/permissions for a Login

Is this the kind of thing you want? You might want to extend it to get more info out of the sys tables.

use master

DECLARE @name VARCHAR(50) -- database name 

DECLARE db_cursor CURSOR FOR 
select name from sys.databases

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @name  

WHILE @@FETCH_STATUS = 0  
BEGIN  
       print @name
      exec('USE ' +  @name + '; select rp.name, mp.name from sys.database_role_members drm
            join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
            join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)')
       FETCH NEXT FROM db_cursor INTO @name  
END  

CLOSE db_cursor  
DEALLOCATE db_cursor

Android: long click on a button -> perform actions

I've done it before, I just used:

down.setOnLongClickListener(new OnLongClickListener() { 
        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            return true;
        }
    });

Per documentation:

public void setOnLongClickListener (View.OnLongClickListener l)

Since: API Level 1 Register a callback to be invoked when this view is clicked and held. If this view is not long clickable, it becomes long clickable.

Notice that it requires to return a boolean, this should work.

Match everything except for specified strings

Depends on the language, but there are generally negative-assertions you can put in like so:

(?!red|green|blue)

(Thanks for the syntax fix, the above is valid Java and Perl, YMMV)

Create a function with optional call variables

Not sure I understand the question correctly.

From what I gather, you want to be able to assign a value to Domain if it is null and also what to check if $args2 is supplied and according to the value, execute a certain code?

I changed the code to reassemble the assumptions made above.

Function DoStuff($computername, $arg2, $domain)
{
    if($domain -ne $null)
    {
        $domain = "Domain1"
    }

    if($arg2 -eq $null)
    {
    }
    else
    {
    }
}

DoStuff -computername "Test" -arg2 "" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Test"  -domain ""
DoStuff -computername "Test" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Domain2"

Did that help?

React Native version mismatch

For others with the same problem on iOS with CocoaPods:

I tried all of the solutions above, without luck. I have some packages with native dependencies in my project, and some of those needed pod modules being installed. The problem was that React was specified in my Podfile, but the React pod didn't automatically get upgraded by using react-native-git-upgrade.

The fix is to upgrade all installed pods, by running cd ios && pod install.

How to post data to specific URL using WebClient in C#

Using WebClient.UploadString or WebClient.UploadData you can POST data to the server easily. I’ll show an example using UploadData, since UploadString is used in the same manner as DownloadString.

byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
                System.Text.Encoding.ASCII.GetBytes("field1=value1&amp;field2=value2") );
 
string sret = System.Text.Encoding.ASCII.GetString(bret);

More: http://www.daveamenta.com/2008-05/c-webclient-usage/

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

How can I see the current value of my $PATH variable on OS X?

You need to use the command echo $PATH to display the PATH variable or you can just execute set or env to display all of your environment variables.

By typing $PATH you tried to run your PATH variable contents as a command name.

Bash displayed the contents of your path any way. Based on your output the following directories will be searched in the following order:

/usr/local/share/npm/bin
/Library/Frameworks/Python.framework/Versions/2.7/bin
/usr/local/bin
/usr/local/sbin
~/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/opt/X11/bin
/usr/local/git/bin

To me this list appears to be complete.

Which maven dependencies to include for spring 3.0?

Since this questions seems to still get quite a lot of views, it might be useful to note that for Spring 4+ it's easiest to start using Spring Boot and the Spring Boot starter POMs.

Using Spring Boot there's less dependencies to manage (and thus fewer conflicts), and setting up a working, well integrated Spring Context is a whole lot easier. I highly recommend it.

git replace local version with remote version

My understanding is that, for example, you wrongly saved a file you had updated for testing purposes only. Then, when you run "git status" the file appears as "Modified" and you say some bad words. You just want the old version back and continue to work normally.

In that scenario you can just run the following command:

git checkout -- path/filename

Force index use in Oracle

You can use optimizer hints

select /*+ INDEX(table_name index_name) */ from table etc...

More on using optimizer hints: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/hintsref.htm

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

in my case it was the path lenght (incl. file name).

..\..\..\..\..\..\..\SWX\Binary\VS2008\Output\Win32\Debug\boost_unit_test_framework-vc90-mt-gd-1_57.lib;

as for the release the path was (this has worked correctly):

..\..\..\..\..\..\..\SWX\Binary\VS2008\Output\Win32\Release\boost_unit_test_framework-vc90-mt-1_57.lib;

==> one char shorter.

  1. i have also verified this by renaming the lib file (using shorter name) and changing this in the

Linker -> input -> additoinal dependencies

  1. i have also verified this by adding absolut path instead of relative path as all those ".." has extended the path string, too. this has also worked.

so the problem for me was the total size of the path + filename string was too long!

Check if a variable is between two numbers with Java

You can use this simply:

I'm using this function to check if the input int number is between 20 and 30

    static boolean isValidInput(int input) {
    return (input >= 20 && input <= 30);
}

Calling JavaScript Function From CodeBehind

Calling a JavaScript function from code behind

Step 1 Add your Javascript code

<script type="text/javascript" language="javascript">
    function Func() {
        alert("hello!")
    }
</script>

Step 2 Add 1 Script Manager in your webForm and Add 1 button too

Step 3 Add this code in your button click event

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "Func()", true);

How to get the root dir of the Symfony2 application?

Since Symfony 3.3 you can use binding, like

services:
_defaults:
    autowire: true      
    autoconfigure: true
    bind:
        $kernelProjectDir: '%kernel.project_dir%'

After that you can use parameter $kernelProjectDir in any controller OR service. Just like

class SomeControllerOrService
{
    public function someAction(...., $kernelProjectDir)
    {
          .....

List of tables, db schema, dump etc using the Python sqlite3 API

If someone wants to do the same thing with Pandas

import pandas as pd
import sqlite3
conn = sqlite3.connect("db.sqlite3")
table = pd.read_sql_query("SELECT name FROM sqlite_master WHERE type='table'", conn)
print(table)

optional parameters in SQL Server stored proc?

2014 and above at least you can set a default and it will take that and NOT error when you do not pass that parameter. Partial Example: the 3rd parameter is added as optional. exec of the actual procedure with only the first two parameters worked fine

exec getlist 47,1,0

create procedure getlist
   @convId int,
   @SortOrder int,
   @contestantsOnly bit = 0
as

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

this is a sample case, which will make sense I believe!

node('master'){
    stage('stage1'){
    def commit = sh (returnStdout: true, script: '''echo hi
    echo bye | grep -o "e"
    date
    echo lol''').split()


    echo "${commit[-1]} "

    }
}

How to return a file using Web API?

Better to return HttpResponseMessage with StreamContent inside of it.

Here is example:

public HttpResponseMessage GetFile(string id)
{
    if (String.IsNullOrEmpty(id))
        return Request.CreateResponse(HttpStatusCode.BadRequest);

    string fileName;
    string localFilePath;
    int fileSize;

    localFilePath = getFileFromID(id, out fileName, out fileSize);

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

    return response;
}

UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:

  1. Disable USB debugging

  2. Disable Developer mode

  3. Unplug the device from the USB cable

  4. Re-enable Developer mode

  5. Re-enable USB debugging

  6. Reconnect the USB cable to your device

It is important you do it in this order as it didn't work until it was done in this order.

How to set cookies in laravel 5 independently inside controller

Here is a sample code with explanation.

 //Create a response instance
 $response = new Illuminate\Http\Response('Hello World');

 //Call the withCookie() method with the response method
 $response->withCookie(cookie('name', 'value', $minutes));

 //return the response
 return $response;

Cookie can be set forever by using the forever method as shown in the below code.

$response->withCookie(cookie()->forever('name', 'value'));

Retrieving a Cookie

//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');

Comparing two dictionaries and checking how many (key, value) pairs are equal

What you want to do is simply x==y

What you do is not a good idea, because the items in a dictionary are not supposed to have any order. You might be comparing [('a',1),('b',1)] with [('b',1), ('a',1)] (same dictionaries, different order).

For example, see this:

>>> x = dict(a=2, b=2,c=3, d=4)
>>> x
{'a': 2, 'c': 3, 'b': 2, 'd': 4}
>>> y = dict(b=2,c=3, d=4)
>>> y
{'c': 3, 'b': 2, 'd': 4}
>>> zip(x.iteritems(), y.iteritems())
[(('a', 2), ('c', 3)), (('c', 3), ('b', 2)), (('b', 2), ('d', 4))]

The difference is only one item, but your algorithm will see that all items are different

How to detect duplicate values in PHP array?

You could try turning that array into a associative array with the fruits as keys and the number of occurrences as values. Bit long-winded, but it looks like:

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
   'pear', 'kiwi', 'kiwi', 'kiwi');
$new_array = array();
foreach ($array as $key => $value) {
    if(isset($new_array[$value]))
        $new_array[$value] += 1;
    else
        $new_array[$value] = 1;
}
foreach ($new_array as $fruit => $n) {
    echo $fruit;
    if($n > 1)
        echo "($n)";
    echo "<br />";
}

Replacing NULL and empty string within Select statement

Sounds like you want a view instead of altering actual table data.

Coalesce(NullIf(rtrim(Address.Country),''),'United States')

This will force your column to be null if it is actually an empty string (or blank string) and then the coalesce will have a null to work with.

Accessing value inside nested dictionaries

The answer was given already by either Sivasubramaniam Arunachalam or ch3ka.

I am just adding a performances view of the answer.

dicttest={}
dicttest['ligne1']={'ligne1.1':'test','ligne1.2':'test8'}
%timeit dicttest['ligne1']['ligne1.1']
%timeit dicttest.get('ligne1').get('ligne1.1')

gives us :

112 ns ± 29.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

235 ns ± 9.82 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

How to make the overflow CSS property work with hidden as value

I did not get it. I had a similar problem but in my nav bar.

What I was doing is I kept my navBar code in this way: nav>div.navlinks>ul>li*3>a

In order to put hover effects on a I positioned a to relative and designed a::before and a::after then i put a gray background on before and after elements and kept hover effects in such way that as one hovers on <a> they will pop from outside a to fill <a>.

The problem is that the overflow hidden is not working on <a>.

What i discovered is if i removed <li> and simply put <a> without <ul> and <li> then it worked.

What may be the problem?

Strangest language feature

NSIS (the Nullsoft Scriptable Install System) has the StrCmp instruction:

StrCmp str1 str2 jump_if_equal [jump_if_not_equal]

Compares (case insensitively) str1 to str2. If str1 and str2 are equal, Gotos jump_if_equal, otherwise Gotos jump_if_not_equal.

StrCmp $0 "a string" 0 +3
 DetailPrint '$$0 == "a string"'
 Goto +2
 DetailPrint '$$0 != "a string"'

The icing on the cake: jump_if_equal and jump_if_not_equal can be negative, too. But I guess you already figured that out from the + symbol in front of positive numbers. I don't remember whether it's mandatory, or just a horrible convention.

This basically combines the worst of BASIC and the worst of Assembler.

Java math function to convert positive int to negative and negative to positive?

original *= -1;

Simple line of code, original is any int you want it to be.

Is there a way to programmatically minimize a window

in c#.net

this.WindowState = FormWindowState.Minimized

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

How to change the height of a div dynamically based on another div using css?

In this piece of code the height of left panel will gets adjusted to the height of right panel dynamically...

function resizeDiv() {
var rh=$('.pright').height()+'px'.toString();
$('.pleft').css('height',rh);
}

You can try this here http://jsfiddle.net/SriharshaCR/7q585k1x/9/embedded/result/

Properties file with a list as the value for an individual key

If this is for some configuration file processing, consider using Apache configuration. https://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/index.html?org/apache/commons/configuration/PropertiesConfiguration.html It has way to multiple values to single key- The format is bit different though

key=value1,value2,valu3 gives three values against same key.

How to draw an empty plot?

Adam, following your comment above ("I wanted the empty plot to serve as filler in a multiplot (mfrow) plot."), what you actually want is the mfg option

    par(mfg=c(row,column))

- which controls where you want to put the next plot. For instance, to put a plot in the middle of a 3x3 multiplot, do

    par(mfrow=c(3,3))
    par(mfg=c(2,2))
    plot(rnorm(10))

What does the exclamation mark do before the function?

JavaScript syntax 101. Here is a function declaration:

function foo() {}

Note that there's no semicolon: this is just a function declaration. You would need an invocation, foo(), to actually run the function.

Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. It is now a function expression.

The ! alone doesn't invoke the function, of course, but we can now put () at the end: !function foo() {}() which has higher precedence than ! and instantly calls the function.

So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:

(function(){})();

Lastly, ! makes the expression return true. This is because by default all immediately invoked function expressions (IIFE) return undefined, which leaves us with !undefined which is true. Not particularly useful.

SyntaxError: Unexpected token o in JSON at position 1

Give a try catch like this, this will parse it if its stringified or else will take the default value

let example;
   try {
   example  = JSON.parse(data)
  } catch(e) {
    example = data
  }

Extract first item of each sublist

Python includes a function called itemgetter to return the item at a specific index in a list:

from operator import itemgetter

Pass the itemgetter() function the index of the item you want to retrieve. To retrieve the first item, you would use itemgetter(0). The important thing to understand is that itemgetter(0) itself returns a function. If you pass a list to that function, you get the specific item:

itemgetter(0)([10, 20, 30]) # Returns 10

This is useful when you combine it with map(), which takes a function as its first argument, and a list (or any other iterable) as the second argument. It returns the result of calling the function on each object in the iterable:

my_list = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
list(map(itemgetter(0), my_list)) # Returns ['a', 1, 'x']

Note that map() returns a generator, so the result is passed to list() to get an actual list. In summary, your task could be done like this:

lst2.append(list(map(itemgetter(0), lst)))

This is an alternative method to using a list comprehension, and which method to choose highly depends on context, readability, and preference.

More info: https://docs.python.org/3/library/operator.html#operator.itemgetter

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

for me , using export PYTHONIOENCODING=UTF-8 before executing python command worked .

Intersect Two Lists in C#

public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
    return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
                .Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}

Can I write into the console in a unit test? If yes, why doesn't the console window open?

NOTE: The original answer below should work for any version of Visual Studio up through Visual Studio 2012. Visual Studio 2013 does not appear to have a Test Results window any more. Instead, if you need test-specific output you can use @Stretch's suggestion of Trace.Write() to write output to the Output window.


The Console.Write method does not write to the "console" -- it writes to whatever is hooked up to the standard output handle for the running process. Similarly, Console.Read reads input from whatever is hooked up to the standard input.

When you run a unit test through Visual Studio 2010, standard output is redirected by the test harness and stored as part of the test output. You can see this by right-clicking the Test Results window and adding the column named "Output (StdOut)" to the display. This will show anything that was written to standard output.

You could manually open a console window, using P/Invoke as sinni800 says. From reading the AllocConsole documentation, it appears that the function will reset stdin and stdout handles to point to the new console window. (I'm not 100% sure about that; it seems kind of wrong to me if I've already redirected stdout for Windows to steal it from me, but I haven't tried.)

In general, though, I think it's a bad idea; if all you want to use the console for is to dump more information about your unit test, the output is there for you. Keep using Console.WriteLine the way you are, and check the output results in the Test Results window when it's done.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I wasn't completely happy by the --allow-file-access-from-files solution, because I'm using Chrome as my primary browser, and wasn't really happy with this breach I was opening.

Now I'm using Canary ( the chrome beta version ) for my development with the flag on. And the mere Chrome version for my real blogging : the two browser don't share the flag !

Add colorbar to existing axis

This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)

im = ax.imshow(data, cmap='bone')

fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

Image with proper colorbar in size

javascript filter array multiple conditions

If you want to put multiple conditions in filter, you can use && and || operator.

var product= Object.values(arr_products).filter(x => x.Status==status && x.email==user)

Redirect pages in JSP?

Just define the target page in the action attribute of the <form> containing the submit button.

So, in page1.jsp:

<form action="page2.jsp">
    <input type="submit">
</form>

Unrelated to the problem, a JSP is not the best place to do business stuff, if you need to do any. Consider learning servlets.

Pycharm/Python OpenCV and CV2 install error

python3.6 -m pip install opencv-python

will install cv2 in python3.6 branch

Can't push to the heroku

Make sure you have package.json inside root of your project. Happy coding :)

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

How to check if a variable is empty in python?

Yes, bool. It's not exactly the same -- '0' is True, but None, False, [], 0, 0.0, and "" are all False.

bool is used implicitly when you evaluate an object in a condition like an if or while statement, conditional expression, or with a boolean operator.

If you wanted to handle strings containing numbers as PHP does, you could do something like:

def empty(value):
    try:
        value = float(value)
    except ValueError:
        pass
    return bool(value)

sort csv by column

import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)

or use lambda

sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)

Random number c++ in some range

int random(int min, int max) //range : [min, max]
{
   static bool first = true;
   if (first) 
   {  
      srand( time(NULL) ); //seeding for the first time only!
      first = false;
   }
   return min + rand() % (( max + 1 ) - min);
}

how to initialize a char array?

memset(msg, 0, 65546)

How to refer to Excel objects in Access VBA?

First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.

After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:

Dim xlApp as Excel.Application

Let's say you added an Excel Workbook Object in your Form and named it xLObject.

Here is how you Access a Sheet of this Object and change a Range

Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"

(I copied the above from my answer to this question)

Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)

How to create folder with PHP code?

... You can then use copy() to duplicate a PHP file, although this sounds incredibly inefficient.

Writing unit tests in Python: How do I start?

nosetests is brilliant solution for unit-testing in python. It supports both unittest based testcases and doctests, and gets you started with it with just simple config file.

Using module 'subprocess' with timeout

if you are using python 2, give it a try

import subprocess32

try:
    output = subprocess32.check_output(command, shell=True, timeout=3)
except subprocess32.TimeoutExpired as e:
    print e

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

There are several decisions to make:

  1. The first about resource path:

    • Model the image as a resource on its own:

      • Nested in user (/user/:id/image): the relationship between the user and the image is made implicitly

      • In the root path (/image):

        • The client is held responsible for establishing the relationship between the image and the user, or;

        • If a security context is being provided with the POST request used to create an image, the server can implicitly establish a relationship between the authenticated user and the image.

    • Embed the image as part of the user

  2. The second decision is about how to represent the image resource:

    • As Base 64 encoded JSON payload
    • As a multipart payload

This would be my decision track:

  • I usually favor design over performance unless there is a strong case for it. It makes the system more maintainable and can be more easily understood by integrators.
  • So my first thought is to go for a Base64 representation of the image resource because it lets you keep everything JSON. If you chose this option you can model the resource path as you like.
    • If the relationship between user and image is 1 to 1 I'd favor to model the image as an attribute specially if both data sets are updated at the same time. In any other case you can freely choose to model the image either as an attribute, updating the it via PUT or PATCH, or as a separate resource.
  • If you choose multipart payload I'd feel compelled to model the image as a resource on is own, so that other resources, in our case, the user resource, is not impacted by the decision of using a binary representation for the image.

Then comes the question: Is there any performance impact about choosing base64 vs multipart?. We could think that exchanging data in multipart format should be more efficient. But this article shows how little do both representations differ in terms of size.

My choice Base64:

  • Consistent design decision
  • Negligible performance impact
  • As browsers understand data URIs (base64 encoded images), there is no need to transform these if the client is a browser
  • I won't cast a vote on whether to have it as an attribute or standalone resource, it depends on your problem domain (which I don't know) and your personal preference.

Remove duplicate elements from array in Ruby

You can return the intersection.

a = [1,1,2,3]
a & a

This will also delete duplicates.

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

When You are sending a single quote in a query

empid = " T'via"
empid =escape(empid)

When You get the value including a single quote

var xxx  = request.QueryString("empid")
xxx= unscape(xxx)

If you want to search/ insert the value which includes a single quote in a query xxx=Replace(empid,"'","''")

Convert byte to string in Java

The string ctor is suitable for this conversion:

System.out.println("string " + new String(new byte[] {0x63}));

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

First letter of file name and class name must be in Uppercase.

Your model class will be

class Logon_model extends CI_Model

and the file name will be Logon_model.php

Access it from your contoller like

$this->load->model('Logon_model');

How to validate a form with multiple checkboxes to have atleast one checked

I had to do the same thing and this is what I wrote.I made it more flexible in my case as I had multiple group of check boxes to check.

// param: reqNum number of checkboxes to select
$.fn.checkboxValidate = function(reqNum){
    var fields = this.serializeArray();
    return (fields.length < reqNum) ? 'invalid' : 'valid';
}

then you can pass this function to check multiple group of checkboxes with multiple rules.

// helper function to create error
function err(msg){
    alert("Please select a " + msg + " preference.");
}

$('#reg').submit(function(e){
    //needs at lease 2 checkboxes to be selected
    if($("input.region, input.music").checkboxValidate(2) == 'invalid'){
        err("Region and Music");
    } 
});

PHP cURL not working - WAMP on Windows 7 64 bit

The error is unrelated to PHP. It means you are somehow relying on Apache's mod_deflate, but that Apache module is not loaded. Try enabling mod_deflate in httpd.conf or commenting out the offending line (search for DEFLATE in httpd.conf).

As for the PHP curl extension, you must make sure it's activated in php.ini. Make sure extension_diris set to the directory php_curl.dll is in:

extension_dir = "C:/whatever" and then add

extension=php_curl.dll