Programs & Examples On #Fluent migrator

FluentMigrator is a migration framework for the .NET platform that lets you easily create migration-steps that fit very nicely into an automated deployment scenario.

How to get the scroll bar with CSS overflow on iOS

The iScroll4 javascript library will fix it right up. It has a hideScrollbar method that you can set to false to prevent the scrollbar from disappearing.

python dict to numpy structured array

Let me propose an improved method when the values of the dictionnary are lists with the same lenght :

import numpy

def dctToNdarray (dd, szFormat = 'f8'):
    '''
    Convert a 'rectangular' dictionnary to numpy NdArray
    entry 
        dd : dictionnary (same len of list 
    retrun
        data : numpy NdArray 
    '''
    names = dd.keys()
    firstKey = dd.keys()[0]
    formats = [szFormat]*len(names)
    dtype = dict(names = names, formats=formats)
    values = [tuple(dd[k][0] for k in dd.keys())]
    data = numpy.array(values, dtype=dtype)
    for i in range(1,len(dd[firstKey])) :
        values = [tuple(dd[k][i] for k in dd.keys())]
        data_tmp = numpy.array(values, dtype=dtype)
        data = numpy.concatenate((data,data_tmp))
    return data

dd = {'a':[1,2.05,25.48],'b':[2,1.07,9],'c':[3,3.01,6.14]}
data = dctToNdarray(dd)
print data.dtype.names
print data

Moment.js with ReactJS (ES6)

Since you are using webpack you should be able to just import or require moment and then use it:

import moment from 'moment'

...
render() {
    return (
        <div>
            { 
            this.props.data.map((post,key) => 
                <div key={key} className="post-detail">
                    <h1>{post.title}</h1>
                    <p>{moment(post.date).format()}</p>
                    <p dangerouslySetInnerHTML={{__html: post.content}}></p>
                    <hr />
                </div>
            )}
        </div>
    );
}
...

How can I get the iOS 7 default blue color programmatically?

swift 4 way:

extension UIColor {
  static let system = UIView().tintColor!
}

TimeSpan to DateTime conversion

var StartTime = new DateTime(item.StartTime.Ticks);

REST response code for invalid data

It is amusing to return 418 I'm a teapot to requests that are obviously crafted or malicious and "can't happen", such as failing CSRF check or missing request properties.

2.3.2 418 I'm a teapot

Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.

To keep it reasonably serious, I restrict usage of funny error codes to RESTful endpoints that are not directly exposed to the user.

Simple and clean way to convert JSON string to Object in Swift

for swift 3/4

extension String {
    func toJSON() -> Any? {
        guard let data = self.data(using: .utf8, allowLossyConversion: false) else { return nil }
        return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    }
}

Example Usage:

 let dict = myString.toJSON() as? [String:AnyObject] // can be any type here

Git merge with force overwrite

When I tried using -X theirs and other related command switches I kept getting a merge commit. I probably wasn't understanding it correctly. One easy to understand alternative is just to delete the branch then track it again.

git branch -D <branch-name>
git branch --track <branch-name> origin/<branch-name>

This isn't exactly a "merge", but this is what I was looking for when I came across this question. In my case I wanted to pull changes from a remote branch that were force pushed.

Simple way to get element by id within a div tag?

You may try something like this.

Sample Markup.

<div id="div1" >
    <input type="text" id="edit1" />
    <input type="text" id="edit2" />
</div>
<div id="div2" >
    <input type="text" id="edit3" />
    <input type="text" id="edit4" />
</div>

JavaScript

function GetElementInsideContainer(containerID, childID) {
    var elm = {};
    var elms = document.getElementById(containerID).getElementsByTagName("*");
    for (var i = 0; i < elms.length; i++) {
        if (elms[i].id === childID) {
            elm = elms[i];
            break;
        }
    }
    return elm;
}

Demo: http://jsfiddle.net/naveen/H8j2A/

A better method as suggested by nnnnnn

function GetElementInsideContainer(containerID, childID) {
    var elm = document.getElementById(childID);
    var parent = elm ? elm.parentNode : {};
    return (parent.id && parent.id === containerID) ? elm : {};
}

Demo: http://jsfiddle.net/naveen/4JMgF/

Call it like

var e = GetElementInsideContainer("div1", "edit1");

SSIS Convert Between Unicode and Non-Unicode Error

I have been having the same issue and tried everything written here but it was still giving me the same error. Turned out to be NULL value in the column which I was trying to convert.

Removing the NULL value solved my issue.

Cheers, Ahmed

PHP date() format when inserting into datetime in MySQL

Here's an alternative solution: if you have the date in PHP as a timestamp, bypass handling it with PHP and let the DB take care of transforming it by using the FROM_UNIXTIME function.

mysql> insert into a_table values(FROM_UNIXTIME(1231634282));
Query OK, 1 row affected (0.00 sec)

mysql> select * from a_table;

+---------------------+
| a_date              |
+---------------------+
| 2009-01-10 18:38:02 |
+---------------------+

Quotation marks inside a string

String name = "\"john\"";

You have to escape the second pair of quotation marks using the \ character in front. It might be worth looking at this link, which explains in some detail.

Other scenario where you set variable:

String name2 = "\""+name+"\"";

Sequence in console:

> String name = "\"john\"";
> name
""john""
> String name2 = "\""+name+"\"";
> name2
"""john"""

Procedure or function !!! has too many arguments specified

For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.

Just put use [DBName] on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

Remote Procedure call failed with sql server 2008 R2

I got the samilar issue, while both SQLServer and SQLServerAgent services are running. The error is fixed by a restart of services.

Server Manager > Service > 
    SQL Server > Stop
    SQL Server > Start
    SQL Server Agent > Start

DateTime vs DateTimeOffset

TLDR if you don't want to read all these great answers :-)

Explicit:

Using DateTimeOffset because the timezone is forced to UTC+0.

Implicit:

Using DateTime where you hope everyone sticks to the unwritten rule of the timezone always being UTC+0.


(Side note for devs: explicit is always better than implicit!)

(Side side note for Java devs, C# DateTimeOffset == Java OffsetDateTime, read this: https://www.baeldung.com/java-zoneddatetime-offsetdatetime)

How do you decrease navbar height in Bootstrap 3?

Minder Saini's example above almost works, but the .navbar-brand needs to be reduced as well.

A working example (using it on my own site) with Bootstrap 3.3.4:

.navbar-nav > li > a, .navbar-brand {
    padding-top:5px !important; padding-bottom:0 !important;
    height: 30px;
}
.navbar {min-height:30px !important;}

Edit for Mobile... To make this example work on mobile as well, you have to change the styling of the navbar toggle like so

.navbar-toggle {
     padding: 0 0;
     margin-top: 7px;
     margin-bottom: 0;
}

Saving an image in OpenCV

On OSX, saving video frames and still images only worked for me when I gave a full path to cvSaveImage:

cvSaveImage("/Users/nicc/image.jpg",img);

Gradle task - pass arguments to Java application

Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar, you can use

gradle run --args='foo --bar'

See Also Gradle Application Plugin

How to upgrade Gradle wrapper

How to remove blank lines from a Unix file

sed -i '/^$/d' foo

This tells sed to delete every line matching the regex ^$ i.e. every empty line. The -i flag edits the file in-place, if your sed doesn't support that you can write the output to a temporary file and replace the original:

sed '/^$/d' foo > foo.tmp
mv foo.tmp foo

If you also want to remove lines consisting only of whitespace (not just empty lines) then use:

sed -i '/^[[:space:]]*$/d' foo

Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:

sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo

Making view resize to its parent when added with addSubview

Tested in Xcode 9.4, Swift 4 Another way to solve this issue is , You can add

override func layoutSubviews() {
        self.frame = (self.superview?.bounds)!
    }

in subview class.

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

You can use:

SET PASSWORD FOR 'root' = PASSWORD('elephant7');

or, in latest versions:

SET PASSWORD FOR root = 'elephant7' 

You can also use:

UPDATE user SET password=password('elephant7') WHERE user='root';

but in Mysql 5.7 the field password is no more there, and you have to use:

UPDATE user SET authentication_string=password('elephant7') WHERE user='root';

Regards

TypeError: method() takes 1 positional argument but 2 were given

In simple words.

In Python you should add self argument as the first argument to all defined methods in classes:

class MyClass:
  def method(self, arg):
    print(arg)

Then you can use your method according to your intuition:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

This should solve your problem :)

For a better understanding, you can also read the answers to this question: What is the purpose of self?

Native query with named parameter fails with "Not all named parameters have been set"

Use set Parameter from query.

Query q = (Query) em.createNativeQuery("SELECT count(*) FROM mytable where username = ?1");
q.setParameter(1, "test");

How to get value of Radio Buttons?

For Win Forms :

To get the value (assuming that you want the value, not the text) out of a radio button, you get the Checked property:

string value = "";
bool isChecked = radioButton1.Checked;
if(isChecked )
  value=radioButton1.Text;
else
  value=radioButton2.Text;

For Web Forms :

<asp:RadioButtonList ID="rdoPriceRange" runat="server" RepeatLayout="Flow">
    <asp:ListItem Value="Male">Male</asp:ListItem>
    <asp:ListItem Value="Female">Female</asp:ListItem>
</asp:RadioButtonList>

And CS-in some button click

string value=rdoPriceRange.SelectedItem.Value.ToString();

String's Maximum length in Java - calling length() method

java.io.DataInput.readUTF() and java.io.DataOutput.writeUTF(String) say that a String object is represented by two bytes of length information and the modified UTF-8 representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with DataInput and DataOutput.

In addition, The specification of CONSTANT_Utf8_info found in the Java virtual machine specification defines the structure as follows.

CONSTANT_Utf8_info {
    u1 tag;
    u2 length;
    u1 bytes[length];
}

You can find that the size of 'length' is two bytes.

That the return type of a certain method (e.g. String.length()) is int does not always mean that its allowed maximum value is Integer.MAX_VALUE. Instead, in most cases, int is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of int are converted to int before calculation (if my memory serves me correctly) and it is one reason to choose int when there is no special reason.

The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the modified UTF-8 representation, not the number of characters in a String object.

