Programs & Examples On #Mkreversegeocoder

The MKReverseGeocoder class provides services for converting a map coordinate (specified as a latitude/longitude pair) into information about that coordinate, such as the country, city, or street. A reverse geocoder object is a single-shot object that works with a network-based map service to look up placemark information for its specified coordinate value.

Arduino COM port doesn't work

Did you install the drivers? See the Arduino installation instructions under #4. I don't know that machine but I doubt it doesn't have any COM ports.

Insert ellipsis (...) into HTML tag if content too wide

Just like @acSlater I couldn't find something for what I needed so I rolled my own. Sharing in case anyone else can use:

Method:
ellipsisIfNecessary(mystring,maxlength);
Usage:
trimmedString = ellipsisIfNecessary(mystring,50);
Code and Demo Link: https://gist.github.com/cemerson/10368014

.ps1 cannot be loaded because the execution of scripts is disabled on this system

There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.

Look in your Windows directory for System32 and SysWOW64.

Repeat these steps for each directory:

  1. Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
  2. Check the current setting for ExecutionPolicy:

    Get-ExecutionPolicy -List

  3. Set the ExecutionPolicy for the level and scope you want, for example:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.

You can read a lot more here: Running Windows PowerShell Scripts

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

It's described on the Angular tutorial: https://angular.io/tutorial/toh-pt1#the-missing-formsmodule

You have to import FormsModule and add it to imports in your @NgModule declaraction.

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    DynamicConfigComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

How to get multiple counts with one SQL query?

One way which works for sure