String objects may be able to have much more characters at runtime. However, if you want to use String objects with DataInput and DataOutput interfaces, it is better to avoid using too long String objects. I found this limitation when I implemented Objective-C equivalents of DataInput.readUTF() and DataOutput.writeUTF(String).

Application not picking up .css file (flask/python)

One more point to add on to this thread.

If you add an underscore in your .css file name, then it wouldn't work.

Getters \ setters for dummies

You'd use them for instance to implement computed properties.

For example:

function Circle(radius) {
    this.radius = radius;
}

Object.defineProperty(Circle.prototype, 'circumference', {
    get: function() { return 2*Math.PI*this.radius; }
});

Object.defineProperty(Circle.prototype, 'area', {
    get: function() { return Math.PI*this.radius*this.radius; }
});

c = new Circle(10);
console.log(c.area); // Should output 314.159
console.log(c.circumference); // Should output 62.832

(CodePen)

HTML - How to do a Confirmation popup to a Submit button and then send the request?

<script type='text/javascript'>

function foo() {


var user_choice = window.confirm('Would you like to continue?');


if(user_choice==true) {


window.location='your url';  // you can also use element.submit() if your input type='submit' 


} else {


return false;


}
}

</script>

<input type="button" onClick="foo()" value="save">

How to evaluate http response codes from bash/shell script?

I needed to demo something quickly today and came up with this. Thought I would place it here if someone needed something similar to the OP's request.

#!/bin/bash

status_code=$(curl --write-out %{http_code} --silent --output /dev/null www.bbc.co.uk/news)

if [[ "$status_code" -ne 200 ]] ; then
  echo "Site status changed to $status_code" | mail -s "SITE STATUS CHECKER" "[email protected]" -r "STATUS_CHECKER"
else
  exit 0
fi

This will send an email alert on every state change from 200, so it's dumb and potentially greedy. To improve this, I would look at looping through several status codes and performing different actions dependant on the result.

How to Completely Uninstall Xcode and Clear All Settings

Before taking such drastic measures, quit Xcode and follow all the instructions here for cleaning out the caches:

How to Empty Caches and Clean All Targets Xcode 4

If that doesn't help, and you decide you really need a clean installation of Xcode, then, in addition to all of the stuff in that answer, trash the Xcode app itself, plus trash your ~/Library/Developer folder and your ~/Library/Preferences/com.apple.dt.Xcode.plist file. I think that should just about do it.

how to show only even or odd rows in sql server 2008?

FASTER: Bitwise instead of modulus.

select * from MEN where (id&1)=0;

Random question: Do you actually use uppercase table names? Usually uppercase is reserved for keywords. (By convention)

Python DNS module import error

I have faced similar issue when importing on mac.i have python 3.7.3 installed Following steps helped me resolve it:

  1. pip3 uninstall dnspython
  2. sudo -H pip3 install dnspython

Import dns

Import dns.resolver

HTTP GET in VBS

You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP (I recommend the more explicit MSXML2.XMLHTTP.3.0 progID) however you may need to do different things with the response, it may not be text.

The XMLHTTP also has a responseBody property which is a byte array version of the reponse and there is a responseStream which is an IStream wrapper for the response.

Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0 or WinHttp.WinHttpRequest.5.1 (which has a near identical interface).

Here is an example of using XmlHttp to fetch a PDF file and store it:-

Dim oXMLHTTP
Dim oStream

Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")

oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send

If oXMLHTTP.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write oXMLHTTP.responseBody
    oStream.SaveToFile "c:\somefolder\file.pdf"
    oStream.Close
End If

React proptype array with shape

There's a ES6 shorthand import, you can reference. More readable and easy to type.

import React, { Component } from 'react';
import { arrayOf, shape, number } from 'prop-types';

class ExampleComponent extends Component {
  static propTypes = {
    annotationRanges: arrayOf(shape({
      start: number,
      end: number,
    })).isRequired,
  }

  static defaultProps = {
     annotationRanges: [],
  }
}

jQuery-- Populate select from json

I believe this can help you:

$(document).ready(function(){
    var temp = {someKey:"temp value", otherKey:"other value", fooKey:"some value"};
    for (var key in temp) {
        alert('<option value=' + key + '>' + temp[key] + '</option>');
    }
});

Remove scrollbars from textarea

style="overflow: hidden" and style="resize: none" were the ones that did the trick.

How to POST request using RestSharp

My RestSharp POST method:

var client = new RestClient(ServiceUrl);

var request = new RestRequest("/resource/", Method.POST);

// Json to post.
string jsonToSend = JsonHelper.ToJson(json);

request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;

try
{
    client.ExecuteAsync(request, response =>
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // OK
        }
        else
        {
            // NOK
        }
    });
}
catch (Exception error)
{
    // Log
}

What is the purpose of flush() in Java streams?

When we give any command, the streams of that command are stored in the memory location called buffer(a temporary memory location) in our computer. When all the temporary memory location is full then we use flush(), which flushes all the streams of data and executes them completely and gives a new space to new streams in buffer temporary location. -Hope you will understand

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

This trick works for me.

You don't have this problem on remote server, because on remote server, the last insert command waits for the result of previous command to execute. It's not the case on same server.

Profit that situation for a workaround.

If you have the right permission to create a Linked Server, do it. Create the same server as linked server.

  • in SSMS, log into your server
  • go to "Server Object
  • Right Click on "Linked Servers", then "New Linked Server"
  • on the dialog, give any name of your linked server : eg: THISSERVER
  • server type is "Other data source"
  • Provider : Microsoft OLE DB Provider for SQL server
  • Data source: your IP, it can be also just a dot (.), because it's localhost
  • Go to the tab "Security" and choose the 3rd one "Be made using the login's current security context"
  • You can edit the server options (3rd tab) if you want
  • Press OK, your linked server is created

now your Sql command in the SP1 is

insert into @myTempTable
exec THISSERVER.MY_DATABASE_NAME.MY_SCHEMA.SP2

Believe me, it works even you have dynamic insert in SP2

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

Android checkbox style

Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.


My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.

At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.

First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.

<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />

As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox in a different name. So let's look at that parent style.

<style name="Widget.CompoundButton.CheckBox">
    <item name="android:background">@android:drawable/btn_check_label_background</item>
    <item name="android:button">?android:attr/listChoiceIndicatorMultiple</item>
</style>

This style references both a background and button drawable. btn_check_label_background is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox.

As listChoiceIndicatorMultiple is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):

<style name="Theme">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
    ...
</style>

<style name="Theme.Holo">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
    ...
</style>

<style name="Theme.Holo.Light" parent="Theme.Light">
    <item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
    ...
</style>

So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple attribute, the actual appearance of the CheckBox is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo, you will always get the CheckBox appearance matching the theme.

Now, if you want to change your CheckBox's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.

As for your second question:

Also can you set styles to individual widgets if you set a style to the application?

Absolutely, and they will override any activity- or application-set styles.

Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?


Update:

Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.

However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:

int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);

The first line will actually return the resource id of the btn_check_holo_light drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox, we can set it as 'button drawable' on the widget. The result is a CheckBox with the appearance of the Holo.Light version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.

Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo styling (non-light, that is).

Screenshot showing the result


Update2:

With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):

Lollipop added the ability to overwrite the theme at a view by view level by using the android:theme XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to use android:theme for Toolbars (deprecating the app:theme used previously) and, even better, brings android:theme support to all views on API 11+ devices.

In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo" />

<CheckBox
    ...
    android:theme="@android:style/Theme.Holo.Light" />

The first CheckBox is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.

Of course you should no longer be using the Holo theme, but instead use Material.

Reading file using relative path in python project

This worked for me.

with open('data/test.csv') as f:

 

How to tar certain file types in all subdirectories?

find ./someDir -name "*.php" -o -name "*.html" | tar -cf my_archive -T -

The program can't start because libgcc_s_dw2-1.dll is missing

I believe this is a MinGW/gcc compiler issue, rather than a Microsoft Visual Studio setup.

The libgcc_s_dw2-1.dll should be in the compiler's bin directory. You can add this directory to your PATH environment variable for runtime linking, or you can avoid the problem by adding "-static-libgcc -static-libstdc++" to your compiler flags.

If you plan to distribute the executable, the latter probably makes the most sense. If you only plan to run it on your own machine, the changing the PATH environment variable is an attractive option (keeps down the size of the executable).

Updated:

Based on feedback from Greg Treleaven (see comments below), I'm adding links to:

[Screenshot of Code::Blocks "Project build options"]

[GNU gcc link options]

The latter discussion includes -static-libgcc and -static-libstdc++ linker options.

XPath - Difference between node() and text()

text() and node() are node tests, in XPath terminology (compare).

Node tests operate on a set (on an axis, to be exact) of nodes and return the ones that are of a certain type. When no axis is mentioned, the child axis is assumed by default.

There are all kinds of node tests:

  • node() matches any node (the least specific node test of them all)
  • text() matches text nodes only
  • comment() matches comment nodes
  • * matches any element node
  • foo matches any element node named "foo"
  • processing-instruction() matches PI nodes (they look like <?name value?>).
  • Side note: The * also matches attribute nodes, but only along the attribute axis. @* is a shorthand for attribute::*. Attributes are not part of the child axis, that's why a normal * does not select them.

This XML document:

<produce>
    <item>apple</item>
    <item>banana</item>
    <item>pepper</item>
</produce>

represents the following DOM (simplified):

root node
   element node (name="produce")
      text node (value="\n    ")
      element node (name="item")
         text node (value="apple")
      text node (value="\n    ")
      element node (name="item")
         text node (value="banana")
      text node (value="\n    ")
      element node (name="item")
         text node (value="pepper")
      text node (value="\n")

So with XPath:

  • / selects the root node
  • /produce selects a child element of the root node if it has the name "produce" (This is called the document element; it represents the document itself. Document element and root node are often confused, but they are not the same thing.)
  • /produce/node() selects any type of child node beneath /produce/ (i.e. all 7 children)
  • /produce/text() selects the 4 (!) whitespace-only text nodes
  • /produce/item[1] selects the first child element named "item"
  • /produce/item[1]/text() selects all child text nodes (there's only one - "apple" - in this case)

And so on.

So, your questions

  • "Select the text of all items under produce" /produce/item/text() (3 nodes selected)
  • "Select all the manager nodes in all departments" //department/manager (1 node selected)

Notes

  • The default axis in XPath is the child axis. You can change the axis by prefixing a different axis name. For example: //item/ancestor::produce
  • Element nodes have text values. When you evaluate an element node, its textual contents will be returned. In case of this example, /produce/item[1]/text() and string(/produce/item[1]) will be the same.
  • Also see this answer where I outline the individual parts of an XPath expression graphically.

How can I open the interactive matplotlib window in IPython notebook?

If all you want to do is to switch from inline plots to interactive and back (so that you can pan/zoom), it is better to use %matplotlib magic.

#interactive plotting in separate window
%matplotlib qt 

and back to html

#normal charts inside notebooks
%matplotlib inline 

%pylab magic imports a bunch of other things and may even result in a conflict. It does "from pylab import *".

You also can use new notebook backend (added in matplotlib 1.4):

#interactive charts inside notebooks, matplotlib 1.4+
%matplotlib notebook 

If you want to have more interactivity in your charts, you can look at mpld3 and bokeh. mpld3 is great, if you don't have ton's of data points (e.g. <5k+) and you want to use normal matplotlib syntax, but more interactivity, compared to %matplotlib notebook . Bokeh can handle lots of data, but you need to learn it's syntax as it is a separate library.

Also you can check out pivottablejs (pip install pivottablejs)

from pivottablejs import pivot_ui
pivot_ui(df)

However cool interactive data exploration is, it can totally mess with reproducibility. It has happened to me, so I try to use it only at the very early stage and switch to pure inline matplotlib/seaborn, once I got the feel for the data.

PDO mysql: How to know if insert was successful

Use id as primary key with auto increment

$stmt->execute();
$insertid = $conn->lastInsertId();

incremental id is always bigger than zero even on first record so that means it will always return a true value for id coz bigger than zero means true in PHP

if ($insertid)
   echo "record inserted successfully";
else
   echo "record insertion failed";

What is the difference between ( for... in ) and ( for... of ) statements?

The for-in loop

for-in loop is used to traverse through enumerable properties of a collection, in an arbitrary order. A collection is a container type object whose items can be using an index or a key.

_x000D_
_x000D_
var myObject = {a: 1, b: 2, c: 3};_x000D_
var myArray = [1, 2, 3];_x000D_
var myString = "123";_x000D_
_x000D_
console.log( myObject[ 'a' ], myArray[ 1 ], myString[ 2 ] );
_x000D_
_x000D_
_x000D_

for-in loop extracts the enumerable properties (keys) of a collection all at once and iterates over it one at a time. An enumerable property is the property of a collection that can appear in for-in loop.

By default, all properties of an Array and Object appear in for-in loop. However, we can use Object.defineProperty method to manually configure the properties of a collection.

_x000D_
_x000D_
var myObject = {a: 1, b: 2, c: 3};_x000D_
var myArray = [1, 2, 3];_x000D_
_x000D_
Object.defineProperty( myObject, 'd', { value: 4, enumerable: false } );_x000D_
Object.defineProperty( myArray, 3, { value: 4, enumerable: false } );_x000D_
_x000D_
for( var i in myObject ){ console.log( 'myObject:i =>', i ); }_x000D_
for( var i in myArray ){ console.log( 'myArray:i  =>', i ); }
_x000D_
_x000D_
_x000D_

In the above example, the property d of the myObject and the index 3 of myArray does not appear in for-in loop because they are configured with enumerable: false.

There are few issues with for-in loops. In the case of Arrays, for-in loop will also consider methods added on the array using myArray.someMethod = f syntax, however, myArray.length remains 4.

The for-of loop

It is a misconception that for-of loop iterate over the values of a collection. for-of loop iterates over an Iterable object. An iterable is an object that has the method with the name Symbol.iterator directly on it one on one of its prototypes.

Symbol.iterator method should return an Iterator. An iterator is an object which has a next method. This method when called return value and done properties.

When we iterate an iterable object using for-of loop, the Symbol.iterator the method will be called once get an iterator object. For every iteration of for-of loop, next method of this iterator object will be called until done returned by the next() call returns false. The value received by the for-of loop for every iteration if the value property returned by the next() call.

_x000D_
_x000D_
var myObject = { a: 1, b: 2, c: 3, d: 4 };_x000D_
_x000D_
// make `myObject` iterable by adding `Symbol.iterator` function directlty on it_x000D_
myObject[ Symbol.iterator ] = function(){_x000D_
  console.log( `LOG: called 'Symbol.iterator' method` );_x000D_
  var _myObject = this; // `this` points to `myObject`_x000D_
  _x000D_
  // return an iterator object_x000D_
  return {_x000D_
    keys: Object.keys( _myObject ), _x000D_
    current: 0,_x000D_
    next: function() {_x000D_
      console.log( `LOG: called 'next' method: index ${ this.current }` );_x000D_
      _x000D_
      if( this.current === this.keys.length ){_x000D_
        return { done: true, value: null }; // Here, `value` is ignored by `for-of` loop_x000D_
      } else {_x000D_
        return { done: false, value: _myObject[ this.keys[ this.current++ ] ] };_x000D_
      }_x000D_
    }_x000D_
  };_x000D_
}_x000D_
_x000D_
// use `for-of` loop on `myObject` iterable_x000D_
for( let value of myObject ) {_x000D_
  console.log( 'myObject: value => ', value );_x000D_
}
_x000D_
_x000D_
_x000D_

The for-of loop is new in ES6 and so are the Iterable and Iterables. The Array constructor type has Symbol.iterator method on its prototype. The Object constructor sadly doesn't have it but Object.keys(), Object.values() and Object.entries() methods return an iterable (you can use console.dir(obj) to check prototype methods). The benefit of the for-of loop is that any object can be made iterable, even your custom Dog and Animal classes.

The easy way to make an object iterable is by implementing ES6 Generator instead of custom iterator implementation.

Unlike for-in, for-of loop can wait for an async task to complete in each iteration. This is achieved using await keyword after for statement documentation.

Another great thing about for-of loop is that it has Unicode support. According to ES6 specifications, strings are stored with UTF-16 encoding. Hence, each character can take either 16-bit or 32-bit. Traditionally, strings were stored with UCS-2 encoding which has supports for characters that can be stored within 16 bits only.

Hence, String.length returns number of 16-bit blocks in a string. Modern characters like an Emoji character takes 32 bits. Hence, this character would return length of 2. for-in loop iterates over 16-bit blocks and returns the wrong index. However, for-of loop iterates over the individual character based on UTF-16 specifications.

_x000D_
_x000D_
var emoji = "";_x000D_
_x000D_
console.log( 'emoji.length', emoji.length );_x000D_
_x000D_
for( var index in emoji ){ console.log( 'for-in: emoji.character', emoji[index] ); }_x000D_
for( var character of emoji ){ console.log( 'for-of: emoji.character', character ); }
_x000D_
_x000D_
_x000D_

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

Android: How to open a specific folder via Intent and show its content in a file browser?

File temp = File.createTempFile("preview", ".png" );
String fullfileName= temp.getAbsolutePath();
final String fileName = Uri.parse(fullfileName)
                    .getLastPathSegment();
final String filePath = fullfileName.
                     substring(0,fullfileName.lastIndexOf(File.separator));
Log.d("filePath", "filePath: " + filePath);

fullfileName:

/mnt/sdcard/Download_Manager_Farsi/preview.png

filePath:

/mnt/sdcard/Download_Manager_Farsi

What is the equivalent of 'describe table' in SQL Server?

Just select table and press Alt+F1,

it will show all the information about table like Column name, datatype, keys etc.

How can I increment a char?

"bad enough not having a traditional for(;;) looper"?? What?

Are you trying to do

import string
for c in string.lowercase:
    ...do something with c...

Or perhaps you're using string.uppercase or string.letters?

Python doesn't have for(;;) because there are often better ways to do it. It also doesn't have character math because it's not necessary, either.

Empty an array in Java / processing

Faster clearing than Arrays.fill is with this (From Fast Serialization Lib). I just use arrayCopy (is native) to clear the array:

static Object[] EmptyObjArray = new Object[10000];

public static void clear(Object[] arr) {
    final int arrlen = arr.length;
    clear(arr, arrlen);
}

public static void clear(Object[] arr, int arrlen) {
    int count = 0;
    final int length = EmptyObjArray.length;
    while( arrlen - count > length) {
        System.arraycopy(EmptyObjArray,0,arr,count, length);
        count += length;
    }
    System.arraycopy(EmptyObjArray,0,arr,count, arrlen -count);
}

Dynamically set value of a file input

I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.

Ways to iterate over a list in Java

Example of each kind listed in the question:

ListIterationExample.java

import java.util.*;

public class ListIterationExample {

     public static void main(String []args){
        List<Integer> numbers = new ArrayList<Integer>();

        // populates list with initial values
        for (Integer i : Arrays.asList(0,1,2,3,4,5,6,7))
            numbers.add(i);
        printList(numbers);         // 0,1,2,3,4,5,6,7

        // replaces each element with twice its value
        for (int index=0; index < numbers.size(); index++) {
            numbers.set(index, numbers.get(index)*2); 
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14

        // does nothing because list is not being changed
        for (Integer number : numbers) {
            number++; // number = new Integer(number+1);
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14  

        // same as above -- just different syntax
        for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            number++;
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14

        // ListIterator<?> provides an "add" method to insert elements
        // between the current element and the cursor
        for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            iter.add(number+1);     // insert a number right before this
        }
        printList(numbers);         // 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15

        // Iterator<?> provides a "remove" method to delete elements
        // between the current element and the cursor
        for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            if (number % 2 == 0)    // if number is even 
                iter.remove();      // remove it from the collection
        }
        printList(numbers);         // 1,3,5,7,9,11,13,15

        // ListIterator<?> provides a "set" method to replace elements
        for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            iter.set(number/2);     // divide each element by 2
        }
        printList(numbers);         // 0,1,2,3,4,5,6,7
     }

     public static void printList(List<Integer> numbers) {
        StringBuilder sb = new StringBuilder();
        for (Integer number : numbers) {
            sb.append(number);
            sb.append(",");
        }
        sb.deleteCharAt(sb.length()-1); // remove trailing comma
        System.out.println(sb.toString());
     }
}