SELECT a.distributor_id,
    (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
    (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
    (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM (SELECT DISTINCT distributor_id FROM myTable) a ;

EDIT:
See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @Taryn?'s answer. I'm leaving this so people can understand their options.

How do you run CMD.exe under the Local System Account?

if you can write a batch file that does not need to be interactive, try running that batch file as a service, to do what needs to be done.

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

The error you are getting is either because you are doing TO_DATE on a column that's already a date, and you're using a format mask that is different to your nls_date_format parameter[1] or because the event_occurrence column contains data that isn't a number.

You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.

And fix the datatype of that column to make sure you can only store numbers.



[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask) is: TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)

Generally, the default nls_date_format parameter is set to dd-MON-yy, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.

Binary search (bisection) in Python

Simplest is to use bisect and check one position back to see if the item is there:

def binary_search(a,x,lo=0,hi=-1):
    i = bisect(a,x,lo,hi)
    if i == 0:
        return -1
    elif a[i-1] == x:
        return i-1
    else:
        return -1

A child container failed during start java.util.concurrent.ExecutionException

This issue might also be caused by a broken Maven repository.

I observe the SEVERE: A child container failed during start message from time to time when working with Eclipse. My Eclipse workspace has several projects. Some of the projects have common external dependencies. If Maven repository is empty (or I add new dependencies into pom.xml files), Eclipse starts downloading libraries specified in pom.xml into Maven repository. And Eclipse does that in parallel for several projects in the workspace. It might happen that several Eclipse threads would be downloading the same file simultaneously into the same place in Maven repository. As a result, this file becomes corrupted.

So, this is how you could resolve the issue.

  1. Close your Eclipse.
  2. If you know which specific jar-file is broken in Maven repository, then delete that file.
  3. If you do not know which file is broken in Maven repository, then delete the whole repository (rm -rf $HOME/.m2).
  4. For each project, run mvn package in the command line. It is important to run the command for each project one-by-one, not in parallel; thus, you ensure that only one instance of Maven runs each time.
  5. Open your Eclipse.

How to remove class from all elements jquery

The best to remove a class in jquery from all the elements is to target via element tag. e.g.,

$("div").removeClass("highlight");

How to remove all MySQL tables from the command-line without DROP database permissions?

The @Devart's version is correct, but here are some improvements to avoid having error. I've edited the @Devart's answer, but it was not accepted.

SET FOREIGN_KEY_CHECKS = 0;
SET GROUP_CONCAT_MAX_LEN=32768;
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables
  FROM information_schema.tables
  WHERE table_schema = (SELECT DATABASE());
SELECT IFNULL(@tables,'dummy') INTO @tables;

SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;

This script will not raise error with NULL result in case when you already deleted all tables in the database by adding at least one nonexistent - "dummy" table.

And it fixed in case when you have many tables.

And This small change to drop all view exist in the Database

SET FOREIGN_KEY_CHECKS = 0;
SET GROUP_CONCAT_MAX_LEN=32768;
SET @views = NULL;
SELECT GROUP_CONCAT('`', TABLE_NAME, '`') INTO @views
  FROM information_schema.views
  WHERE table_schema = (SELECT DATABASE());
SELECT IFNULL(@views,'dummy') INTO @views;

SET @views = CONCAT('DROP VIEW IF EXISTS ', @views);
PREPARE stmt FROM @views;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;

It assumes that you run the script from Database you want to delete. Or run this before:

USE REPLACE_WITH_DATABASE_NAME_YOU_WANT_TO_DELETE;

Thank you to Steve Horvath to discover the issue with backticks.

mappedBy reference an unknown target entity property

I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.

If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany annotation with the 'mappedBy' property, it also means that the other side holding the @ManyToOne annotation with the @JoinColumn is the 'owner' of this bi-directional relationship.

Also, mappedBy takes in the instance name (mCustomer in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).

BONUS : Also, look into the orphanRemoval property of @OneToMany annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.

Enabling SSL with XAMPP

Found the answer. In the file xampp\apache\conf\extra\httpd-ssl.conf, under the comment SSL Virtual Host Context pages on port 443 meaning https is looked up under different document root.

Simply change the document root to the same one and problem is fixed.

How to get progress from XMLHttpRequest

If you have access to your apache install and trust third-party code, you can use the apache upload progress module (if you use apache; there's also a nginx upload progress module).

Otherwise, you'd have to write a script that you can hit out of band to request the status of the file (checking the filesize of the tmp file for instance).

There's some work going on in firefox 3 I believe to add upload progress support to the browser, but that's not going to get into all the browsers and be widely adopted for a while (more's the pity).

Prevent textbox autofill with previously entered values

Trying from the CodeBehind:

Textbox1.Attributes.Add("autocomplete", "off");

Remove scroll bar track from ScrollView in Android

try this is your activity onCreate:

ScrollView sView = (ScrollView)findViewById(R.id.deal_web_view_holder);
// Hide the Scollbar
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);

http://developer.android.com/reference/android/view/View.html#setVerticalScrollBarEnabled%28boolean%29

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

For any complex application, I suggest to use an lxc container. lxc containers are 'something in the middle between a chroot on steroids and a full fledged virtual machine'.

For example, here's a way to build 32-bit wine using lxc on an Ubuntu Trusty system:

sudo apt-get install lxc lxc-templates
sudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty
sudo lxc-start -n my32bitbox
# login as yourself
sudo sh -c "sed s/deb/deb-src/ /etc/apt/sources.list >> /etc/apt/sources.list"
sudo apt-get install devscripts
sudo apt-get build-dep wine1.7
apt-get source wine1.7
cd wine1.7-*
debuild -eDEB_BUILD_OPTIONS="parallel=8" -i -us -uc -b
shutdown -h now   # to exit the container

Here is the wiki page about how to build 32-bit wine on a 64-bit host using lxc.

Rails 4: assets not loading in production

For Rails 5, you should enable the follow config code:

config.public_file_server.enabled = true

By default, Rails 5 ships with this line of config:

config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

Hence, you will need to set the environment variable RAILS_SERVE_STATIC_FILES to true.

Why can't Python find shared objects that are in directories in sys.path?

For me what works here is to using a version manager such as pyenv, which I strongly recommend to get your project environments and package versions well managed and separate from that of the operative system.

I had this same error after an OS update, but was easily fixed with pyenv install 3.7-dev (the version I use).

cURL equivalent in Node.js?

You might want to try using something like this

curl = require('node-curl');
curl('www.google.com', function(err) {
  console.info(this.status);
  console.info('-----');
  console.info(this.body);
  console.info('-----');
  console.info(this.info('SIZE_DOWNLOAD'));
});

How do I set <table> border width with CSS?

<table style="border: 5px solid black">

This only adds a border around the table.

If you want same border through CSS then add this rule:

table tr td { border: 5px solid black; }

and one thing for HTML table to avoid spaces

<table cellspacing="0" cellpadding="0">

How do I execute multiple SQL Statements in Access' Query Editor?

You might find it better to use a 3rd party program to enter the queries into Access such as WinSQL I think from memory WinSQL supports multiple queries via it's batch feature.

I ultimately found it easier to just write a program in perl to do bulk INSERTS into an Access via ODBC. You could use vbscript or any language that supports ODBC though.

You can then do anything you like and have your own complicated logic to handle the importing.

Checking for Undefined In React

What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

componentWillReceiveProps(nextProps) {

    if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
       console.log("new title is", nextProps.blog.title);
       console.log("new body content is", nextProps.blog.content["body"]);
       this.setState({
           title: nextProps.blog.title,
           body: nextProps.blog.content["body"]
       })
    }
}

You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

In order to check for undefined, you can also use the typeof operator like

typeof nextProps.blog.content != "undefined"

How to insert an item into a key/value pair object?

I would use the Dictionary<TKey, TValue> (so long as each key is unique).

EDIT: Sorry, realised you wanted to add it to a specific position. My bad. You could use a SortedDictionary but this still won't let you insert.

Is SMTP based on TCP or UDP?

In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.

As defined in RFC 821, RFC 2821, and RFC 5321:

SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.

In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.

In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.


The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.

Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.

How can I view a git log of just one user's commits?

Show n number of logs for x user in colour by adding this little snippet in your .bashrc file.

gitlog() {
    if [ "$1" ] && [ "$2" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1" --author="$2"
    elif [ "$1" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1"
    else
        git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order
    fi
}

alias l=gitlog

To show the last 10 commits by Frank:

l 10 frank

To show the last 20 commits by anyone:

l 20

How to pass a variable from Activity to Fragment, and pass it back?

To pass info to a fragment , you setArguments when you create it, and you can retrieve this argument later on the method onCreate or onCreateView of your fragment.

On the newInstance function of your fragment you add the arguments you wanna send to it:

/**
 * 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;
}

Then inside the fragment on the method onCreate or onCreateView you can retrieve the arguments like this:

Bundle args = getArguments();
int index = args.getInt("index", 0);

If you want now communicate from your fragment with your activity (sending or not data), you need to use interfaces. The way you can do this is explained really good in the documentation tutorial of communication between fragments. Because all fragments communicate between each other through the activity, in this tutorial you can see how you can send data from the actual fragment to his activity container to use this data on the activity or send it to another fragment that your activity contains.

Documentation tutorial:

http://developer.android.com/training/basics/fragments/communicating.html

How to make button look like a link?

If you don't mind using twitter bootstrap I suggest you simply use the link class.

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">_x000D_
<button type="button" class="btn btn-link">Link</button>
_x000D_
_x000D_
_x000D_

I hope this helps somebody :) Have a nice day!

Is there a portable way to get the current username in Python?

Combined pwd and getpass approach, based on other answers:

try:
  import pwd
except ImportError:
  import getpass
  pwd = None

def current_user():
  if pwd:
    return pwd.getpwuid(os.geteuid()).pw_name
  else:
    return getpass.getuser()

Any tools to generate an XSD schema from an XML instance document?

If all you want is XSD, LiquidXML has a free version that does XSDs, and its got a GUI to it so you can tweak the XSD if you like. Anyways nowadays I write my own XSDs by hand, but its all thanks to this app.

http://www.liquid-technologies.com/

How can I have a newline in a string in sh?

What I did based on the other answers was

NEWLINE=$'\n'
my_var="__between eggs and bacon__"
echo "spam${NEWLINE}eggs${my_var}bacon${NEWLINE}knight"

# which outputs:
spam
eggs__between eggs and bacon__bacon
knight

Run Python script at startup in Ubuntu

Put this in /etc/init (Use /etc/systemd in Ubuntu 15.x)

mystartupscript.conf

start on runlevel [2345]
stop on runlevel [!2345]

exec /path/to/script.py

By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.

manual starting/stopping is done with sudo service mystartupscript start and sudo service mystartupscript stop

Add Insecure Registry to Docker

Creating /etc/docker/daemon.json file and adding the below content and then doing a docker restart on CentOS 7 resolved the issue.

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

Split Div Into 2 Columns Using CSS

This works good for me. I have divided the screen into two halfs: 20% and 80%:

<div style="width: 20%; float:left">
   #left content in here
</div>

<div style="width: 80%; float:right">
   #right content in there
</div>

How to switch from POST to GET in PHP CURL

Solved: The problem lies here:

I set POST via both _CUSTOMREQUEST and _POST and the _CUSTOMREQUEST persisted as POST while _POST switched to _HTTPGET. The Server assumed the header from _CUSTOMREQUEST to be the right one and came back with a 411.

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');

Laravel - Form Input - Multiple select for a one to many relationship

@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.

On your controller

$dogs = Dog::lists('name', 'id');

On customer create view you can use.

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}

Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}

Update For Laravel 5.1

The lists method now returns a Collection. Upgrading To 5.1.0

{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}

How do I get the unix timestamp in C as an int?

For 32-bit systems:

fprintf(stdout, "%u\n", (unsigned)time(NULL)); 

For 64-bit systems:

fprintf(stdout, "%lu\n", (unsigned long)time(NULL)); 

Java Map equivalent in C#

You can index Dictionary, you didn't need 'get'.

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

An efficient way to test/get values is TryGetValue (thanx to Earwicker):

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

With this method you can fast and exception-less get values (if present).

Resources:

Dictionary-Keys

Try Get Value

Has anyone gotten HTML emails working with Twitter Bootstrap?

I apologize for resurecting this old thread, but I just wanted to let everyone know there is a very close Bootstrap like CSS framework specifically created for email styling, here is the link: http://zurb.com/ink/

Hope it helps someone.

Ninja edit: It has since been renamed to Foundation for Emails and the new link is: https://foundation.zurb.com/emails.html

Silent but deadly edit: New link https://get.foundation/emails.html

Best way to convert an ArrayList to a string

In Java 8 or later:

String listString = String.join(", ", list);

In case the list is not of type String, a joining collector can be used:

String listString = list.stream().map(Object::toString)
                        .collect(Collectors.joining(", "));

Default string initialization: NULL or Empty?

I think there's no reason not to use null for an unassigned (or at this place in a program flow not occurring) value. If you want to distinguish, there's ==null. If you just want to check for a certain value and don't care whether it's null or something different, String.Equals("XXX",MyStringVar) does just fine.

How do I write out a text file in C# with a code page other than UTF-8?

You can have something like this

 switch (EncodingFormat.Trim().ToLower())
    {
        case "utf-8":
            File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, new UTF8Encoding(false), convertToCSV(result, fileName)));
            break;
        case "utf-8+bom":
            File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, new UTF8Encoding(true), convertToCSV(result, fileName)));
            break;
        case "ISO-8859-1":
            File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, Encoding.GetEncoding("iso-8859-1"), convertToCSV(result, fileName)));
            break;
        case ..............
    }

Error installing mysql2: Failed to build gem native extension

download the right version of mysqllib.dll then copy it to ruby bin really works for me. Follow this link plases mysql2 gem compiled for wrong mysql client library

How to get the xml node value in string

These posts helped me get past a couple of issues I had creating a CLR Stored Procedure with Restful API call against Infor M3 API.

The XML Result from these API's look like this for my code below:

miResult xmlns="http://lawson.com/m3/miaccess">
    <Program>MMS200MI</Program>
    <Transaction>Get</Transaction>
    <Metadata>...</Metadata>
    <MIRecord>
        <RowIndex>0</RowIndex>
        <NameValue>
            <Name>STAT</Name>
            <Value>20</Value>
        </NameValue>
        <NameValue>
            <Name>ITNO</Name>
            <Value>ITEM123</Value>
        </NameValue>
        <NameValue>
            <Name>ITDS</Name>
            <Value>ITEM DESCRIPTION 123 </Value>
        </NameValue>
...

The CLR C# Code to accomplish listing out the Resultset from the API works as shown below:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using Microsoft.SqlServer.Server;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void CallM3API_Test1()
    {
        SqlPipe pipe_msg = SqlContext.Pipe;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://M3Server.domain.com:12345/m3api-rest/execute/MMS200MI/Get?ITNO=ITEM123");

            request.Method = "Get";
            request.ContentLength = 0;

            request.Credentials = new NetworkCredential("[email protected]", "MyPassword");
            request.ContentType = "application/xml";
            request.Accept = "application/xml";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                    using (Stream receiveStream = response.GetResponseStream())
                    {
                        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                        {
                            string strContent = readStream.ReadToEnd();
                            XmlDocument xdoc = new XmlDocument();
                            xdoc.LoadXml(strContent);
                            try
                            {
                                SqlPipe pipe = SqlContext.Pipe;

                                //Define Output Columns and Max Length of each Column in the Resultset    
                                SqlMetaData[] cols = new SqlMetaData[2];
                                cols[0] = new SqlMetaData("Name", SqlDbType.NVarChar, 50);
                                cols[1] = new SqlMetaData("Value", SqlDbType.NVarChar, 120);
                                SqlDataRecord record = new SqlDataRecord(cols);

                                pipe.SendResultsStart(record);

                                XmlNodeList nodeList = xdoc.GetElementsByTagName("NameValue");
                                //List ALL Output Names + Values
                                foreach (XmlNode nodeRes in nodeList)
                                {
                                    record.SetSqlString(0, nodeRes["Name"].InnerText);
                                    record.SetSqlString(1, nodeRes["Value"].InnerText);

                                    pipe.SendResultsRow(record);
                                }

                                pipe.SendResultsEnd();
                            }
                            catch (Exception ex)
                            {
                                SqlContext.Pipe.Send("Error (readStream): " + ex.Message);
                            }
                        }
                    }
            }
        }
        catch (Exception ex)
        {
            SqlContext.Pipe.Send("Error (CallM3API_Test1): " + ex.Message);

        }
    }
}

Hopefully this provides helpful.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

No need for a StringBuilder:

string path = @"c:\hereIAm.txt";
if (!File.Exists(path)) 
{
    // Create a file to write to.
    using (StreamWriter sw = File.CreateText(path)) 
    {
        sw.WriteLine("Here");
        sw.WriteLine("I");
        sw.WriteLine("am.");
    }    
} 

But of course you can use the StringBuilder to create all lines and write them to the file at once.

sw.Write(stringBuilder.ToString());

StreamWriter.Write Method (String) (.NET Framework 1.1)

Writing Text to a File (.NET Framework 1.1)

Node.js: printing to console without a trailing newline?

util.print can be used also. Read: http://nodejs.org/api/util.html#util_util_print

util.print([...])# A synchronous output function. Will block the process, cast each argument to a string then output to stdout. Does not place newlines after each argument.

An example:

// get total length
var len = parseInt(response.headers['content-length'], 10);
var cur = 0;

// handle the response
response.on('data', function(chunk) {
  cur += chunk.length;
  util.print("Downloading " + (100.0 * cur / len).toFixed(2) + "% " + cur + " bytes\r");
});

Stateless vs Stateful

Money transfered online form one account to another account is stateful, because the receving account has information about the sender. Handing over cash from a person to another person, this transaction is statless, because after cash is recived the identity of the giver is not there with the cash.

Get column index from label in a data frame

Following on from chimeric's answer above:

To get ALL the column indices in the df, so i used:

which(!names(df)%in%c()) 

or store in a list:

indexLst<-which(!names(df)%in%c())

Android - How to regenerate R class?

For me, it was a String value Resource not being defined … after I added it by hand to Strings.xml, the R class was automagically regenerated!

How can I get the current user's username in Bash?

The current user's username can be gotten in pure Bash with the ${parameter@operator} parameter expansion (introduced in Bash 4.4):

$ : \\u
$ printf '%s\n' "${_@P}"

The : built-in (synonym of true) is used instead of a temporary variable by setting the last argument, which is stored in $_. We then expand it (\u) as if it were a prompt string with the P operator.

This is better than using $USER, as $USER is just a regular environmental variable; it can be modified, unset, etc. Even if it isn't intentionally tampered with, a common case where it's still incorrect is when the user is switched without starting a login shell (su's default).

Partition Function COUNT() OVER possible using DISTINCT

I use a solution that is similar to that of David above, but with an additional twist if some rows should be excluded from the count. This assumes that [UserAccountKey] is never null.

-- subtract an extra 1 if null was ranked within the partition,
-- which only happens if there were rows where [Include] <> 'Y'
dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end asc
) 
+ dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end desc
)
- max(case when [Include] = 'Y' then 0 else 1 end) over (partition by [Mth])
- 1

An SQL Fiddle with an extended example can be found here.

How to fire an event when v-model changes?

This happens because your click handler fires before the value of the radio button changes. You need to listen to the change event instead:

<input 
  type="radio" 
  name="optionsRadios" 
  id="optionsRadios2" 
  value=""
  v-model="srStatus" 
  v-on:change="foo"> //here

Also, make sure you really want to call foo() on ready... seems like maybe you don't actually want to do that.

ready:function(){
    foo();
},

Javascript / Chrome - How to copy an object from the webkit inspector as code

You can copy an object to your clip board using copy(JSON.stringify(Object_Name)); in the console.

Eg:- Copy & Paste the below code in your console and press ENTER. Now, try to paste(CTRL+V for Windows or CMD+V for mac) it some where else and you will get {"name":"Daniel","age":25}

var profile = {
    name: "Daniel",
    age: 25
};

copy(JSON.stringify(profile));

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

PHP Redirect with POST data

I'm aware the question is php oriented, but the best way to redirect a POST request is probably using .htaccess, ie:

RewriteEngine on
RewriteCond %{REQUEST_URI} string_to_match_in_url
RewriteCond %{REQUEST_METHOD} POST
RewriteRule ^(.*)$ https://domain.tld/$1 [L,R=307]

Explanation:

By default, if you want to redirect request with POST data, browser redirects it via GET with 302 redirect. This also drops all the POST data associated with the request. Browser does this as a precaution to prevent any unintentional re-submitting of POST transaction.

But what if you want to redirect anyway POST request with it’s data? In HTTP 1.1, there is a status code for this. Status code 307 indicates that the request should be repeated with the same HTTP method and data. So your POST request will be repeated along with it’s data if you use this status code.

SRC

Set value to an entire column of a pandas dataframe

Assuming your Data frame is like 'Data' you have to consider if your data is a string or an integer. Both are treated differently. So in this case you need be specific about that.

import pandas as pd

data = [('001','xxx'), ('002','xxx'), ('003','xxx'), ('004','xxx'), ('005','xxx')]

df = pd.DataFrame(data,columns=['issueid', 'industry'])

print("Old DataFrame")
print(df)

df.loc[:,'industry'] = str('yyy')

print("New DataFrame")
print(df)

Now if want to put numbers instead of letters you must create and array

list_of_ones = [1,1,1,1,1]
df.loc[:,'industry'] = list_of_ones
print(df)

Or if you are using Numpy

import numpy as np
n = len(df)
df.loc[:,'industry'] = np.ones(n)
print(df)

Bootstrap 3 modal responsive

I had the same issue I have resolved by adding a media query for @screen-xs-min in less version under Modals.less

@media (max-width: @screen-xs-min) {
  .modal-xs { width: @modal-sm; }
}

How to access the content of an iframe with jQuery?

You have to use the contents() method:

$("#myiframe").contents().find("#myContent")

Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

API Doc: https://api.jquery.com/contents/

Groovy Shell warning "Could not open/create prefs root node ..."

I was getting the following message:

Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002

and it was gone after creating one of these registry keys, mine is 64 bit so I tried only that.

32 bit Windows
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

64 bit Windows
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

How to set Status Bar Style in Swift 3

iOS 11.2

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UINavigationBar.appearance().barStyle = .black

    return true
}

How to count number of unique values of a field in a tab-delimited text file?

awk -F '\t' '{ a[$1]++ } END { for (n in a) print n, a[n] } ' test.csv

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

There is no b['body'] in python. You have to use get_payload.

if isinstance(mailEntity.get_payload(), list):
    for eachPayload in mailEntity.get_payload():
        ...do things you want...
        ...real mail body is in eachPayload.get_payload()...
else:
    ...means there is only text/plain part....
    ...use mailEntity.get_payload() to get the body...

Good Luck.

Python: how can I check whether an object is of type datetime.date?

According to documentation class date is a parent for class datetime. And isinstance() method will give you True in all cases. If you need to distinguish datetime from date you should check name of the class

import datetime

datetime.datetime.now().__class__.__name__ == 'date' #False
datetime.datetime.now().__class__.__name__ == 'datetime' #True
datetime.date.today().__class__.__name__ == 'date' #True
datetime.date.today().__class__.__name__ == 'datetime' #False

I've faced with this problem when i have different formatting rules for dates and dates with time

OpenCV - DLL missing, but it's not?

Just for your information,after add the "PATH",for my win7 i need to reboot it to get it work.

Don't understand why UnboundLocalError occurs (closure)

You need to use the global statement so that you are modifying the global variable counter, instead of a local variable:

counter = 0

def increment():
  global counter
  counter += 1

increment()

If the enclosing scope that counter is defined in is not the global scope, on Python 3.x you could use the nonlocal statement. In the same situation on Python 2.x you would have no way to reassign to the nonlocal name counter, so you would need to make counter mutable and modify it:

counter = [0]

def increment():
  counter[0] += 1

increment()
print counter[0]  # prints '1'

How to execute a file within the python interpreter?

Just do,

from my_file import *

Make sure not to add .py extension. If your .py file in subdirectory use,

from my_dir.my_file import *

TypeError: got multiple values for argument

Simply put you can't do the following:

class C(object):
    def x(self, y, **kwargs):
        # Which y to use, kwargs or declaration? 
        pass

c = C()
y = "Arbitrary value"
kwargs["y"] = "Arbitrary value"
c.x(y, **kwargs) # FAILS

Because you pass the variable 'y' into the function twice: once as kwargs and once as function declaration.

Begin, Rescue and Ensure in Ruby?

Yes, ensure ENSURES it is run every time, so you don't need the file.close in the begin block.

By the way, a good way to test is to do:

begin
  # Raise an error here
  raise "Error!!"
rescue
  #handle the error here
ensure
  p "=========inside ensure block"
end

You can test to see if "=========inside ensure block" will be printed out when there is an exception. Then you can comment out the statement that raises the error and see if the ensure statement is executed by seeing if anything gets printed out.

How to get max value of a column using Entity Framework?

Your column is nullable

int maxAge = context.Persons.Select(p => p.Age).Max() ?? 0;

Your column is non-nullable

int maxAge = context.Persons.Select(p => p.Age).Cast<int?>().Max() ?? 0;

In both cases, you can use the second code. If you use DefaultIfEmpty, you will do a bigger query on your server. For people who are interested, here are the EF6 equivalent:

Query without DefaultIfEmpty

SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        MAX([Extent1].[Age]) AS [A1]
        FROM [dbo].[Persons] AS [Extent1]
    )  AS [GroupBy1]

Query with DefaultIfEmpty

SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        MAX([Join1].[A1]) AS [A1]
        FROM ( SELECT 
            CASE WHEN ([Project1].[C1] IS NULL) THEN 0 ELSE [Project1].[Age] END AS [A1]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable1]
            LEFT OUTER JOIN  (SELECT 
                [Extent1].[Age] AS [Age], 
                cast(1 as tinyint) AS [C1]
                FROM [dbo].[Persons] AS [Extent1]) AS [Project1] ON 1 = 1
        )  AS [Join1]
    )  AS [GroupBy1]

Selecting only first-level elements in jquery

$("ul > li a")

But you would need to set a class on the root ul if you specifically want to target the outermost ul:

<ul class="rootlist">
...

Then it's:

$("ul.rootlist > li a")....

Another way of making sure you only have the root li elements:

$("ul > li a").not("ul li ul a")

It looks kludgy, but it should do the trick

Does JSON syntax allow duplicate keys in an object?

There are 2 documents specifying the JSON format:

  1. http://json.org/
  2. https://tools.ietf.org/html/rfc7159

The accepted answer quotes from the 1st document. I think the 1st document is more clear, but the 2nd contains more detail.

The 2nd document says:

  1. Objects

    An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

So it is not forbidden to have a duplicate name, but it is discouraged.

How to print an exception in Python 3?

I'm guessing that you need to assign the Exception to a variable. As shown in the Python 3 tutorial:

def fails():
    x = 1 / 0

try:
    fails()
except Exception as ex:
    print(ex)

To give a brief explanation, as is a pseudo-assignment keyword used in certain compound statements to assign or alias the preceding statement to a variable.

In this case, as assigns the caught exception to a variable allowing for information about the exception to stored and used later, instead of needing to be dealt with immediately. (This is discussed in detail in the Python 3 Language Reference: The try Statement.)


The other compound statement using as is the with statement:

@contextmanager
def opening(filename):
    f = open(filename)
    try:
        yield f
    finally:
        f.close()

with opening(filename) as f:
    # ...read data from f...

Here, with statements are used to wrap the execution of a block with methods defined by context managers. This functions like an extended try...except...finally statement in a neat generator package, and the as statement assigns the generator-produced result from the context manager to a variable for extended use. (This is discussed in detail in the Python 3 Language Reference: The with Statement.)


Finally, as can be used when importing modules, to alias a module to a different (usually shorter) name:

import foo.bar.baz as fbb

This is discussed in detail in the Python 3 Language Reference: The import Statement.

Linux command-line call not returning what it should from os.system?

I can not add a comment to IonicBurger because I do not have "50 reputation" so I will add a new entry. My apologies. os.popen() is the best for multiple/complicated commands (my opinion) and also for getting the return value in addition to getting stdout like the following more complicated multiple commands:

import os
out = [ i.strip() for i in os.popen(r"ls *.py | grep -i '.*file' 2>/dev/null; echo $? ").readlines()]
print "     stdout: ", out[:-1]
print "returnValue: ", out[-1]

This will list all python files that have the word 'file' anywhere in their name. The [...] is a list comprehension to remove (strip) the newline character from each entry. The echo $? is a shell command to show the return status of the last command executed which will be the grep command and the last item of the list in this example. the 2>/dev/null says to print the stderr of the grep command to /dev/null so it does not show up in the output. The 'r' before the 'ls' command is to use the raw string so the shell will not interpret metacharacters like '*' incorrectly. This works in python 2.7. Here is the sample output:

      stdout:  ['fileFilter.py', 'fileProcess.py', 'file_access..py', 'myfile.py']
 returnValue:  0

How can I update window.location.hash without jumping the document?

Why dont you get the current scroll position, put it in a variable then assign the hash and put the page scroll back to where it was:

var yScroll=document.body.scrollTop;
window.location.hash = id;
document.body.scrollTop=yScroll;

this should work

HttpClient.GetAsync(...) never returns when using await/async

These two schools are not really excluding.

Here is the scenario where you simply have to use

   Task.Run(() => AsyncOperation()).Wait(); 

or something like

   AsyncContext.Run(AsyncOperation);

I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.

The library I need is async as it is expected to run async.

The only option. Run it as a normal sync call.

I am just saying to each its own.

Are there benefits of passing by pointer over passing by reference in C++?

Most of the answers here fail to address the inherent ambiguity in having a raw pointer in a function signature, in terms of expressing intent. The problems are the following:

  • The caller does not know whether the pointer points to a single objects, or to the start of an "array" of objects.

  • The caller does not know whether the pointer "owns" the memory it points to. IE, whether or not the function should free up the memory. (foo(new int) - Is this a memory leak?).

  • The caller does not know whether or not nullptr can be safely passed into the function.

All of these problems are solved by references:

  • References always refer to a single object.

  • References never own the memory they refer to, they are merely a view into memory.

  • References can't be null.

This makes references a much better candidate for general use. However, references aren't perfect - there are a couple of major problems to consider.

  • No explicit indirection. This is not a problem with a raw pointer, as we have to use the & operator to show that we are indeed passing a pointer. For example, int a = 5; foo(a); It is not clear at all here that a is being passed by reference and could be modified.
  • Nullability. This weakness of pointers can also be a strength, when we actually want our references to be nullable. Seeing as std::optional<T&> isn't valid (for good reasons), pointers give us that nullability you want.

So it seems that when we want a nullable reference with explicit indirection, we should reach for a T* right? Wrong!

Abstractions

In our desperation for nullability, we may reach for T*, and simply ignore all of the shortcomings and semantic ambiguity listed earlier. Instead, we should reach for what C++ does best: an abstraction. If we simply write a class that wraps around a pointer, we gain the expressiveness, as well as the nullability and explicit indirection.

template <typename T>
struct optional_ref {
  optional_ref() : ptr(nullptr) {}
  optional_ref(T* t) : ptr(t) {}
  optional_ref(std::nullptr_t) : ptr(nullptr) {}

  T& get() const {
    return *ptr;
  }

  explicit operator bool() const {
    return bool(ptr);
  }

private:
  T* ptr;
};

This is the most simple interface I could come up with, but it does the job effectively. It allows for initializing the reference, checking whether a value exists and accessing the value. We can use it like so:

void foo(optional_ref<int> x) {
  if (x) {
    auto y = x.get();
    // use y here
  }
}

int x = 5;
foo(&x); // explicit indirection here
foo(nullptr); // nullability

We have acheived our goals! Let's now see the benefits, in comparison to the raw pointer.

  • The interface shows clearly that the reference should only refer to one object.
  • Clearly it does not own the memory it refers to, as it has no user defined destructor and no method to delete the memory.
  • The caller knows nullptr can be passed in, since the function author explicitly is asking for an optional_ref

We could make the interface more complex from here, such as adding equality operators, a monadic get_or and map interface, a method that gets the value or throws an exception, constexpr support. That can be done by you.

In conclusion, instead of using raw pointers, reason about what those pointers actually mean in your code, and either leverage a standard library abstraction or write your own. This will improve your code significantly.

Relative instead of Absolute paths in Excel VBA

Just to clarify what yalestar said, this will give you the relative path:

Workbooks.Open FileName:= ThisWorkbook.Path & "\TRICATEndurance Summary.html"

How do I compare two Integers?

Minor note: since Java 1.7 the Integer class has a static compare(Integer, Integer) method, so you can just call Integer.compare(x, y) and be done with it (questions about optimization aside).

Of course that code is incompatible with versions of Java before 1.7, so I would recommend using x.compareTo(y) instead, which is compatible back to 1.2.

What's the difference between JavaScript and JScript?

JScript is Microsoft's equivalent of JavaScript.
Java is an Oracle product and used to be a Sun product.

Oracle bought Sun.

JavaScript + Microsoft = JScript

window.open target _self v window.location.href?

window.location.href = "webpage.htm";

"Exception has been thrown by the target of an invocation" error (mscorlib)

I just had this issue from a namespace mismatch. My XAML file was getting ported over and it had a different namespace from that in the code behind file.

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

You can try,

<div asp-validation-summary="All" class="text-danger"></div>

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

How to customize listview using baseadapter

I suggest using a custom Adapter, first create a Xml-file, for example layout/customlistview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" >
    <ImageView
        android:id="@+id/image"
        android:layout_alignParentRight="true"
        android:paddingRight="4dp" />
    <TextView
        android:id="@+id/title"
        android:layout_toLeftOf="@id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="23sp"
        android:maxLines="1" />
    <TextView
        android:id="@+id/subtitle"
        android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 
</RelativeLayout>

Assuming you have a custom class like this

public class CustomClass {

    private long id;
    private String title, subtitle, picture;

    public CustomClass () {
    }

    public CustomClass (long id, String title, String subtitle, String picture) {
        this.id = id;
        this.title= title;
        this.subtitle= subtitle;
        this.picture= picture;
    }
    //add getters and setters
}

And a CustomAdapter.java uses the xml-layout

public class CustomAdapter extends ArrayAdapter {

private Context context;
private int resource;
private LayoutInflater inflater;

public CustomAdapter (Context context, List<CustomClass> values) { // or String[][] or whatever

    super(context, R.layout.customlistviewitem, values);

    this.context = context;
    this.resource = R.layout.customlistview;
    this.inflater = LayoutInflater.from(context);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    convertView = (RelativeLayout) inflater.inflate(resource, null);

    CustomClass item = (CustomClass) getItem(position);

    TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
    TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
    ImageView imageview = (ImageView) convertView.findViewById(R.id.image);

    //fill the textviews and imageview with the values
    textviewTitle = item.getTtile();
    textviewSubtitle = item.getSubtitle();

    if (item.getAfbeelding() != null) {
        int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
        Drawable image = context.getResources().getDrawable(imageResource);
    }
    imageview.setImageDrawable(image);

    return convertView;
    }
}

Did you manage to do it? Feel free to ask if you want more info on something :)

EDIT: Changed the adapter to suit a List instead of just a List

Hashmap does not work with int, char

Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.

Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer> if you need to.

TCharIntHashMap: An open addressed Map implementation for char keys and int values.

How to replace an entire line in a text file by line number

Let's suppose you want to replace line 4 with the text "different". You can use AWK like so:

awk '{ if (NR == 4) print "different"; else print $0}' input_file.txt > output_file.txt

AWK considers the input to be "records" divided into "fields". By default, one line is one record. NR is the number of records seen. $0 represents the current complete record (while $1 is the first field from the record and so on; by default the fields are words from the line).

So, if the current line number is 4, print the string "different" but otherwise print the line unchanged.

In AWK, program code enclosed in { } runs once on each input record.

You need to quote the AWK program in single-quotes to keep the shell from trying to interpret things like the $0.

EDIT: A shorter and more elegant AWK program from @chepner in the comments below:

awk 'NR==4 {$0="different"} { print }' input_file.txt

Only for record (i.e. line) number 4, replace the whole record with the string "different". Then for every input record, print the record.

Clearly my AWK skills are rusty! Thank you, @chepner.

EDIT: and see also an even shorter version from @Dennis Williamson:

awk 'NR==4 {$0="different"} 1' input_file.txt

How this works is explained in the comments: the 1 always evaluates true, so the associated code block always runs. But there is no associated code block, which means AWK does its default action of just printing the whole line. AWK is designed to allow terse programs like this.

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

To Trigger OnChange in ObservableCollection List

  1. Get index of selected Item
  2. Remove the item from the Parent
  3. Add the item at same index in parent

Example:

int index = NotificationDetails.IndexOf(notificationDetails);
NotificationDetails.Remove(notificationDetails);
NotificationDetails.Insert(index, notificationDetails);

Android Viewpager as Image Slide Gallery

Hoho.. It should be very easy to use Gallery to implement this, using ViewPager is much harder. But i still encourage to use ViewPager since Gallery really have many problems and is deprecated since android 4.2.

In PagerAdapter there is a method getPageWidth() to control page size, but only by this you cannot achieve your target.

Try to read the following 2 articles for help.

multiple-view-viewpager-options

viewpager-container

Android difference between Two Dates

Here is the modern answer. It’s good for anyone who either uses Java 8 or later (which doesn’t go for most Android phones yet) or is happy with an external library.

    String date1 = "20170717141000";
    String date2 = "20170719175500";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    Duration diff = Duration.between(LocalDateTime.parse(date1, formatter), 
                                     LocalDateTime.parse(date2, formatter));

    if (diff.isZero()) {
        System.out.println("0m");
    } else {
        long days = diff.toDays();
        if (days != 0) {
            System.out.print("" + days + "d ");
            diff = diff.minusDays(days);
        }
        long hours = diff.toHours();
        if (hours != 0) {
            System.out.print("" + hours + "h ");
            diff = diff.minusHours(hours);
        }
        long minutes = diff.toMinutes();
        if (minutes != 0) {
            System.out.print("" + minutes + "m ");
            diff = diff.minusMinutes(minutes);
        }
        long seconds = diff.getSeconds();
        if (seconds != 0) {
            System.out.print("" + seconds + "s ");
        }
        System.out.println();
    }

This prints

2d 3h 45m 

In my own opinion the advantage is not so much that it is shorter (it’s not much), but leaving the calculations to an standard library is less errorprone and gives you clearer code. These are great advantages. The reader is not burdened with recognizing constants like 24, 60 and 1000 and verifying that they are used correctly.

I am using the modern Java date & time API (described in JSR-310 and also known under this name). To use this on Android under API level 26, get the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project. To use it with other Java 6 or 7, get ThreeTen Backport. With Java 8 and later it is built-in.

With Java 9 it will be still a bit easier since the Duration class is extended with methods to give you the days part, hours part, minutes part and seconds part separately so you don’t need the subtractions. See an example in my answer here.

How can I mock requests and the response?

Here is what worked for me:

import mock
@mock.patch('requests.get', mock.Mock(side_effect = lambda k:{'aurl': 'a response', 'burl' : 'b response'}.get(k, 'unhandled request %s'%k)))

How to empty the message in a text area with jquery?

A comment to jarijira

Well I have had many issues with .html and .empty() methods for inputs o. If the id represents an input and not another type of html selector like

or use the .val() function to manipulate.

For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').val('') //clear input value
     $('#someInput').val(newVal) //override w/ the new value
     $('#someInput').val('test2) 
     newVal= $('#someInput').val(newVal) //get input value

}

For improper, but sometimes works For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').html('') //clear input value
     $('#someInput').empty() //clear html inside of the id
     $('#someInput').html(newVal) //override the html inside of text area w/ string could be '<div>test3</div>
     really overriding with a string manipulates the value, but this is not the best practice as you do not put things besides strings or values inside of an input. 
     newVal= $('#someInput').val(newVal) //get input value

}

An issue that I had was I was using the $getJson method and I was indeed able to use .html calls to manipulate my inputs. However, whenever I had an error or fail on the getJSON I could no longer change my inputs using the .clear and .html calls. I could still return the .val(). After some experimentation and research I discovered that you should only use the .val() function to make changes to input fields.

Rounding integer division (instead of truncating)

Safer C code (unless you have other methods of handling /0):

return (_divisor > 0) ? ((_dividend + (_divisor - 1)) / _divisor) : _dividend;

This doesn't handle the problems that occur from having an incorrect return value as a result of your invalid input data, of course.

Installing J2EE into existing eclipse IDE

You could install Web Tool Platform on top of your current installation to help you learn about Java EE. Download the Web Tools Platform by using Eclipse Software Update (Instruction at http://download.eclipse.org/webtools/updates/). It has features to get you going with learning Java EE. You could learn more about Web Tools Platform at http://www.eclipse.org/webtools/

How to convert empty spaces into null values, using SQL Server?

SQL Server ignores trailing whitespace when comparing strings, so ' ' = ''. Just use the following query for your update

UPDATE table
SET col1 = NULL
WHERE col1 = ''

NULL values in your table will stay NULL, and col1s with any number on space only characters will be changed to NULL.

If you want to do it during your copy from one table to another, use this:

INSERT INTO newtable ( col1, othercolumn )
SELECT
   NULLIF(col1, ''),
   othercolumn
FROM table

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

I was facing the same problem trying to get around a custom check constraint that I needed to updated to allow different values. Problem is that ALL_CONSTRAINTS does't have a way to tell which column the constraint(s) are applied to. The way I managed to do it is by querying ALL_CONS_COLUMNS instead, then dropping each of the constraints by their name and recreate it.

select constraint_name from all_cons_columns where table_name = [TABLE_NAME] and column_name = [COLUMN_NAME];

What is the correct syntax of ng-include?

You have to single quote your src string inside of the double quotes:

<div ng-include src="'views/sidepanel.html'"></div>

Source

Angularjs prevent form submission when input validation fails

Change the submit button to:

<button type="submit" ng-disabled="loginform.$invalid">Login</button>

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

Is it ok to run docker from inside docker?

Running Docker inside Docker (a.k.a. dind), while possible, should be avoided, if at all possible. (Source provided below.) Instead, you want to set up a way for your main container to produce and communicate with sibling containers.

Jérôme Petazzoni — the author of the feature that made it possible for Docker to run inside a Docker container — actually wrote a blog post saying not to do it. The use case he describes matches the OP's exact use case of a CI Docker container that needs to run jobs inside other Docker containers.

Petazzoni lists two reasons why dind is troublesome:

  1. It does not cooperate well with Linux Security Modules (LSM).
  2. It creates a mismatch in file systems that creates problems for the containers created inside parent containers.

From that blog post, he describes the following alternative,

[The] simplest way is to just expose the Docker socket to your CI container, by bind-mounting it with the -v flag.

Simply put, when you start your CI container (Jenkins or other), instead of hacking something together with Docker-in-Docker, start it with:

docker run -v /var/run/docker.sock:/var/run/docker.sock ...

Now this container will have access to the Docker socket, and will therefore be able to start containers. Except that instead of starting "child" containers, it will start "sibling" containers.

jQuery trigger file input

I think i understand your problem, because i have a similar. So the tag <label> have the atribute for, you can use this atribute to link your input with type="file". But if you don't want to activate this using this label because some rule of your layout, you can do like this.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  var reference = $(document).find("#main");_x000D_
  reference.find(".js-btn-upload").attr({_x000D_
     formenctype: 'multipart/form-data'_x000D_
  });_x000D_
  _x000D_
  reference.find(".js-btn-upload").click(function(){_x000D_
    reference.find("label").trigger("click");_x000D_
  });_x000D_
  _x000D_
});
_x000D_
.hide{_x000D_
  overflow: hidden;_x000D_
  visibility: hidden;_x000D_
  /*Style for hide the elements, don't put the element "out" of the screen*/_x000D_
}_x000D_
_x000D_
.btn{_x000D_
  /*button style*/_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<div id="main">_x000D_
<form enctype"multipart/formdata" id="form-id" class="hide" method="post" action="your-action">_x000D_
  <label for="input-id" class="hide"></label>_x000D_
  <input type="file" id="input-id" class="hide"/>_x000D_
</form>_x000D_
_x000D_
<button class="btn js-btn-upload">click me</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Of course you will adapt this for your own purpose and layout, but that's the more easily way i know to make it work!!

How to split a string into an array in Bash?

All of the answers to this question are wrong in one way or another.


Wrong answer #1

IFS=', ' read -r -a array <<< "$string"

1: This is a misuse of $IFS. The value of the $IFS variable is not taken as a single variable-length string separator, rather it is taken as a set of single-character string separators, where each field that read splits off from the input line can be terminated by any character in the set (comma or space, in this example).

Actually, for the real sticklers out there, the full meaning of $IFS is slightly more involved. From the bash manual:

The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words using these characters as field terminators. If IFS is unset, or its value is exactly <space><tab><newline>, the default, then sequences of <space>, <tab>, and <newline> at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters <space>, <tab>, and <newline> are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs.

Basically, for non-default non-null values of $IFS, fields can be separated with either (1) a sequence of one or more characters that are all from the set of "IFS whitespace characters" (that is, whichever of <space>, <tab>, and <newline> ("newline" meaning line feed (LF)) are present anywhere in $IFS), or (2) any non-"IFS whitespace character" that's present in $IFS along with whatever "IFS whitespace characters" surround it in the input line.

For the OP, it's possible that the second separation mode I described in the previous paragraph is exactly what he wants for his input string, but we can be pretty confident that the first separation mode I described is not correct at all. For example, what if his input string was 'Los Angeles, United States, North America'?

IFS=', ' read -ra a <<<'Los Angeles, United States, North America'; declare -p a;
## declare -a a=([0]="Los" [1]="Angeles" [2]="United" [3]="States" [4]="North" [5]="America")

2: Even if you were to use this solution with a single-character separator (such as a comma by itself, that is, with no following space or other baggage), if the value of the $string variable happens to contain any LFs, then read will stop processing once it encounters the first LF. The read builtin only processes one line per invocation. This is true even if you are piping or redirecting input only to the read statement, as we are doing in this example with the here-string mechanism, and thus unprocessed input is guaranteed to be lost. The code that powers the read builtin has no knowledge of the data flow within its containing command structure.

You could argue that this is unlikely to cause a problem, but still, it's a subtle hazard that should be avoided if possible. It is caused by the fact that the read builtin actually does two levels of input splitting: first into lines, then into fields. Since the OP only wants one level of splitting, this usage of the read builtin is not appropriate, and we should avoid it.

3: A non-obvious potential issue with this solution is that read always drops the trailing field if it is empty, although it preserves empty fields otherwise. Here's a demo:

string=', , a, , b, c, , , '; IFS=', ' read -ra a <<<"$string"; declare -p a;
## declare -a a=([0]="" [1]="" [2]="a" [3]="" [4]="b" [5]="c" [6]="" [7]="")

Maybe the OP wouldn't care about this, but it's still a limitation worth knowing about. It reduces the robustness and generality of the solution.

This problem can be solved by appending a dummy trailing delimiter to the input string just prior to feeding it to read, as I will demonstrate later.


Wrong answer #2

string="1:2:3:4:5"
set -f                     # avoid globbing (expansion of *).
array=(${string//:/ })

Similar idea:

t="one,two,three"
a=($(echo $t | tr ',' "\n"))

(Note: I added the missing parentheses around the command substitution which the answerer seems to have omitted.)

Similar idea:

string="1,2,3,4"
array=(`echo $string | sed 's/,/\n/g'`)

These solutions leverage word splitting in an array assignment to split the string into fields. Funnily enough, just like read, general word splitting also uses the $IFS special variable, although in this case it is implied that it is set to its default value of <space><tab><newline>, and therefore any sequence of one or more IFS characters (which are all whitespace characters now) is considered to be a field delimiter.

This solves the problem of two levels of splitting committed by read, since word splitting by itself constitutes only one level of splitting. But just as before, the problem here is that the individual fields in the input string can already contain $IFS characters, and thus they would be improperly split during the word splitting operation. This happens to not be the case for any of the sample input strings provided by these answerers (how convenient...), but of course that doesn't change the fact that any code base that used this idiom would then run the risk of blowing up if this assumption were ever violated at some point down the line. Once again, consider my counterexample of 'Los Angeles, United States, North America' (or 'Los Angeles:United States:North America').

Also, word splitting is normally followed by filename expansion (aka pathname expansion aka globbing), which, if done, would potentially corrupt words containing the characters *, ?, or [ followed by ] (and, if extglob is set, parenthesized fragments preceded by ?, *, +, @, or !) by matching them against file system objects and expanding the words ("globs") accordingly. The first of these three answerers has cleverly undercut this problem by running set -f beforehand to disable globbing. Technically this works (although you should probably add set +f afterward to reenable globbing for subsequent code which may depend on it), but it's undesirable to have to mess with global shell settings in order to hack a basic string-to-array parsing operation in local code.

Another issue with this answer is that all empty fields will be lost. This may or may not be a problem, depending on the application.

Note: If you're going to use this solution, it's better to use the ${string//:/ } "pattern substitution" form of parameter expansion, rather than going to the trouble of invoking a command substitution (which forks the shell), starting up a pipeline, and running an external executable (tr or sed), since parameter expansion is purely a shell-internal operation. (Also, for the tr and sed solutions, the input variable should be double-quoted inside the command substitution; otherwise word splitting would take effect in the echo command and potentially mess with the field values. Also, the $(...) form of command substitution is preferable to the old `...` form since it simplifies nesting of command substitutions and allows for better syntax highlighting by text editors.)


Wrong answer #3

str="a, b, c, d"  # assuming there is a space after ',' as in Q
arr=(${str//,/})  # delete all occurrences of ','

This answer is almost the same as #2. The difference is that the answerer has made the assumption that the fields are delimited by two characters, one of which being represented in the default $IFS, and the other not. He has solved this rather specific case by removing the non-IFS-represented character using a pattern substitution expansion and then using word splitting to split the fields on the surviving IFS-represented delimiter character.

This is not a very generic solution. Furthermore, it can be argued that the comma is really the "primary" delimiter character here, and that stripping it and then depending on the space character for field splitting is simply wrong. Once again, consider my counterexample: 'Los Angeles, United States, North America'.

Also, again, filename expansion could corrupt the expanded words, but this can be prevented by temporarily disabling globbing for the assignment with set -f and then set +f.

Also, again, all empty fields will be lost, which may or may not be a problem depending on the application.


Wrong answer #4

string='first line
second line
third line'

oldIFS="$IFS"
IFS='
'
IFS=${IFS:0:1} # this is useful to format your code with tabs
lines=( $string )
IFS="$oldIFS"

This is similar to #2 and #3 in that it uses word splitting to get the job done, only now the code explicitly sets $IFS to contain only the single-character field delimiter present in the input string. It should be repeated that this cannot work for multicharacter field delimiters such as the OP's comma-space delimiter. But for a single-character delimiter like the LF used in this example, it actually comes close to being perfect. The fields cannot be unintentionally split in the middle as we saw with previous wrong answers, and there is only one level of splitting, as required.

One problem is that filename expansion will corrupt affected words as described earlier, although once again this can be solved by wrapping the critical statement in set -f and set +f.

Another potential problem is that, since LF qualifies as an "IFS whitespace character" as defined earlier, all empty fields will be lost, just as in #2 and #3. This would of course not be a problem if the delimiter happens to be a non-"IFS whitespace character", and depending on the application it may not matter anyway, but it does vitiate the generality of the solution.

So, to sum up, assuming you have a one-character delimiter, and it is either a non-"IFS whitespace character" or you don't care about empty fields, and you wrap the critical statement in set -f and set +f, then this solution works, but otherwise not.

(Also, for information's sake, assigning a LF to a variable in bash can be done more easily with the $'...' syntax, e.g. IFS=$'\n';.)


Wrong answer #5

countries='Paris, France, Europe'
OIFS="$IFS"
IFS=', ' array=($countries)
IFS="$OIFS"

Similar idea:

IFS=', ' eval 'array=($string)'

This solution is effectively a cross between #1 (in that it sets $IFS to comma-space) and #2-4 (in that it uses word splitting to split the string into fields). Because of this, it suffers from most of the problems that afflict all of the above wrong answers, sort of like the worst of all worlds.

Also, regarding the second variant, it may seem like the eval call is completely unnecessary, since its argument is a single-quoted string literal, and therefore is statically known. But there's actually a very non-obvious benefit to using eval in this way. Normally, when you run a simple command which consists of a variable assignment only, meaning without an actual command word following it, the assignment takes effect in the shell environment:

IFS=', '; ## changes $IFS in the shell environment

This is true even if the simple command involves multiple variable assignments; again, as long as there's no command word, all variable assignments affect the shell environment:

IFS=', ' array=($countries); ## changes both $IFS and $array in the shell environment

But, if the variable assignment is attached to a command name (I like to call this a "prefix assignment") then it does not affect the shell environment, and instead only affects the environment of the executed command, regardless whether it is a builtin or external:

IFS=', ' :; ## : is a builtin command, the $IFS assignment does not outlive it
IFS=', ' env; ## env is an external command, the $IFS assignment does not outlive it

Relevant quote from the bash manual:

If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment.

It is possible to exploit this feature of variable assignment to change $IFS only temporarily, which allows us to avoid the whole save-and-restore gambit like that which is being done with the $OIFS variable in the first variant. But the challenge we face here is that the command we need to run is itself a mere variable assignment, and hence it would not involve a command word to make the $IFS assignment temporary. You might think to yourself, well why not just add a no-op command word to the statement like the : builtin to make the $IFS assignment temporary? This does not work because it would then make the $array assignment temporary as well:

IFS=', ' array=($countries) :; ## fails; new $array value never escapes the : command

So, we're effectively at an impasse, a bit of a catch-22. But, when eval runs its code, it runs it in the shell environment, as if it was normal, static source code, and therefore we can run the $array assignment inside the eval argument to have it take effect in the shell environment, while the $IFS prefix assignment that is prefixed to the eval command will not outlive the eval command. This is exactly the trick that is being used in the second variant of this solution:

IFS=', ' eval 'array=($string)'; ## $IFS does not outlive the eval command, but $array does

So, as you can see, it's actually quite a clever trick, and accomplishes exactly what is required (at least with respect to assignment effectation) in a rather non-obvious way. I'm actually not against this trick in general, despite the involvement of eval; just be careful to single-quote the argument string to guard against security threats.

But again, because of the "worst of all worlds" agglomeration of problems, this is still a wrong answer to the OP's requirement.


Wrong answer #6

IFS=', '; array=(Paris, France, Europe)

IFS=' ';declare -a array=(Paris France Europe)

Um... what? The OP has a string variable that needs to be parsed into an array. This "answer" starts with the verbatim contents of the input string pasted into an array literal. I guess that's one way to do it.

It looks like the answerer may have assumed that the $IFS variable affects all bash parsing in all contexts, which is not true. From the bash manual:

IFS    The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is <space><tab><newline>.

So the $IFS special variable is actually only used in two contexts: (1) word splitting that is performed after expansion (meaning not when parsing bash source code) and (2) for splitting input lines into words by the read builtin.

Let me try to make this clearer. I think it might be good to draw a distinction between parsing and execution. Bash must first parse the source code, which obviously is a parsing event, and then later it executes the code, which is when expansion comes into the picture. Expansion is really an execution event. Furthermore, I take issue with the description of the $IFS variable that I just quoted above; rather than saying that word splitting is performed after expansion, I would say that word splitting is performed during expansion, or, perhaps even more precisely, word splitting is part of the expansion process. The phrase "word splitting" refers only to this step of expansion; it should never be used to refer to the parsing of bash source code, although unfortunately the docs do seem to throw around the words "split" and "words" a lot. Here's a relevant excerpt from the linux.die.net version of the bash manual:

Expansion is performed on the command line after it has been split into words. There are seven kinds of expansion performed: brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and pathname expansion.

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expansion.

You could argue the GNU version of the manual does slightly better, since it opts for the word "tokens" instead of "words" in the first sentence of the Expansion section:

Expansion is performed on the command line after it has been split into tokens.

The important point is, $IFS does not change the way bash parses source code. Parsing of bash source code is actually a very complex process that involves recognition of the various elements of shell grammar, such as command sequences, command lists, pipelines, parameter expansions, arithmetic substitutions, and command substitutions. For the most part, the bash parsing process cannot be altered by user-level actions like variable assignments (actually, there are some minor exceptions to this rule; for example, see the various compatxx shell settings, which can change certain aspects of parsing behavior on-the-fly). The upstream "words"/"tokens" that result from this complex parsing process are then expanded according to the general process of "expansion" as broken down in the above documentation excerpts, where word splitting of the expanded (expanding?) text into downstream words is simply one step of that process. Word splitting only touches text that has been spit out of a preceding expansion step; it does not affect literal text that was parsed right off the source bytestream.


Wrong answer #7

string='first line
        second line
        third line'

while read -r line; do lines+=("$line"); done <<<"$string"

This is one of the best solutions. Notice that we're back to using read. Didn't I say earlier that read is inappropriate because it performs two levels of splitting, when we only need one? The trick here is that you can call read in such a way that it effectively only does one level of splitting, specifically by splitting off only one field per invocation, which necessitates the cost of having to call it repeatedly in a loop. It's a bit of a sleight of hand, but it works.

But there are problems. First: When you provide at least one NAME argument to read, it automatically ignores leading and trailing whitespace in each field that is split off from the input string. This occurs whether $IFS is set to its default value or not, as described earlier in this post. Now, the OP may not care about this for his specific use-case, and in fact, it may be a desirable feature of the parsing behavior. But not everyone who wants to parse a string into fields will want this. There is a solution, however: A somewhat non-obvious usage of read is to pass zero NAME arguments. In this case, read will store the entire input line that it gets from the input stream in a variable named $REPLY, and, as a bonus, it does not strip leading and trailing whitespace from the value. This is a very robust usage of read which I've exploited frequently in my shell programming career. Here's a demonstration of the difference in behavior:

string=$'  a  b  \n  c  d  \n  e  f  '; ## input string

a=(); while read -r line; do a+=("$line"); done <<<"$string"; declare -p a;
## declare -a a=([0]="a  b" [1]="c  d" [2]="e  f") ## read trimmed surrounding whitespace

a=(); while read -r; do a+=("$REPLY"); done <<<"$string"; declare -p a;
## declare -a a=([0]="  a  b  " [1]="  c  d  " [2]="  e  f  ") ## no trimming

The second issue with this solution is that it does not actually address the case of a custom field separator, such as the OP's comma-space. As before, multicharacter separators are not supported, which is an unfortunate limitation of this solution. We could try to at least split on comma by specifying the separator to the -d option, but look what happens:

string='Paris, France, Europe';
a=(); while read -rd,; do a+=("$REPLY"); done <<<"$string"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France")

Predictably, the unaccounted surrounding whitespace got pulled into the field values, and hence this would have to be corrected subsequently through trimming operations (this could also be done directly in the while-loop). But there's another obvious error: Europe is missing! What happened to it? The answer is that read returns a failing return code if it hits end-of-file (in this case we can call it end-of-string) without encountering a final field terminator on the final field. This causes the while-loop to break prematurely and we lose the final field.

Technically this same error afflicted the previous examples as well; the difference there is that the field separator was taken to be LF, which is the default when you don't specify the -d option, and the <<< ("here-string") mechanism automatically appends a LF to the string just before it feeds it as input to the command. Hence, in those cases, we sort of accidentally solved the problem of a dropped final field by unwittingly appending an additional dummy terminator to the input. Let's call this solution the "dummy-terminator" solution. We can apply the dummy-terminator solution manually for any custom delimiter by concatenating it against the input string ourselves when instantiating it in the here-string:

a=(); while read -rd,; do a+=("$REPLY"); done <<<"$string,"; declare -p a;
declare -a a=([0]="Paris" [1]=" France" [2]=" Europe")

There, problem solved. Another solution is to only break the while-loop if both (1) read returned failure and (2) $REPLY is empty, meaning read was not able to read any characters prior to hitting end-of-file. Demo:

a=(); while read -rd,|| [[ -n "$REPLY" ]]; do a+=("$REPLY"); done <<<"$string"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=$' Europe\n')

This approach also reveals the secretive LF that automatically gets appended to the here-string by the <<< redirection operator. It could of course be stripped off separately through an explicit trimming operation as described a moment ago, but obviously the manual dummy-terminator approach solves it directly, so we could just go with that. The manual dummy-terminator solution is actually quite convenient in that it solves both of these two problems (the dropped-final-field problem and the appended-LF problem) in one go.

So, overall, this is quite a powerful solution. It's only remaining weakness is a lack of support for multicharacter delimiters, which I will address later.


Wrong answer #8

string='first line
        second line
        third line'

readarray -t lines <<<"$string"

(This is actually from the same post as #7; the answerer provided two solutions in the same post.)

The readarray builtin, which is a synonym for mapfile, is ideal. It's a builtin command which parses a bytestream into an array variable in one shot; no messing with loops, conditionals, substitutions, or anything else. And it doesn't surreptitiously strip any whitespace from the input string. And (if -O is not given) it conveniently clears the target array before assigning to it. But it's still not perfect, hence my criticism of it as a "wrong answer".

First, just to get this out of the way, note that, just like the behavior of read when doing field-parsing, readarray drops the trailing field if it is empty. Again, this is probably not a concern for the OP, but it could be for some use-cases. I'll come back to this in a moment.

Second, as before, it does not support multicharacter delimiters. I'll give a fix for this in a moment as well.

Third, the solution as written does not parse the OP's input string, and in fact, it cannot be used as-is to parse it. I'll expand on this momentarily as well.

For the above reasons, I still consider this to be a "wrong answer" to the OP's question. Below I'll give what I consider to be the right answer.


Right answer

Here's a naïve attempt to make #8 work by just specifying the -d option:

string='Paris, France, Europe';
readarray -td, a <<<"$string"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=$' Europe\n')

We see the result is identical to the result we got from the double-conditional approach of the looping read solution discussed in #7. We can almost solve this with the manual dummy-terminator trick:

readarray -td, a <<<"$string,"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=" Europe" [3]=$'\n')

The problem here is that readarray preserved the trailing field, since the <<< redirection operator appended the LF to the input string, and therefore the trailing field was not empty (otherwise it would've been dropped). We can take care of this by explicitly unsetting the final array element after-the-fact:

readarray -td, a <<<"$string,"; unset 'a[-1]'; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=" Europe")

The only two problems that remain, which are actually related, are (1) the extraneous whitespace that needs to be trimmed, and (2) the lack of support for multicharacter delimiters.

The whitespace could of course be trimmed afterward (for example, see How to trim whitespace from a Bash variable?). But if we can hack a multicharacter delimiter, then that would solve both problems in one shot.

Unfortunately, there's no direct way to get a multicharacter delimiter to work. The best solution I've thought of is to preprocess the input string to replace the multicharacter delimiter with a single-character delimiter that will be guaranteed not to collide with the contents of the input string. The only character that has this guarantee is the NUL byte. This is because, in bash (though not in zsh, incidentally), variables cannot contain the NUL byte. This preprocessing step can be done inline in a process substitution. Here's how to do it using awk:

readarray -td '' a < <(awk '{ gsub(/, /,"\0"); print; }' <<<"$string, "); unset 'a[-1]';
declare -p a;
## declare -a a=([0]="Paris" [1]="France" [2]="Europe")

There, finally! This solution will not erroneously split fields in the middle, will not cut out prematurely, will not drop empty fields, will not corrupt itself on filename expansions, will not automatically strip leading and trailing whitespace, will not leave a stowaway LF on the end, does not require loops, and does not settle for a single-character delimiter.


Trimming solution

Lastly,

MongoDB or CouchDB - fit for production?

Here's a list of production deployed sites with mongoDB

  • The New Yorks Times: Using it in a form-building application for photo submissions. Mongo's lack of schema gives producers the ability to define any combination of custom form fields.
  • SourceForge: is used for back-end storage on the SourceForge front pages, project pages, and download pages for all projects.
  • Bit.ly
  • Etsy
  • IGN: powers IGN’s real-time traffic analytics and RESTful Content APIs.
  • Justin.tv: powers Justin.tv's internal analytics tools for virality, user retention, and general usage stats that out-of-the-box solutions can't provide.
  • Posterous
  • Intuit
  • Foursquare: Sharded Mongo databases are used for most data at foursquare.
  • Business Insider: Using it since the beginning of 2008. All of the site's data, including posts, comments, and even the images, are stored on MongoDB.
  • Github: is used for an internal reporting application.
  • Examiner: migrated their site from Cold Fusion and SQL Server to Drupal 7 and MongoDB.
  • Grooveshark: currently uses Mongo to manage over one million unique user sessions per day.
  • Buzzfeed
  • Discus
  • Evite: Used for analytics and quick reporting.
  • Squarespace
  • Shutterfly: is used for various persistent data storage requirements within Shutterfly. MongoDB helps Shutterfly build an unrivaled service that enables deeper, more personal relationships between customers and those who matter most in their lives.
  • Topsy
  • Sharethis
  • Mongohq: provides a hosting platform for MongoDB and also uses MongoDB as the back-end for its service. Our hosting centers page provides more information about MongoHQ and other MongoDB hosting options.

and more...

Extracted from: http://lineofthought.com/tools/mongodb

You can check other databases or tools there too.

How to change the background color on a Java panel?

I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);

PHP convert XML to JSON

        $content = str_replace(array("\n", "\r", "\t"), '', $response);
        $content = trim(str_replace('"', "'", $content));
        $xml = simplexml_load_string($content);
        $json = json_encode($xml);
        return json_decode($json,TRUE);

This worked for me

How to disable javax.swing.JButton in java?

This works.

public class TestButton {

public TestButton() {
    JFrame f = new JFrame();
    f.setSize(new Dimension(200,200));
    JPanel p = new JPanel();
    p.setLayout(new FlowLayout());

    final JButton stop = new JButton("Stop");
    final JButton start = new JButton("Start");
    p.add(start);
    p.add(stop);
    f.getContentPane().add(p);
    stop.setEnabled(false);
    stop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            start.setEnabled(true);
            stop.setEnabled(false);

        }
    });

    start.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            start.setEnabled(false);
            stop.setEnabled(true);

        }
    });
    f.setVisible(true);
}

/**
 * @param args
 */
public static void main(String[] args) {
    new TestButton();

}

}

Excel date to Unix timestamp

To make up for the daylight saving time (starting on March's last sunday until October's last sunday) I had to use the following formula:

=IF(
  AND(
    A2>=EOMONTH(DATE(YEAR(A2);3;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);3;1);0);11);7);
    A2<=EOMONTH(DATE(YEAR(A2);10;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);10;1);0);11);7)
  );
  (A2-DATE(1970;1;1)-TIME(1;0;0))*24*60*60*1000;
  (A2-DATE(1970;1;1))*24*60*60*1000
)