Comparing two strings, ignoring case in C#

you may also want to look at that already answered question Differences in string compare methods in C#

Time in milliseconds in C

You can use gettimeofday() together with the timedifference_msec() function below to calculate the number of milliseconds elapsed between two samples:

#include <sys/time.h>
#include <stdio.h>

float timedifference_msec(struct timeval t0, struct timeval t1)
{
    return (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) / 1000.0f;
}

int main(void)
{
   struct timeval t0;
   struct timeval t1;
   float elapsed;

   gettimeofday(&t0, 0);
   /* ... YOUR CODE HERE ... */
   gettimeofday(&t1, 0);

   elapsed = timedifference_msec(t0, t1);

   printf("Code executed in %f milliseconds.\n", elapsed);

   return 0;
}

Note that, when using gettimeofday(), you need to take seconds into account even if you only care about microsecond differences because tv_usec will wrap back to zero every second and you have no way of knowing beforehand at which point within a second each sample is obtained.

Creating columns in listView and add items

            listView1.View = View.Details;
        listView1.Columns.Add("Target No.", 83, HorizontalAlignment.Center);
        listView1.Columns.Add("   Range   ", 100, HorizontalAlignment.Center);
        listView1.Columns.Add(" Azimuth ", 100, HorizontalAlignment.Center);     

i also had same problem .. i drag column to left .. but now ok .. so let's say i have 283*196 size of listview ..... We declared in the column width -2 for auto width .. For fitting in the listview ,we can divide listview width into 3 parts (83,100,100) ...

Why do I get a C malloc assertion failure?

i got the same problem, i used malloc over n over again in a loop for adding new char *string data. i faced the same problem, but after releasing the allocated memory void free() problem were sorted

How can I disable inherited css styles?

Cascading Style Sheet are designed for inheritance. Inheritance is intrinsic to their existence. If it wasn't built to be cascading, they would only be called "Style Sheets".

That said, if an inherited style doesn't fit your needs, you'll have to override it with another style closer to the object. Forget about the notion of "blocking inheritance".

You can also choose the more granular solution by giving styles to every individual objects, and not giving styles to the general tags like div, p, pre, etc.

For example, you can use styles that start with # for objects with a specific ID:

<style>
#dividstyle{
    font-family:MS Trebuchet;
}
</style>
<div id="dividstyle">Hello world</div>

You can define classes for objects:

<style>
.divclassstyle{
    font-family: Calibri;
}
</style>
<div class="divclassstyle">Hello world</div>

Hope it helps.

In Bash, how can I check if a string begins with some value?

grep

Forgetting performance, this is POSIX and looks nicer than case solutions:

mystr="abcd"
if printf '%s' "$mystr" | grep -Eq '^ab'; then
  echo matches
fi

Explanation:

Maven in Eclipse: step by step installation

I have just include Maven integration plug-in at Eclipse:

Just follow the bellow steps:

  • In eclipse, from upper menu item select- "Help" ->click on "Install New Software.."-> then click on "Add" button.

  • set the "MavenAPI" at name text box and "http://download.eclipse.org/technology/m2e/releases" at location text box.

  • press Ok and select the Maven project and install by clicking next next.

How to prevent column break within an element?

As of October 2014, break-inside still seems to be buggy in Firefox and IE 10-11. However, adding overflow: hidden to the element, along with the break-inside: avoid, seems to make it work in Firefox and IE 10-11. I am currently using:

overflow: hidden; /* Fix for firefox and IE 10-11  */
-webkit-column-break-inside: avoid; /* Chrome, Safari, Opera */
page-break-inside: avoid; /* Firefox */
break-inside: avoid; /* IE 10+ */
break-inside: avoid-column;

Find an item in List by LINQ?

How about IndexOf?

Searches for the specified object and returns the index of the first occurrence within the list

For example

> var boys = new List<string>{"Harry", "Ron", "Neville"};  
> boys.IndexOf("Neville")  
2
> boys[2] == "Neville"
True

Note that it returns -1 if the value doesn't occur in the list

> boys.IndexOf("Hermione")  
-1

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

Not this exact problem, but this is the top result when googling for almost the exact same error:

If you see this problem calling a WCF Service hosted on the same machine, you may need to populate the BackConnectionHostNames registry key

  1. In regedit, locate and then click the following registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
  2. Right-click MSV1_0, point to New, and then click Multi-String Value.
  3. In the Name column, type BackConnectionHostNames, and then press ENTER.
  4. Right-click BackConnectionHostNames, and then click Modify. In the Value data box, type the CNAME or the DNS alias, that is used for the local shares on the computer, and then click OK.
    • Type each host name on a separate line.

See Calling WCF service hosted in IIS on the same machine as client throws authentication error for details.

Get full path of the files in PowerShell

Why has nobody used the foreach loop yet? A pro here is that you can easily name your variable:

# Note that I'm pretty explicit here. This would work as well as the line after:
# Get-ChildItem -Recurse C:\windows\System32\*.txt
$fileList = Get-ChildItem -Recurse -Path C:\windows\System32 -Include *.txt
foreach ($textfile in $fileList) {
    # This includes the filename ;)
    $filePath = $textfile.fullname
    # You can replace the next line with whatever you want to.
    Write-Output $filePath
}

Javascript Array of Functions

If you're doing something like trying to dynamically pass callbacks you could pass a single object as an argument. This gives you much greater control over which functions you want to you execute with any parameter.

function func_one(arg) {
    console.log(arg)
};

function func_two(arg) {
    console.log(arg+' make this different')
};

var obj = {
    callbacks: [func_one, func_two],
    params: ["something", "something else"];
};

function doSomething(obj) {
    var n = obj.counter
    for (n; n < (obj.callbacks.length - obj.len); n++) {
        obj.callbacks[n](obj.params[n]);
    }
};

obj.counter = 0;
obj.len = 0;
doSomething(obj); 

//something
//something else make this different

obj.counter = 1;
obj.len = 0;
doSomething(obj);

//something else make this different

UEFA/FIFA scores API

You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

How to rename uploaded file before saving it into a directory?

You can Try this,

$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

How can I strip first and last double quotes?

Below function will strip the empty spces and return the strings without quotes. If there are no quotes then it will return same string(stripped)

def removeQuote(str):
str = str.strip()
if re.search("^[\'\"].*[\'\"]$",str):
    str = str[1:-1]
    print("Removed Quotes",str)
else:
    print("Same String",str)
return str

What to do about Eclipse's "No repository found containing: ..." error messages?

Eclipse Kepler (at least) allows to specifically reload a software site in the Preferences > Install/Update > Available Software Sites dialog.

It is a cleaner / simpler solution than the workaround explained above (add trailing slash) and it worked for me...

Note: a link to this dialog is also available in the Install New Software dialog.

Python List vs. Array - when to use?

This answer will sum up almost all the queries about when to use List and Array:

  1. The main difference between these two data types is the operations you can perform on them. For example, you can divide an array by 3 and it will divide each element of array by 3. Same can not be done with the list.

  2. The list is the part of python's syntax so it doesn't need to be declared whereas you have to declare the array before using it.

  3. You can store values of different data-types in a list (heterogeneous), whereas in Array you can only store values of only the same data-type (homogeneous).

  4. Arrays being rich in functionalities and fast, it is widely used for arithmetic operations and for storing a large amount of data - compared to list.

  5. Arrays take less memory compared to lists.

C# how to create a Guid value?

There are two ways

var guid = Guid.NewGuid();

or

var guid = Guid.NewGuid().ToString();

both use the Guid class, the first creates a Guid Object, the second a Guid string.

How do I accomplish an if/else in mustache.js?

This is how you do if/else in Mustache (perfectly supported):