Quick explanation:

If the date ["A2"] is between March's last sunday and October's last sunday [third and fourth code lines], then I'll be subtracting one hour [-TIME(1;0;0)] to the date.

How to create a private class method?

Just for the completeness, we can also avoid declaring private_class_method in a separate line. I personally don't like this usage but good to know that it exists.

private_class_method  def self.method_name
 ....
end

Is Google Play Store supported in avd emulators?

on the Select a Device option choose a device with google play icon and then select a system image that shows Google play in the target

enter image description here

Stretch and scale CSS background

Define "stretch and scale"...

If you've got a bitmap format, it's generally not great (graphically speaking) to stretch it and pull it about. You can use repeatable patterns to give the illusion of the same effect. For instance if you have a gradient that gets lighter towards the bottom of the page, then you would use a graphic that's a single pixel wide and the same height as your container (or preferably larger to account for scaling) and then tile it across the page. Likewise, if the gradient ran across the page, it would be one pixel high and wider than your container and repeated down the page.

Normally to give the illusion of it stretching to fill the container when the container grows or shrinks, you make the image larger than the container. Any overlap would not be displayed outside the bounds of the container.

If you want an effect that relies on something like a box with curved edges, then you would stick the left side of your box to the left side of your container with enough overlap that (within reason) no matter how large the container, it never runs out of background and then you layer an image of the right side of the box with curved edges and position it on the right of the container. Thus as the container shrinks or grows, the curved box effect appears to shrink or grow with it - it doesn't in fact, but it gives the illusion that is what's happening.

As for really making the image shrink and grow with the container, you would need to use some layering tricks to make the image appear to function as a background and some javascript to resize it with the container. There's no current way of doing this with CSS...

If you're using vector graphics, you're way outside my realm of expertise I'm afraid.

Bootstrap 3 scrollable div for table

You can use too

style="overflow-y: scroll; height:150px; width: auto;"

It's works for me

How to use delimiter for csv in python

Your code is blanking out your file:

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)

if you want to read the file in, you will need to use csv.reader and open the file for reading.

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
    print line

If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).

Where can I find the Java SDK in Linux after installing it?

Use find to located it. It should be under /usr somewhere:

find /usr -name java

When running the command, if there are too many "Permission denied" message obfuscating the actual found results then, simply redirect stderr to /dev/null

find /usr -name java 2> /dev/null

Problems with entering Git commit message with Vim

If it is VIM for Windows, you can do the following:

  • enter your message following the presented guidelines
  • press Esc to make sure you are out of the insert mode
  • then type :wqEnter or ZZ.

Note that in VIM there are often several ways to do one thing. Here there is a slight difference though. :wqEnter always writes the current file before closing it, while ZZ, :xEnter, :xiEnter, :xitEnter, :exiEnter and :exitEnter only write it if the document is modified.
All these synonyms just have different numbers of keypresses.