{{#repo}}
  <b>{{name}}</b>
{{/repo}}
{{^repo}}
  No repos :(
{{/repo}}

Or in your case:

{{#author}}
  {{#avatar}}
    <img src="{{avatar}}"/>
  {{/avatar}}
  {{^avatar}}
    <img src="/images/default_avatar.png" height="75" width="75" />
  {{/avatar}}
{{/author}}

Look for inverted sections in the docs: https://github.com/janl/mustache.js

Change bootstrap navbar background color and font color

No need for the specificity .navbar-default in your CSS. Background color requires background-color:#cc333333 (or just background:#cc3333). Finally, probably best to consolidate all your customizations into a single class, as below:

.navbar-custom {
    color: #FFFFFF;
    background-color: #CC3333;
}

..

<div id="menu" class="navbar navbar-default navbar-custom">

Example: http://www.bootply.com/OusJAAvFqR#

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

Reading an Excel file in python using pandas

Thought i should add here, that if you want to access rows or columns to loop through them, you do this:

import pandas as pd

# open the file
xlsx = pd.ExcelFile("PATH\FileName.xlsx")

# get the first sheet as an object
sheet1 = xlsx.parse(0)
    
# get the first column as a list you can loop through
# where the is 0 in the code below change to the row or column number you want    
column = sheet1.icol(0).real

# get the first row as a list you can loop through
row = sheet1.irow(0).real

Edit:

The methods icol(i) and irow(i) are deprecated now. You can use sheet1.iloc[:,i] to get the i-th col and sheet1.iloc[i,:] to get the i-th row.

C++ Erase vector element by value rather than by position?

Eric Niebler is working on a range-proposal and some of the examples show how to remove certain elements. Removing 8. Does create a new vector.

#include <iostream>
#include <range/v3/all.hpp>

int main(int argc, char const *argv[])
{
    std::vector<int> vi{2,4,6,8,10};
    for (auto& i : vi) {
        std::cout << i << std::endl;
    }
    std::cout << "-----" << std::endl;
    std::vector<int> vim = vi | ranges::view::remove_if([](int i){return i == 8;});
    for (auto& i : vim) {
        std::cout << i << std::endl;
    }
    return 0;
}

outputs

2
4
6
8
10
-----
2
4
6
10

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

How can I split and parse a string in Python?

"2.7.0_bf4fda703454".split("_") gives a list of strings:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1).

If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

An alternative is to use partition(). The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.

Printing chars and their ASCII-code in C

This reads a line of text from standard input and prints out the characters in the line and their ASCII codes:

#include <stdio.h>

void printChars(void)
{
    unsigned char   line[80+1];
    int             i;

    // Read a text line
    if (fgets(line, 80, stdin) == NULL)
        return;

    // Print the line chars
    for (i = 0;  line[i] != '\n';  i++)
    {
        int     ch;

        ch = line[i];
        printf("'%c' %3d 0x%02X\n", ch, ch, (unsigned)ch);
    }
}

How to convert java.sql.timestamp to LocalDate (java8) java.time?

You can do:

timeStamp.toLocalDateTime().toLocalDate();

Note that timestamp.toLocalDateTime() will use the Clock.systemDefaultZone() time zone to make the conversion. This may or may not be what you want.

Program to find largest and second largest number in array

Getting the second largest number from an array is pretty easy in python, I have done with simple steps and put various ways of test cases and it gave the right answer every time. PS. I know it's for c but I just gave a simple solution to the question if done in python

n = int(input()) #taking number of elements in array
arr = map(int, input().split()) #taking differet elements
l=[]
s=set()
for i in arr: #putting all the elemnents in set to remove any duplicate number
    s.add(i)
for j in s:  #putting all element from the set in the list to sort and get the second largest number
    l.append(j)
l.sort()
c=len(l)
print(l[c-2]) #printing second largest number

What is the purpose of Node.js module.exports and how do you use it?

There are some default or existing modules in node.js when you download and install node.js like http, sys etc.

Since they are already in node.js, when we want to use these modules we basically do like import modules, but why? because they are already present in the node.js. Importing is like taking them from node.js and putting them into your program. And then using them.

Whereas Exports is exactly the opposite, you are creating the module you want, let's say the module addition.js and putting that module into the node.js, you do it by exporting it.

Before I write anything here, remember, module.exports.additionTwo is same as exports.additionTwo

Huh, so that's the reason, we do like

exports.additionTwo = function(x)
{return x+2;};

Be careful with the path

Lets say you have created an addition.js module,

exports.additionTwo = function(x){
return x + 2;
};

When you run this on your NODE.JS command prompt:

node
var run = require('addition.js');

This will error out saying

Error: Cannot find module addition.js

This is because the node.js process is unable the addition.js since we didn't mention the path. So, we have can set the path by using NODE_PATH

set NODE_PATH = path/to/your/additon.js

Now, this should run successfully without any errors!!

One more thing, you can also run the addition.js file by not setting the NODE_PATH, back to your nodejs command prompt:

node
var run = require('./addition.js');

Since we are providing the path here by saying it's in the current directory ./ this should also run successfully.

Truncating a table in a stored procedure

try the below code

execute immediate 'truncate table tablename' ;

Does JavaScript have the interface type (such as Java's 'interface')?

there is no native interfaces in JavaScript, there are several ways to simulate an interface. i have written a package that does it

you can see the implantation here

HTML/Javascript change div content

$('#content').html('whatever');

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

Here are three different checkmark styles you can use:

_x000D_
_x000D_
ul:first-child  li:before { content:"\2713\0020"; }  /* OR */_x000D_
ul:nth-child(2) li:before { content:"\2714\0020"; }  /* OR */_x000D_
ul:last-child   li:before { content:"\2611\0020"; }_x000D_
ul { list-style-type: none; }
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul><!-- not working on Stack snippet; check fiddle demo -->_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

jsFiddle

References:

How to avoid the "Circular view path" exception with Spring MVC test

I use the annotation to configure spring web app, the problem solved by adding a InternalResourceViewResolver bean to the configuration. Hope it would be helpful.

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.example.springmvc" })
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

MySQL: Fastest way to count number of rows

I've always understood that the below will give me the fastest response times.

SELECT COUNT(1) FROM ... WHERE ...

Check with jquery if div has overflowing elements

I fixed this by adding another div in the one that overflows. Then you compare the heights of the 2 divs.

<div class="AAAA overflow-hidden" style="height: 20px;" >
    <div class="BBBB" >
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </div>
</div>

and the js

    if ($('.AAAA').height() < $('.BBBB').height()) {
        console.log('we have overflow')
    } else {
        console.log('NO overflow')
    }

This looks easier...

Good examples using java.util.logging

I would suggest that you use Apache's commons logging utility. It is highly scalable and supports separate log files for different loggers. See here.

IndexError: list index out of range and python

The way Python indexing works is that it starts at 0, so the first number of your list would be [0]. You would have to print[52], as the starting index is 0 and therefore line 53 is [52].

Subtract 1 from the value and you should be fine. :)

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111 check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null

Explicitly calling return in a function or not

Question was: Why is not (explicitly) calling return faster or better, and thus preferable?

There is no statement in R documentation making such an assumption.
The main page ?'function' says:

function( arglist ) expr
return(value)

Is it faster without calling return?

Both function() and return() are primitive functions and the function() itself returns last evaluated value even without including return() function.

Calling return() as .Primitive('return') with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return') call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }

bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }

maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])

# res object is then visualized
# R version 2.15

Function elapsed time comparison

The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.

Is it better without calling return?

Return is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.

# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
> 

It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.

R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.

Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.

It is not clear if it is better or not as standard user or analyst using R can not see the real difference.

My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?

Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?

Counting the number of elements with the values of x in a vector

There are different ways of counting a specific elements

library(plyr)
numbers =c(4,23,4,23,5,43,54,56,657,67,67,435,453,435,7,65,34,435)

print(length(which(numbers==435)))

#Sum counts number of TRUE's in a vector 
print(sum(numbers==435))
print(sum(c(TRUE, FALSE, TRUE)))

#count is present in plyr library 
#o/p of count is a DataFrame, freq is 1 of the columns of data frame
print(count(numbers[numbers==435]))
print(count(numbers[numbers==435])[['freq']])

Spring Boot - inject map from application.yml

Solution for pulling Map using @Value from application.yml property coded as multiline

application.yml

other-prop: just for demo 

my-map-property-name: "{\
         key1: \"ANY String Value here\", \  
         key2: \"any number of items\" , \ 
         key3: \"Note the Last item does not have comma\" \
         }"

other-prop2: just for demo 2 

Here the value for our map property "my-map-property-name" is stored in JSON format inside a string and we have achived multiline using \ at end of line

myJavaClass.java

import org.springframework.beans.factory.annotation.Value;

public class myJavaClass {

@Value("#{${my-map-property-name}}") 
private Map<String,String> myMap;

public void someRandomMethod (){
    if(myMap.containsKey("key1")) {
            //todo...
    } }

}

More explanation

  • \ in yaml it is Used to break string into multiline

  • \" is escape charater for "(quote) in yaml string

  • {key:value} JSON in yaml which will be converted to Map by @Value

  • #{ } it is SpEL expresion and can be used in @Value to convert json int Map or Array / list Reference

Tested in a spring boot project

How do I check if the mouse is over an element in jQuery?

Set a timeout on the mouseout to fadeout and store the return value to data in the object. Then onmouseover, cancel the timeout if there is a value in the data.

Remove the data on callback of the fadeout.

It is actually less expensive to use mouseenter/mouseleave because they do not fire for the menu when children mouseover/mouseout fire.

Oracle query to fetch column names

You can try this:

describe 'Table Name'

It will return all column names and data types

In Python, how do I iterate over a dictionary in sorted key order?

You can now use OrderedDict in Python 2.7 as well:

>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1),
...                  ('second', 2),
...                  ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]

Here you have the what's new page for 2.7 version and the OrderedDict API.

Equation for testing if a point is inside a circle

This is the same solution as mentioned by Jason Punyon, but it contains a pseudo-code example and some more details. I saw his answer after writing this, but I didn't want to remove mine.

I think the most easily understandable way is to first calculate the distance between the circle's center and the point. I would use this formula:

d = sqrt((circle_x - x)^2 + (circle_y - y)^2)

Then, simply compare the result of that formula, the distance (d), with the radius. If the distance (d) is less than or equal to the radius (r), the point is inside the circle (on the edge of the circle if d and r are equal).

Here is a pseudo-code example which can easily be converted to any programming language:

function is_in_circle(circle_x, circle_y, r, x, y)
{
    d = sqrt((circle_x - x)^2 + (circle_y - y)^2);
    return d <= r;
}

Where circle_x and circle_y is the center coordinates of the circle, r is the radius of the circle, and x and y is the coordinates of the point.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

If running beta software and you update the OS, make sure to get the latest Xcode beta also. This fixed it for me.

One time page refresh after first page load

Here is another solution with setTimeout, not perfect, but it works:

It requires a parameter in the current url, so just image the current url looks like this:

www.google.com?time=1

The following code make the page reload just once:

 // Reload Page Function //
    // get the time parameter //
        let parameter = new URLSearchParams(window.location.search);
          let time = parameter.get("time");
          console.log(time)//1
          let timeId;
          if (time == 1) {
    // reload the page after 0 ms //
           timeId = setTimeout(() => {
            window.location.reload();//
           }, 0);
   // change the time parameter to 0 //
           let currentUrl = new URL(window.location.href);
           let param = new URLSearchParams(currentUrl.search);
           param.set("time", 0);
   // replace the time parameter in url to 0; now it is 0 not 1 //
           window.history.replaceState({}, "", `${currentUrl.pathname}?${param}`);
        // cancel the setTimeout function after 0 ms //
           let currentTime = Date.now();
           if (Date.now() - currentTime > 0) {
            clearTimeout(timeId);
           }
          }

The accepted answer uses the least amount of code and is easy to understand. I just provided another solution to this.

Hope this helps others.

Print in one line dynamically

Or even simpler:

import time
a = 0
while True:
    print (a, end="\r")
    a += 1
    time.sleep(0.1)

end="\r" will overwrite from the beginning [0:] of the first print.

Remove Array Value By index in jquery

Your syntax is incorrect, you should either specify a hash:

hash = {abc: true, def: true, ghi: true};

Or an array:

arr = ['abc','def','ghi'];

You can effectively remove an item from a hash by simply setting it to null:

hash['def'] = null;
hash.def = null;

Or removing it entirely:

delete hash.def;

To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:

arr.splice(arr.indexOf("def"), 1);

This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:

arr.filter(function(item) { return item !== 'def'; });

This will create a new array with only elements that are not 'def'.

It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.

When do you use varargs in Java?

In Java doc of Var-Args it is quite clear the usage of var args:

http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

about usage it says:

"So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. "

Java integer to byte array

How about:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

The idea is not mine. I've taken it from some post on dzone.com.

python : list index out of range error while iteratively popping elements

x=[]
x = [int(i) for i in input().split()]
i = 0
    while i < len(x):
        print(x[i])
        if(x[i]%5)==0:
            del x[i]
        else:
            i += 1
print(*x)

Which HTML elements can receive focus?

The ally.js accessibility library provides an unofficial, test-based list here:

https://allyjs.io/data-tables/focusable.html

(NB: Their page doesn't say how often tests were performed.)

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

Greek would need UTF-8 on N column types: aß? ;)

How can I convert a date into an integer?

var dates = dates_as_int.map(function(dateStr) {
    return new Date(dateStr).getTime();
});

=>

[1468959781804, 1469029434776, 1469199218634, 1469457574527]

Update: ES6 version:

const dates = dates_as_int.map(date => new Date(date).getTime())

How to set all elements of an array to zero or any same value?

If your array is static or global it's initialized to zero before main() starts. That would be the most efficient option.

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

Multiple lines of text in UILabel

Swift 3
Set number of lines zero for dynamic text information, it will be useful for varying text.

var label = UILabel()
let stringValue = "A label\nwith\nmultiline text."
label.text = stringValue
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingTail // or .byWrappingWord
label.minimumScaleFactor = 0.8 . // It is not required but nice to have a minimum scale factor to fit text into label frame

enter image description here

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

How can I set the request header for curl?

Just use the -H parameter several times:

curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com

What does "export" do in shell programming?

it makes the assignment visible to subprocesses.

$ foo=bar
$ bash -c 'echo $foo'

$ export foo
$ bash -c 'echo $foo'
bar

if checkbox is checked, do this

I found out a crazy solution for dealing with this issue of checkbox not checked or checked here is my algorithm... create a global variable lets say var check_holder

check_holder has 3 states

  1. undefined state
  2. 0 state
  3. 1 state

If the checkbox is clicked,

$(document).on("click","#check",function(){
    if(typeof(check_holder)=="undefined"){
          //this means that it is the first time and the check is going to be checked
          //do something
          check_holder=1; //indicates that the is checked,it is in checked state
    }
    else if(check_holder==1){
          //do something when the check is going to be unchecked
          check_holder=0; //it means that it is not checked,it is in unchecked state
    }
     else if(check_holder==0){
            //do something when the check is going to be checked
            check_holder=1;//indicates that it is in a checked state
     }
});

The code above can be used in many situation to find out if a checkbox has been checked or not checked. The concept behind it is to save the checkbox states in a variable, ie when it is on,off. i Hope the logic can be used to solve your problem.

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

Stop and Start a service via batch or cmd file?

Using the return codes from net start and net stop seems like the best method to me. Try a look at this: Net Start return codes.

Remove trailing comma from comma-separated string

package com.app;

public class SiftNumberAndEvenNumber {

    public static void main(String[] args) {

        int arr[] = {1,2,3,4,5};
        int arr1[] = new int[arr.length];
        int shiftAmount=3;
        
        for(int i = 0; i < arr.length; i++){
            int newLocation = (i + (arr.length - shiftAmount)) % arr.length;
            arr1[newLocation] = arr[i];
            
        }
        for(int i=0;i<arr1.length;i++) {
            if(i==arr1.length-1) {
                System.out.print(arr1[i]);
            }else {
                System.out.print(arr1[i]+",");
            }
        }
        System.out.println();
        for(int i=0;i<arr1.length;i++) {
            if(arr1[i]%2==0) {
                System.out.print(arr1[i]+" ");
            }
        }
    }
}

How to increment a number by 2 in a PHP For Loop

You should use other variable:

 $m=0; 
 for($n=1; $n<=8; $n++): 
  $n = $n + $m;
  $m++;
  echo '<p>'. $n .'</p>';
 endfor;

Importing a function from a class in another file?

If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:

from FILE NAME import FUNCTION NAME

Note - the parts in capital letters are where you type the file name and function name.

Now you just use your function however it was meant to be.

Example:

FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py

def choose(a):
  from random import randint
  b = randint(0, len(a) - 1)
  c = a[b]
  return(c)

SCRIPT USING FUNCTION - saved wherever

from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))