How to apply CSS page-break to print a table with lots of rows?

You should use

<tbody> 
  <tr>
  first page content here 
  </tr>
  <tr>
  ..
  </tr>
</tbody>
<tbody>
  next page content...
</tbody>

And CSS:

tbody { display: block; page-break-before: avoid; }
tbody { display: block; page-break-after: always; }

Why does instanceof return false for some literals?

Primitives are a different kind of type than objects created from within Javascript. From the Mozilla API docs:

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

I can't find any way to construct primitive types with code, perhaps it's not possible. This is probably why people use typeof "foo" === "string" instead of instanceof.

An easy way to remember things like this is asking yourself "I wonder what would be sane and easy to learn"? Whatever the answer is, Javascript does the other thing.

Can an Android NFC phone act as an NFC tag?

Yes, take a look at NDEF Push in NFCManager - with Android 4 you can now even create the NDEFMessage to push to the active device at the time the interaction takes place.

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

C++: constructor initializer for arrays

You can do it, but it's not pretty:

#include <iostream>

class A {
    int mvalue;
public:
    A(int value) : mvalue(value) {}
    int value() { return mvalue; }
};

class B {
    // TODO: hack that respects alignment of A.. maybe C++14's alignof?
    char _hack[sizeof(A[3])];
    A* marr;
public:
    B() : marr(reinterpret_cast<A*>(_hack)) {
        new (&marr[0]) A(5);
        new (&marr[1]) A(6);
        new (&marr[2]) A(7);
    }