OUTPUT WILL BE DOG, CAT, OR CHICKEN

Hoped this helped, now you can create function packs for download!

--------------------------------This is for Python 2.7-------------------------------------

What Ruby IDE do you prefer?

While TextMate is not an IDE in the classical sense, try the following in terminal to be 'wowed'

cd 'your-shiny-ruby-project'
mate .

It'll spawn up TextMate and the project drawer will list the contents of your project. Pretty awesome if you ask me.

Android - how do I investigate an ANR?

Whenever you're analyzing timing issues, debugging often does not help, as freezing the app at a breakpoint will make the problem go away.

Your best bet is to insert lots of logging calls (Log.XXX()) into the app's different threads and callbacks and see where the delay is at. If you need a stacktrace, create a new Exception (just instantiate one) and log it.

How to know when a web page was last updated?

01. Open the page for which you want to get the information.

02. Clear the address bar [where you type the address of the sites]:

and type or copy/paste from below:

javascript:alert(document.lastModified)

03. Press Enter or Go button.

How to get an Instagram Access Token

If you don't want to build your server side, like only developing on a client side (web app or a mobile app) , you could choose an Implicit Authentication .

As the document saying , first make a https request with

https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token

Fill in your CLIENT-ID and REDIRECT-URL you designated.

Then that's going to the log in page , but the most important thing is how to get the access token after the user correctly logging in.

After the user click the log in button with both correct account and password, the web page will redirect to the url you designated followed by a new access token.

http://your-redirect-uri#access_token=ACCESS-TOKEN

I'm not familiar with javascript , but in Android studio , that's an easy way to add a listener which listen to the event the web page override the url to the new url (redirect event) , then it will pass the redirect url string to you , so you can easily split it to get the access-token like:

String access_token = url.split("=")[1];

Means to break the url into the string array in each "=" character , then the access token obviously exists at [1].

What is the best way to iterate over a dictionary?

If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.

public new IEnumerator<T> GetEnumerator()
{
   return this.Values.GetEnumerator();
}

How to implement private method in ES6 class with Traceur

As Marcelo Lazaroni has already said,

Although currently there is no way to declare a method or property as private, ES6 modules are not in the global namespace. Therefore, anything that you declare in your module and do not export will not be available to any other part of your program, but will still be available to your module during run time.

But his example didn't show how the private method could access members of the instance of the class. Max shows us some good examples of how access instance members through binding or the alternative of using a lambda method in the constructor, but I would like to add one more simple way of doing it: passing the instance as a parameter to the private method. Doing it this way would lead Max's MyClass to look like this:

function myPrivateFunction(myClass) {
  console.log("My property: " + myClass.prop);
}

class MyClass() {
  constructor() {
    this.prop = "myProp";
  }
  testMethod() {
    myPrivateFunction(this);
  }
}
module.exports = MyClass;

Which way you do it really comes down to personal preference.

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

This really should be a comment to Brad Rippe's answer, but alas, not enough rep. That answer got me 90% of the way there. In my case, the installation and configuration of the databases put entries in the tnsnames.ora file for the databases I was running. First, I was able to connect to the database by setting the environment variables (Windows):

set ORACLE_SID=mydatabase
set ORACLE_HOME=C:\Oracle\product\11.2.0\dbhome_1

and then connecting using

sqlplus / as sysdba

Next, running the command from Brad Rippe's answer:

select value from v$parameter where name='service_names';

showed that the names didn't match exactly. The entries as created using Oracle's Database Configuration Assistant where originally:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase.mydomain.com)
    )
  ) 

The service name from the query was just mydatabase rather than mydatabase.mydomain.com. I edited the tnsnames.ora file to just the base name without the domain portion so they looked like this:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase)
    )
  ) 

I restarted the TNS Listener service (I often use lsnrctl stop and lsnrctl start from an administrator command window [or Windows Powershell] instead of the Services control panel, but both work.) After that, I was able to connect.

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

Thank you all, just to add that some process wont close unless the /F force switch is also send with TaskKill. Also with /T switch, all secondary threads of the process will be closed.

C:\>FOR /F "tokens=5 delims= " %P IN ('netstat -a -n -o ^|
 findstr :2002') DO TaskKill.exe /PID %P /T /F

For services it will be necessary to get the name of the service and execute:

sc stop ServiceName

How to find where gem files are installed

gem env works just like gem environment. Saves some typing.

# gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 2.0.14
  - RUBY VERSION: 2.0.0 (2014-02-24 patchlevel 451) [i686-linux]
  - INSTALLATION DIRECTORY: /usr/local/lib/ruby/gems/2.0.0
  - RUBY EXECUTABLE: /usr/local/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86-linux
  - GEM PATHS:
     - /usr/local/lib/ruby/gems/2.0.0
     - /root/.gem/ruby/2.0.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/

Find an element by class name, from a known parent element

var element = $("#parentDiv .myClassNameOfInterest")

Create a basic matrix in C (input by user !)

int rows, cols , i, j;
printf("Enter number of rows and cols for the matrix: \n");
scanf("%d %d",&rows, &cols);

int mat[rows][cols];

printf("enter the matrix:");

for(i = 0; i < rows ; i++)
    for(j = 0; j < cols; j++)
        scanf("%d", &mat[i][j]);

printf("\nThe Matrix is:\n");
for(i = 0; i < rows ; i++)
{
    for(j = 0; j < cols; j++)
    {
        printf("%d",mat[i][j]);
        printf("\t");
    }
    printf("\n");
}

}

File Upload in WebView

2019: This code worked for me (Tested on Androids 5 - 9).