    A* arr() { return marr; }
};

int main(int argc, char** argv) {
    B b;
    A* arr = b.arr();
    std::cout << arr[0].value() << " " << arr[1].value() << " " << arr[2].value() << "\n";
    return 0;
}

If you put this in your code, I hope you have a VERY good reason.

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

Taken from the documentation.

deleting folder from java

It could be problem with nested folders. Your code deletes the folders in the order they were found, which is top-down, which does not work. It might work if you reverse the folder list first.

But I would recommend you just use a library like Commons IO for this.

Drop all tables whose names begin with a certain string

I would like to post my proposal of the solution which DROP (not just generate and select a drop commands) all tables based on the wildcard (e.g. "table_20210114") older than particular amount of days.

DECLARE 
    @drop_command NVARCHAR(MAX) = '',
    @system_time date,
    @table_date nvarchar(8),
    @older_than int = 7
    
Set @system_time = (select getdate() - @older_than)
Set @table_date = (SELECT CONVERT(char(8), @system_time, 112))

SELECT @drop_command += N'DROP TABLE ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME([Name]) + ';'
FROM <your_database_name>.sys.tables
WHERE [Name] LIKE 'table_%' AND RIGHT([Name],8) < @table_date

SELECT @drop_command
 
EXEC sp_executesql @drop_command

Why do people say that Ruby is slow?

Obviously, talking about speed Ruby loses. Even though benchmark tests suggest that Ruby is not so much slower than PHP. But in return, you are getting easy-to-maintain DRY code, the best out of all frameworks in various languages.

For a small project, you wont feel any slowness (I mean until like <50K users) given that no complex calculations are used in the code, just the mainstream stuff.

For a bigger project, paying for resources pays off and is cheaper than developer wages. In addition, writing code on RoR turns out to be much faster than any other.

In 2014 this magnitude of speed difference you're talking about is for most websites insignificant.

Type converting slices of interfaces

Try interface{} instead. To cast back as slice, try

func foo(bar interface{}) {
    s := bar.([]string)
    // ...
}

How to get first 5 characters from string

For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use substr and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use mb_substr:

// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);

What is the iOS 6 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

iPad:

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)

jQuery events .load(), .ready(), .unload()

window load will wait for all resources to be loaded.

document ready waits for the document to be initialized.

unload well, waits till the document is being unloaded.

the order is: document ready, window load, ... ... ... ... window unload.

always use document ready unless you need to wait for your images to load.

shorthand for document ready:

$(function(){
    // yay!
});

How can I use UIColorFromRGB in Swift?

This is a nice extension for UIColor. You can use enum values(hex, string) and direct string values when you creating UIColor objects.

The extension we deserve https://github.com/ioramashvili/UsefulExtensions/blob/master/Extensions.playground/Pages/UIColor.xcplaygroundpage/Contents.swift

Switch firefox to use a different DNS than what is in the windows.host file

It appears from your question that you already have a second set of DNS servers available that reference the development site instead of the live site.

I would suggest that you simply run a standard SOCKS proxy either on that DNS server system or on a low-end spare system and have that system configured to use the development DNS server. You can then tell Firefox to use that proxy instead of downloading pages directly.

Doing it this way, the actual DNS lookups will be done on the proxy machine and not on the machine that's running the web browser.

Algorithm for Determining Tic Tac Toe Game Over

This is a really simple way to check.

    public class Game() { 

    Game player1 = new Game('x');
    Game player2 = new Game('o');

    char piece;

    Game(char piece) {
       this.piece = piece;
    }

public void checkWin(Game player) {

    // check horizontal win
    for (int i = 0; i <= 6; i += 3) {

        if (board[i] == player.piece &&
                board[i + 1] == player.piece &&
                board[i + 2] == player.piece)
            endGame(player);
    }

    // check vertical win
    for (int i = 0; i <= 2; i++) {

        if (board[i] == player.piece &&
                board[i + 3] == player.piece &&
                board[i + 6] == player.piece)
            endGame(player);
    }

    // check diagonal win
    if ((board[0] == player.piece &&
            board[4] == player.piece &&
            board[8] == player.piece) ||
            board[2] == player.piece &&
            board[4] == player.piece &&
            board[6] == player.piece)
        endGame(player);
    }

}

How to open select file dialog via js?

_x000D_
_x000D_
function promptFile(contentType, multiple) {
  var input = document.createElement("input");
  input.type = "file";
  input.multiple = multiple;
  input.accept = contentType;
  return new Promise(function(resolve) {
    document.activeElement.onfocus = function() {
      document.activeElement.onfocus = null;
      setTimeout(resolve, 500);
    };
    input.onchange = function() {
      var files = Array.from(input.files);
      if (multiple)
        return resolve(files);
      resolve(files[0]);
    };
    input.click();
  });
}
function promptFilename() {
  promptFile().then(function(file) {
    document.querySelector("span").innerText = file && file.name || "no file selected";
  });
}
_x000D_
<button onclick="promptFilename()">Open</button>
<span></span>
_x000D_
_x000D_
_x000D_

Relational Database Design Patterns?

Your question is a bit vague, but I suppose UPSERT could be considered a design pattern. For languages that don't implement MERGE, a number of alternatives to solve the problem (if a suitable rows exists, UPDATE; else INSERT) exist.

Print second last column/field in awk

It's simplest:

 awk '{print $--NF}' 

The reason the original $NF-- didn't work is because the expression is evaluated before the decrement, whereas my prefix decrement is performed before evaluation.

How to determine the IP address of a Solaris system

/usr/sbin/host `hostname`

should do the trick. Bear in mind that it's a pretty common configuration for a solaris box to have several IP addresses, though, in which case

 /usr/sbin/ifconfig -a inet | awk '/inet/ {print $2}'

will list them all

The name 'controlname' does not exist in the current context

I fixed this in my project by backing up the current files (so I still had my code), deleting the current aspx (and child pages), making a new one, and copying the contents of the backup files into the new files.

Passing variable number of arguments around

Let's say you have a typical variadic function you've written. Because at least one argument is required before the variadic one ..., you have to always write an extra argument in usage.

Or do you?

If you wrap your variadic function in a macro, you need no preceding arg. Consider this example:

#define LOGI(...)
    ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))

This is obviously far more convenient, since you needn't specify the initial argument every time.

What's the difference between nohup and ampersand

Most of the time we login to remote server using ssh. If you start a shell script and you logout then the process is killed. Nohup helps to continue running the script in background even after you log out from shell.

Nohup command name &
eg: nohup sh script.sh &

Nohup catches the HUP signals. Nohup doesn't put the job automatically in the background. We need to tell that explicitly using &

How to dock "Tool Options" to "Toolbox"?

In the detached 'Tool Options' window, click on the red 'X' in the upper right corner to get rid of the window. Then on the main Gimp screen, click on 'Windows,' then 'Dockable Dialogs.' The first entry on its list will be 'Tool Options,' so click on that. Then, Tool Options will appear as a tab in the window on the right side of the screen, along with layers and undo history. Click and drag that tab over to the toolbox window on hte left and drop it inside. The tool options will again be docked in the toolbox.

.htaccess mod_rewrite - how to exclude directory from rewrite rule

What you could also do is put a .htaccess file containing

RewriteEngine Off

In the folders you want to exclude from being rewritten (by the rules in a .htaccess file that's higher up in the tree). Simple but effective.

Visual Studio Code always asking for git credentials

After fighting with something like this for a little while, I think I came up with a good solution, especially when having multiple accounts across both GitHub and BitBucket. However for VSCode, it ultimately ended up as start it from a Git Bash terminal so that it inherited the environment variables from the bash session and it knew which ssh-agent to look at.

I realise this is an old post but I still really struggled to find one place to get the info I needed. Plus since 2017, ssh-agent got the ability to prompt you for a passphrase only when you try to access a repo.

I put my findings down here if anyone is interested:

How to get the index of an item in a list in a single step?

  1. Simple solution to find index for any string value in the List.

Here is code for List Of String:

int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
  1. Simple solution to find index for any Integer value in the List.

Here is Code for List Of Integer:

    int indexOfNumber = myList.IndexOf(/*insert number from list*/);

Force the origin to start at 0

xlim and ylim don't cut it here. You need to use expand_limits, scale_x_continuous, and scale_y_continuous. Try:

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for

enter image description here

p + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))

enter image description here

You may need to adjust things a little to make sure points are not getting cut off (see, for example, the point at x = 5 and y = 5.

How to get base url in CodeIgniter 2.*

Just load helper class

$this->load->helper('url');

thats it.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/

File.separator gets the separator for the default filesystem.

FileSystems.getDefault() gets you the default filesystem.

FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.

Using Eloquent ORM in Laravel to perform search of database using LIKE

You're able to do database finds using LIKE with this syntax:

Model::where('column', 'LIKE', '%value%')->get();

How to extract a single value from JSON response?

Extract single value from JSON response Python

Try this

import json
import sys

#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

#dumps the json object into an element
json_str = json.dumps(data)

#load the json to a string
resp = json.loads(json_str)

#print the resp
print (resp)

#extract an element in the response
print (resp['test1'])

Get cursor position (in characters) within a text Input field

Got a very simple solution. Try the following code with verified result-

<html>
<head>
<script>
    function f1(el) {
    var val = el.value;
    alert(val.slice(0, el.selectionStart).length);
}
</script>
</head>
<body>
<input type=text id=t1 value=abcd>
    <button onclick="f1(document.getElementById('t1'))">check position</button>
</body>
</html>

I'm giving you the fiddle_demo

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

For my situation, I switched the value of "fork" to false, such as <fork>false</fork>. I do not understand why, hope someone could explain to me. Thanks in advance.

Can't compile C program on a Mac after upgrade to Mojave

The problem is that Xcode, especially Xcode 10.x, has not installed everything, so ensure the command line tools are installed, type this in a terminal shell:

xcode-select --install

also start Xcode and ensure all the required installation is installed ( you should get prompted if it is not.) and since Xcode 10 does not install the full Mac OS SDK, run the installer at

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

as this package is not installed by Xcode 10.

How to copy file from one location to another location?

You can use this (or any variant):

Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

Also, I'd recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.

Since you're not sure how to temporarily store files, take a look at ArrayList:

List<File> files = new ArrayList();
files.add(foundFile);

To move a List of files into a single directory:

List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
    Files.copy(file.toPath(),
        (new File(path + file.getName())).toPath(),
        StandardCopyOption.REPLACE_EXISTING);
}

Split text file into smaller multiple text file using command line

here is one in c# that doesn't run out of memory when splitting into large chunks! I needed to split 95M file into 10M x line files.

var fileSuffix = 0;
int lines = 0;
Stream fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
StreamWriter sw = new StreamWriter(fstream);

using (var file = File.OpenRead(filename))
using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        sw.WriteLine(reader.ReadLine());
        lines++;

        if (lines >= 10000000)
        {
              sw.Close();
              fstream.Close();
              lines = 0;
              fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
              sw = new StreamWriter(fstream);
        }
    }
}

sw.Close();
fstream.Close();

Post-increment and pre-increment within a 'for' loop produce same output

If you wrote it like this then it would matter :

for(i=0; i<5; i=j++) {
    printf("%d",i);
}

Would iterate once more than if written like this :

for(i=0; i<5; i=++j) {
    printf("%d",i);
}

Location of my.cnf file on macOS

If you are using macOS Sierra and the file doesn't exists, run

mysql --help or mysql --help | grep my.cnf

to see the possible locations and loading/reading sequence of my.cnf for mysql then create my.cnf file in one of the suggested directories then add the following line

[mysqld] sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

You can sudo touch /{preferred-path}/my.cnf then edit the file to add sql mode by

sudo nano /{preferred-path}/my.cnf

Then restart mysql, voilaah you are good to go. happy coding

Programmatically get the version number of a DLL

This works if the dll is .net or Win32. Reflection methods only work if the dll is .net. Also, if you use reflection, you have the overhead of loading the whole dll into memory. The below method does not load the assembly into memory.

// Get the file version.
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(@"C:\MyAssembly.dll");

// Print the file name and version number.
Console.WriteLine("File: " + myFileVersionInfo.FileDescription + '\n' +
                  "Version number: " + myFileVersionInfo.FileVersion);

From: http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo.fileversion.aspx

original source

Mockito How to mock and assert a thrown exception?

Assert by exception message:

    try {
        MyAgent.getNameByNode("d");
    } catch (Exception e) {
        Assert.assertEquals("Failed to fetch data.", e.getMessage());
    }

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Use String.Format:

string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";

string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);

In the format {0,-20} means the first argument has a fixed length 20, and the negative sign guarantees the string is printed from left to right.

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

You can use Oracle.ManagedDataAccess.dll instead (download from Oracle), include that dll in you project bin dir, add reference to that dll in the project. In code, "using Oracle.MangedDataAccess.Client". Deploy project to server as usual. No need install Oracle Client on server. No need to add assembly info in web.config.

Check if item is in an array / list

You can also use the same syntax for an array. For example, searching within a Pandas series:

ser = pd.Series(['some', 'strings', 'to', 'query'])

if item in ser.values:
    # do stuff

How to use basic authorization in PHP curl

Its Simple Way To Pass Header

function get_data($url) {

$ch = curl_init();
$timeout = 5;
$username = 'c4f727b9646045e58508b20ac08229e6';        // Put Username 
$password = '';                                        // Put Password
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");    // Add This Line
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = "https://storage.scrapinghub.com/items/397187/2/127";
$data = get_data($url);
echo '<pre>';`print_r($data_json);`die;    // For Print Value

Check My JSON Value

Call PHP function from Twig template

If you really know what you do and you don't mind the evil ways, this is the only additional Twig extension you'll ever need:

function evilEvalPhp($eval, $args = null)
{
    $result = null;
    eval($eval);
    return $result;
}

How to create an Explorer-like folder browser control?

Take a look at Shell MegaPack control set. It provides Windows Explorer like folder/file browsing with most of the features and functionality like context menus, renaming, drag-drop, icons, overlay icons, thumbnails, etc

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

This specifies the default collation for the database. Every text field that you create in tables in the database will use that collation, unless you specify a different one.

A database always has a default collation. If you don't specify any, the default collation of the SQL Server instance is used.

The name of the collation that you use shows that it uses the Latin1 code page 1, is case insensitive (CI) and accent sensitive (AS). This collation is used in the USA, so it will contain sorting rules that are used in the USA.

The collation decides how text values are compared for equality and likeness, and how they are compared when sorting. The code page is used when storing non-unicode data, e.g. varchar fields.

jQuery Selector: Id Ends With?

Try this:

<asp:HiddenField ID="0858674_h" Value="0" runat="server" />

var test = $(this).find('[id*="_h"').val();

Manually map column names with class properties

I do the following using dynamic and LINQ:

    var sql = @"select top 1 person_id, first_name, last_name from Person";
    using (var conn = ConnectionFactory.GetConnection())
    {
        List<Person> person = conn.Query<dynamic>(sql)
                                  .Select(item => new Person()
                                  {
                                      PersonId = item.person_id,
                                      FirstName = item.first_name,
                                      LastName = item.last_name
                                  }
                                  .ToList();

        return person;
    }

Making TextView scrollable on Android

You don't need to use a ScrollView actually.

Just set the

android:scrollbars = "vertical"

properties of your TextView in your layout's xml file.

Then use:

yourTextView.setMovementMethod(new ScrollingMovementMethod());

in your code.

Bingo, it scrolls!

Simple working Example of json.net in VB.net

Imports Newtonsoft.Json.Linq

Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))

java- reset list iterator to first element of the list

If the order doesn't matter, we can re-iterate backward with the same iterator using the hasPrevious() and previous() methods:

ListIterator<T> lit = myList.listIterator(); // create just one iterator

Initially the iterator sits at the beginning, we do forward iteration:

while (lit.hasNext()) process(lit.next()); // begin -> end

Then the iterator sits at the end, we can do backward iteration:

while (lit.hasPrevious()) process2(lit.previous()); // end -> begin

How to stop execution after a certain time in Java?

If you can't go over your time limit (it's a hard limit) then a thread is your best bet. You can use a loop to terminate the thread once you get to the time threshold. Whatever is going on in that thread at the time can be interrupted, allowing calculations to stop almost instantly. Here is an example:

Thread t = new Thread(myRunnable); // myRunnable does your calculations

long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;

t.start(); // Kick off calculations

while (System.currentTimeMillis() < endTime) {
    // Still within time theshold, wait a little longer
    try {
         Thread.sleep(500L);  // Sleep 1/2 second
    } catch (InterruptedException e) {
         // Someone woke us up during sleep, that's OK
    }
}

t.interrupt();  // Tell the thread to stop
t.join();       // Wait for the thread to cleanup and finish

That will give you resolution to about 1/2 second. By polling more often in the while loop, you can get that down.

Your runnable's run would look something like this:

public void run() {
    while (true) {
        try {
            // Long running work
            calculateMassOfUniverse();
        } catch (InterruptedException e) {
            // We were signaled, clean things up
            cleanupStuff();
            break;           // Leave the loop, thread will exit
    }
}

Update based on Dmitri's answer

Dmitri pointed out TimerTask, which would let you avoid the loop. You could just do the join call and the TimerTask you setup would take care of interrupting the thread. This would let you get more exact resolution without having to poll in a loop.

What's the actual use of 'fail' in JUnit test case?

I've used it in the case where something may have gone awry in my @Before method.

public Object obj;

@Before
public void setUp() {
    // Do some set up
    obj = new Object();
}

@Test
public void testObjectManipulation() {
    if(obj == null) {
        fail("obj should not be null");
     }

    // Do some other valuable testing
}

How to get element by class name?

You need to use the document.getElementsByClassName('class_name');

and dont forget that the returned value is an array of elements so if you want the first one use:

document.getElementsByClassName('class_name')[0]

UPDATE

Now you can use:

document.querySelector(".class_name") to get the first element with the class_name CSS class (null will be returned if non of the elements on the page has this class name)

or document.querySelectorAll(".class_name") to get a NodeList of elements with the class_name css class (empty NodeList will be returned if non of. the elements on the the page has this class name).

@Resource vs @Autowired

In spring pre-3.0 it doesn't matter which one.

In spring 3.0 there's support for the standard (JSR-330) annotation @javax.inject.Inject - use it, with a combination of @Qualifier. Note that spring now also supports the @javax.inject.Qualifier meta-annotation:

@Qualifier
@Retention(RUNTIME)
public @interface YourQualifier {}

So you can have

<bean class="com.pkg.SomeBean">
   <qualifier type="YourQualifier"/>
</bean>

or

@YourQualifier
@Component
public class SomeBean implements Foo { .. }

And then:

@Inject @YourQualifier private Foo foo;

This makes less use of String-names, which can be misspelled and are harder to maintain.


As for the original question: both, without specifying any attributes of the annotation, perform injection by type. The difference is:

  • @Resource allows you to specify a name of the injected bean
  • @Autowired allows you to mark it as non-mandatory.

Two-dimensional array in Swift

In Swift 4

var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]

How do I configure PyCharm to run py.test tests?

Please go to File| Settings | Tools | Python Integrated Tools and change the default test runner to py.test. Then you'll get the py.test option to create tests instead of the unittest one.

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

Is your website also on the oxfordlearnersdictionaries.com domain? or your trying to make a call to a domain and the same origin policy is blocking you?

Unless you have permission to set header via CORS on the oxfordlearnersdictionaries.com domain you may want to look for another approach.

How to install PHP intl extension in Ubuntu 14.04

you could search with aptitude search intl after you can choose the right one, for example sudo aptitude install php-intl and finally sudo service apache2 restart

good Luck!

jQuery - Illegal invocation

Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

In HTML:

<div ng-repeat="product in products | filter: colorFilter">

In Angular:

$scope.colorFilter = function (item) { 
  if (item.color === 'red' || item.color === 'blue') {
  return item;
 }
};

Check if value exists in column in VBA

Just to modify scott's answer to make it a function:

Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant

    Dim LookAtWhat As Integer

    If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart

    With RngIn
        Set FindFirstInRange = .Find(What:=FindString, _
                                     After:=.Cells(.Cells.Count), _
                                     LookIn:=xlValues, _
                                     LookAt:=LookAtWhat, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlNext, _
                                     MatchCase:=UseCase)

        If FindFirstInRange Is Nothing Then FindFirstInRange = False

    End With

End Function

This returns FALSE if the value isn't found, and if it's found, it returns the range.

You can optionally tell it to be case-sensitive, and/or to allow partial-word matches.

I took out the TRIM because you can add that beforehand if you want to.

An example:

MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address

That does a case-sensitive, partial-word search on the 2nd row and displays a box with the address. The following is the same search, but a whole-word search that is not case-sensitive:

MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address

You can easily tweak this function to your liking or change it from a Variant to to a boolean, or whatever, to speed it up a little.

Do note that VBA's Find is sometimes slower than other methods like brute-force looping or Match, so don't assume that it's the fastest just because it's native to VBA. It's more complicated and flexible, which also can make it not always as efficient. And it has some funny quirks to look out for, like the "Object variable or with block variable not set" error.

Whoops, looks like something went wrong. Laravel 5.0

First run command composer install

Then check for .env.example and .env files in your project folder.

.env file is your main configuration file for database and .env.example is backup file for .env file.

.env.example file will always be there but sometimes .env file can be missing. just copy the .env.example file and paste in the same project folder with filename .env .

now run php artisan key:generate command. this will generate key for your application.

PHP - Notice: Undefined index:

You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an

if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

Python - Create list with numbers between 2 values?

In python you can do this very eaisly

start=0
end=10
arr=list(range(start,end+1))
output: arr=[0,1,2,3,4,5,6,7,8,9,10]

or you can create a recursive function that returns an array upto a given number:

ar=[]
def diff(start,end):
    if start==end:
        d.append(end)
        return ar
    else:
        ar.append(end)
        return diff(start-1,end) 

output: ar=[10,9,8,7,6,5,4,3,2,1,0]

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

Comparing arrays in C#

For .NET 4.0 and higher, you can compare elements in array or tuples using the StructuralComparisons type:

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };
        
Console.WriteLine (a1 == a2);        // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2));  // False (because arrays is reference types)
        
IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer)); 

Image size (Python, OpenCV)

Here is a method that returns the image dimensions:

from PIL import Image
import os

def get_image_dimensions(imagefile):
    """
    Helper function that returns the image dimentions

    :param: imagefile str (path to image)
    :return dict (of the form: {width:<int>, height=<int>, size_bytes=<size_bytes>)
    """
    # Inline import for PIL because it is not a common library
    with Image.open(imagefile) as img:
        # Calculate the width and hight of an image
        width, height = img.size

    # calculat ethe size in bytes
    size_bytes = os.path.getsize(imagefile)

    return dict(width=width, height=height, size_bytes=size_bytes)

Does bootstrap 4 have a built in horizontal divider?

For dropdowns, yes:

https://v4-alpha.getbootstrap.com/components/dropdowns/

<div class="dropdown-menu">
  <a class="dropdown-item" href="#">Action</a>
  <a class="dropdown-item" href="#">Another action</a>
  <a class="dropdown-item" href="#">Something else here</a>
  <div class="dropdown-divider"></div>
  <a class="dropdown-item" href="#">Separated link</a>
</div>

Selenium Webdriver move mouse to Point

Using MoveToElement you will be able to find or click in whatever point you want, you have just to define the first parameter, it can be the session(winappdriver) or driver(in other ways) which is created when you instance WindowsDriver. Otherwise you can set as first parameter a grid (my case), a list, a panel or whatever you want.

Note: The top-left of your first parameter element will be the position X = 0 and Y = 0

   Actions actions = new Actions(this.session);
    int xPosition = this.session.FindElementsByAccessibilityId("GraphicView")[0].Size.Width - 530;
    int yPosition = this.session.FindElementsByAccessibilityId("GraphicView")[0].Size.Height- 150;
    actions.MoveToElement(this.xecuteClientSession.FindElementsByAccessibilityId("GraphicView")[0], xPosition, yPosition).ContextClick().Build().Perform();

babel-loader jsx SyntaxError: Unexpected token

Since the answer above still leaves some people in the dark, here's what a complete webpack.config.js might look like:

_x000D_
_x000D_
var path = require('path');_x000D_
var config = {_x000D_
    entry: path.resolve(__dirname, 'app/main.js'),_x000D_
    output: {_x000D_
        path: path.resolve(__dirname, 'build'),_x000D_
        filename: 'bundle.js'_x000D_
    },_x000D_
    module: {_x000D_
        loaders: [{_x000D_
            test: /\.jsx?$/,_x000D_
            loader: 'babel',_x000D_
            query:_x000D_
            {_x000D_
                presets:['es2015', 'react']_x000D_
            }_x000D_
        }]_x000D_
    },_x000D_
_x000D_
};_x000D_
_x000D_
module.exports = config;
_x000D_
_x000D_
_x000D_

How to create JSON post to api using C#

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

Regex pattern for numeric values

This will allow decimal numbers (or whole numbers) that don't start with zero:

^(([1-9]*)|(([1-9]*)\.([0-9]*)))$

If you want to allow numbers that start with zero, you can do :

^(([0-9]*)|(([0-9]*)\.([0-9]*)))$

Best algorithm for detecting cycles in a directed graph

If a graph satisfy this property

|e| > |v| - 1

then the graph contains at least on cycle.

What does "Git push non-fast-forward updates were rejected" mean?

In my case for exact same error, I was also not the only developer.

So I went to commit & push my changes at same time, seen at bottom of the Commit dialog popup:

Checked option for: Push changes immediately to origin

...but I made the huge mistake of forgetting to hit the Fetch button to see if I have latest, which I did not.

The commit successfully executed, however not the push, but instead gives the same mentioned error; ...even though other developers didn't alter same files as me, I cannot pull latest as same error is presented.

The GUI Solution

Most of the time I prefer sticking with Sourcetree's GUI (Graphical User Interface). This solution might not be ideal, however this is what got things going again for me without worrying that I may lose my changes or compromise more recent updates from other developers.

STEP 1

Right-click on the commit right before yours to undo your locally committed changes and select Reset current branch to this commit like so:

Sourcetree window with right-clicked commit and selecting: Reset current branch to this commit

STEP 2

Once all the loading spinners disappear and Sourcetree is done loading the previous commit, at the top-left of window, click on Pull button...

Sourcetree window with with the Pull button highlighted

...then a dialog popup will appear, and click the OK button at bottom-right:

Sourcetree window dialog popup with the OK button highlighted

STEP 3

After pulling latest, if you do not get any errors, skip to STEP 4 (next step below). Otherwise if you discover any merge conflicts at this point, like I did with my Web.config file:

Sourcetree window showing the error hint: Updates were rejected because the tip of your current branch is behind

...then click on the Stash button at the top, a dialog popup will appear and you will need to write a Descriptive-name-of-your-changes, then click the OK button:

Sourcetree window with Stash button highlighted and dialog popup showing input to name your stash with OK button highlighted

...once Sourcetree is done stashing your altered file(s), repeat actions in STEP 2 (previous step above), and then your local files will have latest changes. Now your changes can be reapplied by opening your STASHES seen at bottom of Sourcetree left column, use the arrow to expand your stashes, then right-click to choose Apply Stash 'Descriptive-name-of-your-changes', and after select OK button in dialog popup that appears:

Sourcetree window with the Stashes section expanded and changes right-clicked with Apply Stash highlighted

Sourcetree dialog popup ask your to confirm if you would like to apply stash you your local copy

IF you have any Merge Conflict(s) right now, go to your preferred text-editor, like Visual Studio Code, and in the affected files select the Accept Incoming Change link, then save:

enter image description here

Then back to Sourcetree, click on the Commit button at top:

enter image description here

then right-click on the conflicted file(s), and under Resolve Conflicts select the Mark Resolved option:

enter image description here

STEP 4

Finally!!! We are now able to commit our file(s), also checkmark the Push changes immediately to origin option before clicking the Commit button:

enter image description here

P.S. while writing this, a commit was submitted by another developer right before I got to commit, so had to pretty much repeat steps.

Git credential helper - update password

Just cd in the directory where you have installed git-credential-winstore. If you don't know where, just run this in Git Bash:

cat ~/.gitconfig

It should print something looking like:

[credential]
    helper = !'C:\\ProgramFile\\GitCredStore\\git-credential-winstore.exe'

In this case, you repository is C:\ProgramFile\GitCredStore. Once you are inside this folder using Git Bash or the Windows command, just type:

git-credential-winstore.exe erase
host=github.com
protocol=https

Don't forget to press Enter twice after protocol=https.

Android Facebook style slide

I've been playing with this the past few days and I've come up with a solution that's quite straightforward in the end, and which works pre-Honeycomb. My solution was to animate the View I want to slide (FrameLayout for me) and to listen for the end of the animation (at which point to offset the View's left/right position). I've pasted my solution here: How to animate a View's translation

How can I get a Unicode character's code?

In Java, char is technically a "16-bit integer", so you can simply cast it to int and you'll get it's code. From Oracle:

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

So you can simply cast it to int.

char registered = '®';
System.out.println(String.format("This is an int-code: %d", (int) registered));
System.out.println(String.format("And this is an hexa code: %x", (int) registered));

LINQ orderby on date field in descending order

I don't believe that Distinct() is guaranteed to maintain the order of the set.

Try pulling out an anonymous type first and distinct/sort on that before you convert to string:

var ud = env.Select(d => new 
                         {
                             d.ReportDate.Year,
                             d.ReportDate.Month,
                             FormattedDate = d.ReportDate.ToString("yyyy-MMM")
                         })
            .Distinct()
            .OrderByDescending(d => d.Year)
            .ThenByDescending(d => d.Month)
            .Select(d => d.FormattedDate);

How to create a Custom Dialog box in android?

Create alert Dialog layout something like this

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:text="Custom Alert Dialog"
        android:layout_height="40dp">
    </Button>
</LinearLayout>

and Add below code on your Activity class

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

    LayoutInflater inflate = LayoutInflater.from(this);
    alertView = inflate.inflate(R.layout.your_alert_layout, null);
    Button btn= (Button) alertView.findViewById(R.id.btn);

    showDialog();
  }

 public void showDialog(){
        Dialog alertDialog = new Dialog(RecognizeConceptsActivity.this);
        alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        alertDialog.setContentView(alertView);
        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alertDialog.show();
    }

How to target the href to div

if you use

angularjs

you have just to write the right css in order to frame you div html code

<div 
style="height:51px;width:111px;margin-left:203px;" 
ng-click="nextDetail()">
</div>


JS Code(in your controller):

$scope.nextDetail = function()
{
....
}

How to fix Error: laravel.log could not be opened?

Never set a directory to 777. you should change directory ownership. so set your current user that you are logged in with as owner and the webserver user (www-data, apache, ...) as the group. You can try this:

sudo chown -R $USER:www-data storage
sudo chown -R $USER:www-data bootstrap/cache

then to set directory permission try this:

chmod -R 775 storage
chmod -R 775 bootstrap/cache

Update:

Webserver user and group depend on your webserver and your OS. to figure out what's your web server user and group use the following commands. for nginx use:

ps aux|grep nginx|grep -v grep

for apache use:

ps aux | egrep '(apache|httpd)'