package com.example.filechooser;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends Activity {

    // variables para manejar la subida de archivos
    private final static int FILECHOOSER_RESULTCODE = 1;
    private ValueCallback<Uri[]> mUploadMessage;

    // variable para manejar el navegador empotrado
    WebView mainWebView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // instanciamos el webview
        mainWebView = findViewById(R.id.main_web_view);

        // establecemos el cliente interno para que la navegacion no se salga de la aplicacion
        mainWebView.setWebViewClient(new MyWebViewClient());

        // establecemos el cliente chrome para seleccionar archivos
        mainWebView.setWebChromeClient(new MyWebChromeClient());

        // configuracion del webview
        mainWebView.getSettings().setJavaScriptEnabled(true);

        // cargamos la pagina
        mainWebView.loadUrl("https://example.com");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        // manejo de seleccion de archivo
        if (requestCode == FILECHOOSER_RESULTCODE) {

            if (null == mUploadMessage || intent == null || resultCode != RESULT_OK) {
                return;
            }

            Uri[] result = null;
            String dataString = intent.getDataString();

            if (dataString != null) {
                result = new Uri[]{ Uri.parse(dataString) };
            }

            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }


    // ====================
    // Web clients classes
    // ====================

    /**
     * Clase para configurar el webview
     */
    private class MyWebViewClient extends WebViewClient {

        // permite la navegacion dentro del webview
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }


    /**
     * Clase para configurar el chrome client para que nos permita seleccionar archivos
     */
    private class MyWebChromeClient extends WebChromeClient {

        // maneja la accion de seleccionar archivos
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

            // asegurar que no existan callbacks
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
            }

            mUploadMessage = filePathCallback;

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*"); // set MIME type to filter

            MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FILECHOOSER_RESULTCODE );

            return true;
        }
    }

}

Hope can help you.

Call a function from another file?

You can do this in 2 ways. First is just to import the specific function you want from file.py. To do this use

from file import function

Another way is to import the entire file

import file as fl

Then you can call any function inside file.py using

fl.function(a,b)

Send HTTP GET request with header

You do it exactly as you showed with this line:

get.setHeader("Content-Type", "application/x-zip");

So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.

LIKE vs CONTAINS on SQL Server

I think that CONTAINS took longer and used Merge because you had a dash("-") in your query adventure-works.com.

The dash is a break word so the CONTAINS searched the full-text index for adventure and than it searched for works.com and merged the results.

Android ImageView's onClickListener does not work

Same Silly thing happed with me.

I just copied one activity and pasted. Defined in Manifest.

Open from MainActivity.java but I was forgot that Copied Activity is getting some params in bundle and If I don't pass any params, just finished.

So My Activity is getting started but finished at same moment.

I had written Toast and found this silly mistake. :P

Facebook Graph API, how to get users email?

Assuming you've requested email permissions when the user logged in from your app and you have a valid token,

With the fetch api you can just

const token = "some_valid_token";
const response = await fetch(
        `https://graph.facebook.com/me?fields=email&access_token=${token}`
      );
const result = await response.json();

result will be:

{
    "id": "some_id",
    "email": "[email protected]"
}

id will be returned anyway.

You can add to the fields query param more stuff, but you need permissions for them if they are not on the public profile (name is public).

?fields=name,email,user_birthday&token=

https://developers.facebook.com/docs/facebook-login/permissions

Remove new lines from string and replace with one empty space

You can try below code will preserve any white-space and new lines in your text.

$str = "
put returns between paragraphs

for linebreak add 2 spaces at end

";

echo preg_replace( "/\r|\n/", "", $str );

powershell is missing the terminator: "

This can also occur when the path ends in a '' followed by the closing quotation mark. e.g. The following line is passed as one of the arguments and this is not right:

"c:\users\abc\"

instead pass that argument as shown below so that the last backslash is escaped instead of escaping the quotation mark.

"c:\users\abc\\"

What exactly should be set in PYTHONPATH?

You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYTHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH.

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

It can be a mathematical convention in the definition of an interval where square brackets mean "extremal inclusive" and round brackets "extremal exclusive".

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

Make the class serializable by implementing the interface java.io.Serializable.

  • java.io.Serializable - Marker Interface which does not have any methods in it.
  • Purpose of Marker Interface - to tell the ObjectOutputStream that this object is a serializable object.

Single vs double quotes in JSON

It truly solved my problem using eval function.

single_quoted_dict_in_string = "{'key':'value', 'key2': 'value2'}"
desired_double_quoted_dict = eval(single_quoted_dict_in_string)
# Go ahead, now you can convert it into json easily
print(desired_double_quoted_dict)

Creating an Arraylist of Objects

How to Creating an Arraylist of Objects.

Create an array to store the objects:

ArrayList<MyObject> list = new ArrayList<MyObject>();

In a single step:

list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 

or

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.

Simple (I think) Horizontal Line in WPF?

How about add this to your xaml:

<Separator/>

HTTP POST with Json on Body - Flutter/Dart

This would also work :

import 'package:http/http.dart' as http;

  sendRequest() async {

    Map data = {
       'apikey': '12345678901234567890'
    };

    var url = 'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
    http.post(url, body: data)
        .then((response) {
      print("Response status: ${response.statusCode}");
      print("Response body: ${response.body}");
    });  
  }

How to convert a time string to seconds?

import time
from datetime import datetime

t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())

result: 3.0

Using Node.JS, how do I read a JSON file into (server) memory?

The easiest way I have found to do this is to just use require and the path to your JSON file.

For example, suppose you have the following JSON file.

test.json

{
  "firstName": "Joe",
  "lastName": "Smith"
}

You can then easily load this in your node.js application using require

var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);

How to create a DataFrame from a text file in Spark

If you want to use the toDF method, you have to convert your RDD of Array[String] into a RDD of a case class. For example, you have to do:

case class Test(id:String,filed2:String)
val myFile = sc.textFile("file.txt")
val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Kinda late, but you need to access the original event, not the jQuery massaged one. Also, since these are multi-touch events, other changes need to be made:

$('#box').live('touchstart', function(e) {
  var xPos = e.originalEvent.touches[0].pageX;
});

If you want other fingers, you can find them in other indices of the touches list.

UPDATE FOR NEWER JQUERY:

$(document).on('touchstart', '#box', function(e) {
  var xPos = e.originalEvent.touches[0].pageX;
});

Set Google Maps Container DIV width and height 100%

This worked for me.

map_canvas {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}

How to create a file in Ruby

Try

File.open("out.txt", "w") do |f|     
  f.write(data_you_want_to_write)   
end

without using the

File.new "out.txt"

Javascript switch vs. if...else if...else

Answering in generalities:

  1. Yes, usually.
  2. See More Info Here
  3. Yes, because each has a different JS processing engine, however, in running a test on the site below, the switch always out performed the if, elseif on a large number of iterations.

Test site

How to apply !important using .css()?

You can do this:

$("#elem").css("cssText", "width: 100px !important;");

Using "cssText" as the property name and whatever you want added to the CSS as its value.

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

Select a Dictionary<T1, T2> with LINQ

The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.

class SomeObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

SomeObject[] objects = new SomeObject[]
{
    new SomeObject { ID = 1, Name = "Hello" },
    new SomeObject { ID = 2, Name = "World" }
};

Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);

Then objectDictionary[1] Would contain the value "Hello"

C# ListView Column Width Auto

It is also worth noting that ListView may not display as expected without first changing the property:

myListView.View = View.Details; // or View.List

For me Visual Studio seems to default it to View.LargeIcon for some reason so nothing appears until it is changed.

Complete code to show a single column in a ListView and allow space for a vertical scroll bar.

lisSerials.Items.Clear();
lisSerials.View = View.Details;
lisSerials.FullRowSelect = true;

// add column if not already present
if(lisSerials.Columns.Count==0)
{
    int vw = SystemInformation.VerticalScrollBarWidth;
    lisSerials.Columns.Add("Serial Numbers", lisSerials.Width-vw-5);
}

foreach (string s in stringArray)
{
    ListViewItem lvi = new ListViewItem(new string[] { s });
    lisSerials.Items.Add(lvi);
}

Count number of days between two dates

None of the previous answers (to this date) gives the correct difference in days between two dates.

The one that comes closest is by thatdankent. A full answer would convert to_i and then divide:

(Time.now.to_i - 23.hours.ago.to_i) / 86400
>> 0

(Time.now.to_i - 25.hours.ago.to_i) / 86400
>> 1

(Time.now.to_i - 1.day.ago.to_i) / 86400
>> 1

In the question's specific example, one should not parse to Date if the time passed is relevant. Use Time.parse instead.

Is it possible to Turn page programmatically in UIPageViewController?

Yes it is possible with the method:

- (void)setViewControllers:(NSArray *)viewControllers 
                 direction:(UIPageViewControllerNavigationDirection)direction 
                  animated:(BOOL)animated 
                completion:(void (^)(BOOL finished))completion;`

That is the same method used for setting up the first view controller on the page. Similar, you can use it to go to other pages.

Wonder why viewControllers is an array, and not a single view controller?

That's because a page view controller could have a "spine" (like in iBooks), displaying 2 pages of content at a time. If you display 1 page of content at a time, then just pass in a 1-element array.

An example in Swift:

pageContainer.setViewControllers([displayThisViewController], direction: .Forward, animated: true, completion: nil)

How do I check if a variable is of a certain type (compare two types) in C?

C is statically typed language. You can't declare a function which operate on type A or type B, and you can't declare variable which hold type A or type B. Every variable has an explicitly declared and unchangeable type, and you supposed to use this knowledge.

And when you want to know if void * points to memory representation of float or integer - you have to store this information somewhere else. The language is specifically designed not to care if char * points to something stored as int or char.

ASP.NET MVC Global Variables

You can put them in the Application:

Application["GlobalVar"] = 1234;

They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.

Flutter: Setting the height of the AppBar

In addition to @Cinn's answer, you can define a class like this

class MyAppBar extends AppBar with PreferredSizeWidget {
  @override
  get preferredSize => Size.fromHeight(50);

  MyAppBar({Key key, Widget title}) : super(
    key: key,
    title: title,
    // maybe other AppBar properties
  );
}

or this way

class MyAppBar extends PreferredSize {
  MyAppBar({Key key, Widget title}) : super(
    key: key,
    preferredSize: Size.fromHeight(50),
    child: AppBar(
      title: title,
      // maybe other AppBar properties
    ),
  );
}

and then use it instead of standard one

socket.emit() vs. socket.send()

In basic two way communication systems, socket.emit has proved to be more convincing and easy to use (personal experience) and is a part of Socket.IO which is primarily built for such purposes

Notepad++ Regular expression find and delete a line

Provide the following in the search dialog:

Find What: ^$\r\n
Replace With: (Leave it empty)

Click Replace All

How to Apply Mask to Image in OpenCV?

Well, this question appears on top of search results, so I believe we need code example here. Here's the Python code:

import cv2

def apply_mask(frame, mask):
    """Apply binary mask to frame, return in-place masked image."""
    return cv2.bitwise_and(frame, frame, mask=mask)

Mask and frame must be the same size, so pixels remain as-is where mask is 1 and are set to zero where mask pixel is 0.

And for C++ it's a little bit different:

cv::Mat inFrame; // Original (non-empty) image
cv::Mat mask; // Original (non-empty) mask

// ...

cv::Mat outFrame;  // Result output
inFrame.copyTo(outFrame, mask);

Using strtok with a std::string

Assuming that by "string" you're talking about std::string in C++, you might have a look at the Tokenizer package in Boost.

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

Creating NSData from NSString in Swift

Convert String to Data

extension String {
    func toData() -> Data {
        return Data(self.utf8)
    }
}

Convert Data to String

extension Data {
      func toString() -> String {
          return String(decoding: self, as: UTF8.self)
      }
   }

Adding asterisk to required fields in Bootstrap 3

This CSS worked for me:

.form-group.required.control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -10px;
}

and this HTML:

<div class="form-group required control-label">
  <label for="emailField">Email</label>
  <input type="email" class="form-control" id="emailField" placeholder="Type Your Email Address Here" />
</div>

Angular - ng: command not found

Guess You are running on Windows (To make @jowey's answer more straightforward).

  • Install Angular normally from your bash $ npm install -g @angular/cli@latest Next is to rearrange the PATHS to
  • NPM
  • Nodejs
  • Angular CLI

in System Environment Variables, the picture below shows the arrangement.

enter image description here

How can I dynamically switch web service addresses in .NET without a recompile?

If you are fetching the URL from a database you can manually assign it to the web service proxy class URL property. This should be done before calling the web method.

If you would like to use the config file, you can set the proxy classes URL behavior to dynamic.

How to add extra whitespace in PHP?

pre is your friend.

<pre> 
<?php // code goes here

?>
</pre>

Or you can "View Source" in your browser. (Ctrl+U for most browser.)

Inline style to act as :hover in CSS

A simple solution:

   <a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>

Or

<script>
 /** Change the style **/
 function overStyle(object){
    object.style.color = 'orange';
    // Change some other properties ...
 }

 /** Restores the style **/
 function outStyle(object){
    object.style.color = 'orange';
    // Restore the rest ...
 }
</script>

<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>

Using Mysql in the command line in osx - command not found?

modify your bash profile as follows <>$vim ~/.bash_profile export PATH=/usr/local/mysql/bin:$PATH Once its saved you can type in mysql to bring mysql prompt in your terminal.

What does "javascript:void(0)" mean?

Web Developers use javascript:void(0) because it is the easiest way to prevent the default behavior of a tag. void(*anything*) returns undefined and it is a falsy value. and returning a falsy value is like return false in onclick event of a tag that prevents its default behavior.

So I think javascript:void(0) is the simplest way to prevent the default behavior of a tag.

How to use ConcurrentLinkedQueue?

Just use it as you would a non-concurrent collection. The Concurrent[Collection] classes wrap the regular collections so that you don't have to think about synchronizing access.

Edit: ConcurrentLinkedList isn't actually just a wrapper, but rather a better concurrent implementation. Either way, you don't have to worry about synchronization.

Errno 13 Permission denied Python

If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates... I hope someone will help this info.

SQL Server Format Date DD.MM.YYYY HH:MM:SS

A quick way to do it in sql server 2012 is as follows:

SELECT FORMAT(GETDATE() , 'dd/MM/yyyy HH:mm:ss')

Onclick event to remove default value in a text input field

This is the right, cross-browser way to do it :

<input type="text" value="Enter Your Name" onfocus="if(this.value  == 'Enter Your Name') { this.value = ''; } " onblur="if(this.value == '') { this.value = 'Enter Your Name'; } " />

Vuex - passing multiple parameters to mutation

In simple terms you need to build your payload into a key array

payload = {'key1': 'value1', 'key2': 'value2'}

Then send the payload directly to the action

this.$store.dispatch('yourAction', payload)

No change in your action

yourAction: ({commit}, payload) => {
  commit('YOUR_MUTATION',  payload )
},

In your mutation call the values with the key

'YOUR_MUTATION' (state,  payload ){
  state.state1 = payload.key1
  state.state2 =  payload.key2
},

What is the meaning of prepended double colon "::"?

"::" represents scope resolution operator. Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.

Simple if else onclick then do?

You may use jQuery in it like

$('#yesh').click(function(){
     *****HERE GOES THE FUNCTION*****
});

Besides jQuery is easy to use.

You can make changes in colors etc using simple jQUery or Javascript.

Windows Task Scheduler doesn't start batch file task

I had the same problem. I believe it's a privilege problem. If you have "Run only when user is logged on" selected, then it won't happen.

You've hopefully figured it out by now, but I wanted to register it here for the next person who has wasted hours on this.

Online Internet Explorer Simulators

I just realized that there's yet another option. I've heard a lot of good things about this service: Litmus Alkaline.

"Alkaline tests your website designs across 17 different Windows browsers right from your Mac desktop in seconds. No need for virtual machines, Windows licenses, or any messing around with Windows Update."

Why is PHP session_destroy() not working?

If you need to clear the values of $_SESSION, set the array equal to an empty array:

$_SESSION = array();

Of course, you can't access the values of $_SESSION on another page once you call session_destroy, so it doesn't matter that much.

Try the following:

session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable

Error converting data types when importing from Excel to SQL Server 2008

There seems to be a really easy solution when dealing with data type issues.

Basically, at the end of Excel connection string, add ;IMEX=1;"

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\YOURSERVER\shared\Client Projects\FOLDER\Data\FILE.xls;Extended Properties="EXCEL 8.0;HDR=YES;IMEX=1";

This will resolve data type issues such as columns where values are mixed with text and numbers.

To get to connection property, right click on Excel connection manager below control flow and hit properties. It'll be to the right under solution explorer. Hope that helps.

Javascript Regex: How to put a variable inside a regular expression?

You can use the RegExp object:

var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);

Then you can construct regexstring in any way you want.

You can read more about it here.

What is the equivalent to getLastInsertId() in Cakephp?

There are several methods to get last inserted primary key id while using save method

$this->loadModel('Model');
$this->Model->save($this->data);

This will return last inserted id of the model current model

$this->Model->getLastInsertId();
$this->Model-> getInsertID();

This will return last inserted id of model with given model name

$this->Model->id;

This will return last inserted id of last loaded model

$this->id;

SignalR Console app example

First of all, you should install SignalR.Host.Self on the server application and SignalR.Client on your client application by nuget :

PM> Install-Package SignalR.Hosting.Self -Version 0.5.2

PM> Install-Package Microsoft.AspNet.SignalR.Client

Then add the following code to your projects ;)

(run the projects as administrator)

Server console app:

using System;
using SignalR.Hubs;

namespace SignalR.Hosting.Self.Samples {
    class Program {
        static void Main(string[] args) {
            string url = "http://127.0.0.1:8088/";
            var server = new Server(url);

            // Map the default hub url (/signalr)
            server.MapHubs();

            // Start the server
            server.Start();

            Console.WriteLine("Server running on {0}", url);

            // Keep going until somebody hits 'x'
            while (true) {
                ConsoleKeyInfo ki = Console.ReadKey(true);
                if (ki.Key == ConsoleKey.X) {
                    break;
                }
            }
        }

        [HubName("CustomHub")]
        public class MyHub : Hub {
            public string Send(string message) {
                return message;
            }

            public void DoSomething(string param) {
                Clients.addMessage(param);
            }
        }
    }
}

Client console app:

using System;
using SignalR.Client.Hubs;

namespace SignalRConsoleApp {
    internal class Program {
        private static void Main(string[] args) {
            //Set connection
            var connection = new HubConnection("http://127.0.0.1:8088/");
            //Make proxy to hub based on hub name on server
            var myHub = connection.CreateHubProxy("CustomHub");
            //Start connection

            connection.Start().ContinueWith(task => {
                if (task.IsFaulted) {
                    Console.WriteLine("There was an error opening the connection:{0}",
                                      task.Exception.GetBaseException());
                } else {
                    Console.WriteLine("Connected");
                }

            }).Wait();

            myHub.Invoke<string>("Send", "HELLO World ").ContinueWith(task => {
                if (task.IsFaulted) {
                    Console.WriteLine("There was an error calling send: {0}",
                                      task.Exception.GetBaseException());
                } else {
                    Console.WriteLine(task.Result);
                }
            });

            myHub.On<string>("addMessage", param => {
                Console.WriteLine(param);
            });

            myHub.Invoke<string>("DoSomething", "I'm doing something!!!").Wait();


            Console.Read();
            connection.Stop();
        }
    }
}

Which Python memory profiler is recommended?

I'm developing a memory profiler for Python called memprof:

http://jmdana.github.io/memprof/

It allows you to log and plot the memory usage of your variables during the execution of the decorated methods. You just have to import the library using:

from memprof import memprof

And decorate your method using:

@memprof

This is an example on how the plots look like:

enter image description here

The project is hosted in GitHub:

https://github.com/jmdana/memprof

Finding rows containing a value (or values) in any column

Here's a dplyr option:

library(dplyr)

# across all columns:
df %>% filter_all(any_vars(. %in% c('M017', 'M018')))

# or in only select columns:
df %>% filter_at(vars(col1, col2), any_vars(. %in% c('M017', 'M018')))                                                                                                     

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions: