Programs & Examples On #Ora 00918

ORA-00918: column ambiguously defined

ORA-00918: column ambiguously defined in SELECT *

You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:

SELECT DISTINCT
    coaches.id,
    people.*,
    users.*,
    coaches.*
FROM "COACHES"
    INNER JOIN people ON people.id = coaches.person_id
    INNER JOIN users ON coaches.person_id = users.person_id
    LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
    rownum <= 25

It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.

$(this).serialize() -- How to add a value?

Don't forget you can always do:

<input type="hidden" name="NonFormName" value="NonFormValue" />

in your actual form, which may be better for your code depending on the case.

how to delete all cookies of my website in php

I agree with some of the above answers. I would just recommend replacing "time()-1000" with "1". A value of "1" means January 1st, 1970, which ensures expiration 100%. Therefore:

setcookie($name, '', 1);
setcookie($name, '', 1, '/');

Best way to read a large file into a byte array in C#?

Overview: if your image is added as a action= embedded resource then use the GetExecutingAssembly to retrieve the jpg resource into a stream then read the binary data in the stream into an byte array

   public byte[] GetAImage()
    {
        byte[] bytes=null;
        var assembly = Assembly.GetExecutingAssembly();
        var resourceName = "MYWebApi.Images.X_my_image.jpg";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        {
            bytes = new byte[stream.Length];
            stream.Read(bytes, 0, (int)stream.Length);
        }
        return bytes;

    }

Extract time from date String

If you have date in integers, you could use like here:

Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);

how to activate a textbox if I select an other option in drop down box

Coded an example at http://jsbin.com/orisuv

HTML

<select name="color" onchange='checkvalue(this.value)'> 
    <option>pick a color</option>  
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
</select> 
<input type="text" name="color" id="color" style='display:none'/>

Javascript

function checkvalue(val)
{
    if(val==="others")
       document.getElementById('color').style.display='block';
    else
       document.getElementById('color').style.display='none'; 
}

How to use concerns in Rails 4

This post helped me understand concerns.

# app/models/trader.rb
class Trader
  include Shared::Schedule
end

# app/models/concerns/shared/schedule.rb
module Shared::Schedule
  extend ActiveSupport::Concern
  ...
end

How to pass command line arguments to a rake task

You can specify formal arguments in rake by adding symbol arguments to the task call. For example:

require 'rake'

task :my_task, [:arg1, :arg2] do |t, args|
  puts "Args were: #{args} of class #{args.class}"
  puts "arg1 was: '#{args[:arg1]}' of class #{args[:arg1].class}"
  puts "arg2 was: '#{args[:arg2]}' of class #{args[:arg2].class}"
end

task :invoke_my_task do
  Rake.application.invoke_task("my_task[1, 2]")
end

# or if you prefer this syntax...
task :invoke_my_task_2 do
  Rake::Task[:my_task].invoke(3, 4)
end

# a task with prerequisites passes its 
# arguments to it prerequisites
task :with_prerequisite, [:arg1, :arg2] => :my_task #<- name of prerequisite task

# to specify default values, 
# we take advantage of args being a Rake::TaskArguments object
task :with_defaults, :arg1, :arg2 do |t, args|
  args.with_defaults(:arg1 => :default_1, :arg2 => :default_2)
  puts "Args with defaults were: #{args}"
end

Then, from the command line:

> rake my_task[1,false]
Args were: {:arg1=>"1", :arg2=>"false"} of class Rake::TaskArguments
arg1 was: '1' of class String
arg2 was: 'false' of class String

> rake "my_task[1, 2]"
Args were: {:arg1=>"1", :arg2=>"2"}

> rake invoke_my_task
Args were: {:arg1=>"1", :arg2=>"2"}

> rake invoke_my_task_2
Args were: {:arg1=>3, :arg2=>4}

> rake with_prerequisite[5,6]
Args were: {:arg1=>"5", :arg2=>"6"}

> rake with_defaults
Args with defaults were: {:arg1=>:default_1, :arg2=>:default_2}

> rake with_defaults['x','y']
Args with defaults were: {:arg1=>"x", :arg2=>"y"}

As demonstrated in the second example, if you want to use spaces, the quotes around the target name are necessary to keep the shell from splitting up the arguments at the space.

Looking at the code in rake.rb, it appears that rake does not parse task strings to extract arguments for prerequisites, so you can't do task :t1 => "dep[1,2]". The only way to specify different arguments for a prerequisite would be to invoke it explicitly within the dependent task action, as in :invoke_my_task and :invoke_my_task_2.

Note that some shells (like zsh) require you to escape the brackets: rake my_task\['arg1'\]

Centering elements in jQuery Mobile

You can make the button an anchor element, and put it in a paragraph with the attribute:

align='center'

Worked for me.

Open a new tab in the background?

I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.


function newTab(url)
{
    var tab=window.open("");
    tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
    tab.document.close();
    window.location.href=url;
}

Fiddle : http://jsfiddle.net/tFCnA/show/

Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)


The only thing you may doesn't like is that the new tab opens before the main page.

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You're not reading the file content:

my_file_contents = f.read()

See the docs for further infos

You could, without calling read() or readlines() loop over your file object:

f = open('goodlines.txt')
for line in f:
    print(line)

If you want a list out of it (without \n as you asked)

my_list = [line.rstrip('\n') for line in f]

How does the communication between a browser and a web server take place?

Your browser is sitting on top of TCP/IP, as the web is based on standards, usually port 80, what happens is when you enter an address, such as google.com, your computer where the browser is running on, creates packets of data, encapsulated at each layer accordingly to the OSI standards, (think of envelopes of different sizes, packed into each envelope of next size), OSI defines 7 layers, in one of the envelopes contains the source address and destination address(that is the website) encoded in binary.

As it reaches the 1st layer, in OSI terms, it gets transmitted across the media transmitter (such as cable, DSL).

If you are connected via ISP, the layered pack of envelopes gets transmitted to the ISP, the ISP's network system, peeks through the layered pack of envelopes by decoding in reverse order to find out the address, then the ISP checks their Domain Name System database to find out if they have a route to that address (cached in memory, if it does, it forwards it across the internet network - again layered pack of envelopes).

If it doesn't, the ISP interrogates the top level DNS server to say 'Hey, get me the route for the address as supplied by you, ie. the browser', the top level DNS server then passes the route to the ISP which is then stored in the ISP's server memory.

The layered pack of envelopes are transmitted and received by the website server after successful routing of the packets (think of routing as signposts for directions to get to the server), which in turn, unpacks the layered pack of envelopes, extracts the source address and says 'Aha, that is for me, right, I know the destination address (that is you, the browser), then the server packetizes the webpages into a packed layered envelopes and sends it back (usually in reverse route, but not always the case).

Your browser than receives the packetized envelopes and unpacks each of them. Then your computer descrambles the data and your browser renders the pages on the screen.

I hope this answer is sufficient enough for your understanding.

How to convert "0" and "1" to false and true

How about:

return (returnValue == "1");

or as suggested below:

return (returnValue != "0");

The correct one will depend on what you are looking for as a success result.

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

Lining up labels with radio buttons in bootstrap

This is all nicely lined up including the field label. Lining up the field label was the tricky part.

enter image description here

HTML Code:

<div class="form-group">
    <label class="control-label col-md-5">Create a</label>
    <div class="col-md-7">
        <label class="radio-inline control-label">
            <input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
        </label>
        <label class="radio-inline control-label">
            <input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
        </label>
    </div>
</div>

CSHTML / Razor Code:

<div class="form-group">
    @Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
    <div class="col-md-7">
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
        </label>
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
        </label>
    </div>
</div>

How to prevent robots from automatically filling up a form?

The best solution I've found to avoid getting spammed by bots is using a very trivial question or field on your form.

Try adding a field like these :

  • Copy "hello" in the box aside
  • 1+1 = ?
  • Copy the website name in the box

These tricks require the user to understant what must be input on the form, thus making it much harder to be the target of massive bot form-filling.

EDIT

The backside of this method, as you stated in your question, is the extra step for the user to validate its form. But, in my opinion, it is far simpler than a captcha and the overhead when filling the form is not more than 5 seconds, which seems acceptable from the user point of view.

How to remove array element in mongodb?

In Mongoose: from the document:

To remove a document from a subdocument array we may pass an object with a matching _id.

contact.phone.pull({ _id: itemId }) // remove
contact.phone.pull(itemId); // this also works

See Leonid Beschastny's answer for the correct answer.

C# cannot convert method to non delegate type

Because getTitle is not a string, it returns a reference or delegate to a method (if you like), if you don't explicitly call the method.

Call your method this way:

string t= obj.getTitle() ; //obj.getTitle()  says return the title string object

However, this would work:

Func<string> method = obj.getTitle; // this compiles to a delegate and points to the method

string s = method();//call the delegate or using this syntax `method.Invoke();`

How to unpackage and repackage a WAR file

copy your war file to /tmp now extract the contents:

cp warfile.war /tmp
cd /tmp
unzip warfile.war
cd WEB-INF
nano web.xml (or vim or any editor you want to use)
cd ..
zip -r -u warfile.war WEB-INF

now you have in /tmp/warfile.war your file updated.

Remove all the children DOM elements in div

If you are looking for a modern >1.7 Dojo way of destroying all node's children this is the way:

// Destroys all domNode's children nodes
// domNode can be a node or its id:
domConstruct.empty(domNode);

Safely empty the contents of a DOM element. empty() deletes all children but keeps the node there.

Check "dom-construct" documentation for more details.

// Destroys domNode and all it's children
domConstruct.destroy(domNode);

Destroys a DOM element. destroy() deletes all children and the node itself.

Find length of 2D array Python

You can use numpy.shape.

import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])

Result:

>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.shape(x)
(3, 2)

First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.

Get values from other sheet using VBA

SomeVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value

did not work. However the following code only worked for me.

SomeVal = ThisWorkbook.Sheets(2).cells(aRow,aCol).Value

Differences between arm64 and aarch64

AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.

As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.

So AArch64 and ARM64 refer to the same thing.

Spring Boot Java Config Set Session Timeout

server.session.timeout in the application.properties file is now deprecated. The correct setting is:

server.servlet.session.timeout=60s

Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.

JPA: How to get entity based on field value other than ID?

It is not a "problem" as you stated it.

Hibernate has the built-in find(), but you have to build your own query in order to get a particular object. I recommend using Hibernate's Criteria :

Criteria criteria = session.createCriteria(YourClass.class);
YourObject yourObject = criteria.add(Restrictions.eq("yourField", yourFieldValue))
                             .uniqueResult();

This will create a criteria on your current class, adding the restriction that the column "yourField" is equal to the value yourFieldValue. uniqueResult() tells it to bring a unique result. If more objects match, you should retrive a list.

List<YourObject> list = criteria.add(Restrictions.eq("yourField", yourFieldValue)).list();

If you have any further questions, please feel free to ask. Hope this helps.

How to generate access token using refresh token through google drive API?

If you are using web api then you should make a http POST call to URL : https://www.googleapis.com/oauth2/v4/token with following request body

client_id: <YOUR_CLIENT_ID>
client_secret: <YOUR_CLIENT_SECRET>
refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
grant_type: refresh_token

refresh token never expires so you can use it any number of times. The response will be a JSON like this:

{
  "access_token": "your refreshed access token",
  "expires_in": 3599,
  "scope": "Set of scope which you have given",
  "token_type": "Bearer"
}

Freemarker iterating over hashmap keys

If using a BeansWrapper with an exposure level of Expose.SAFE or Expose.ALL, then the standard Java approach of iterating the entry set can be employed:

For example, the following will work in Freemarker (since at least version 2.3.19):

<#list map.entrySet() as entry>  
  <input type="hidden" name="${entry.key}" value="${entry.value}" />
</#list>

In Struts2, for instance, an extension of the BeanWrapper is used with the exposure level defaulted to allow this manner of iteration.

How to take a first character from the string

Try this:

Dim s = "RAJAN"
Dim firstChar = s(0)

You can even do this:

Dim firstChar = "RAJAN"(0)

How can I update the current line in a C# Windows Console App?

So far we have three competing alternatives for how to do this:

Console.Write("\r{0}   ", value);                      // Option 1: carriage return
Console.Write("\b\b\b\b\b{0}", value);                 // Option 2: backspace
{                                                      // Option 3 in two parts:
    Console.SetCursorPosition(0, Console.CursorTop);   // - Move cursor
    Console.Write(value);                              // - Rewrite
}

I've always used Console.CursorLeft = 0, a variation on the third option, so I decided to do some tests. Here's the code I used:

public static void CursorTest()
{
    int testsize = 1000000;

    Console.WriteLine("Testing cursor position");
    Stopwatch sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < testsize; i++)
    {
        Console.Write("\rCounting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("\nTime using \\r: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    int top = Console.CursorTop;
    for (int i = 0; i < testsize; i++)
    {
        Console.SetCursorPosition(0, top);        
        Console.Write("Counting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("\nTime using CursorLeft: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    Console.Write("Counting:          ");
    for (int i = 0; i < testsize; i++)
    {        
        Console.Write("\b\b\b\b\b\b\b\b{0,8}", i);
    }

    sw.Stop();
    Console.WriteLine("\nTime using \\b: {0}", sw.ElapsedMilliseconds);
}

On my machine, I get the following results:

  • Backspaces: 25.0 seconds
  • Carriage Returns: 28.7 seconds
  • SetCursorPosition: 49.7 seconds

Additionally, SetCursorPosition caused noticeable flicker that I didn't observe with either of the alternatives. So, the moral is to use backspaces or carriage returns when possible, and thanks for teaching me a faster way to do this, SO!


Update: In the comments, Joel suggests that SetCursorPosition is constant with respect to the distance moved while the other methods are linear. Further testing confirms that this is the case, however constant time and slow is still slow. In my tests, writing a long string of backspaces to the console is faster than SetCursorPosition until somewhere around 60 characters. So backspace is faster for replacing portions of the line shorter than 60 characters (or so), and it doesn't flicker, so I'm going to stand by my initial endorsement of \b over \r and SetCursorPosition.

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

In addition to the accepted answer, I would like to add one info, that NuGet packages in Visual Studio 2017 are located in the project file itself. I.e., right click on the project -> edit, to find all package reference entries.

How to set the matplotlib figure default size in ipython notebook?

If you don't have this ipython_notebook_config.py file, you can create one by following the readme and typing

ipython profile create

How do I store an array in localStorage?

Use JSON.stringify() and JSON.parse() as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three|||bars).

How to start a background process in Python?

Both capture output and run on background with threading

As mentioned on this answer, if you capture the output with stdout= and then try to read(), then the process blocks.

However, there are cases where you need this. For example, I wanted to launch two processes that talk over a port between them, and save their stdout to a log file and stdout.

The threading module allows us to do that.

First, have a look at how to do the output redirection part alone in this question: Python Popen: Write to stdout AND log file simultaneously

Then:

main.py

#!/usr/bin/env python3

import os
import subprocess
import sys
import threading

def output_reader(proc, file):
    while True:
        byte = proc.stdout.read(1)
        if byte:
            sys.stdout.buffer.write(byte)
            sys.stdout.flush()
            file.buffer.write(byte)
        else:
            break

with subprocess.Popen(['./sleep.py', '0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc1, \
     subprocess.Popen(['./sleep.py', '10'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc2, \
     open('log1.log', 'w') as file1, \
     open('log2.log', 'w') as file2:
    t1 = threading.Thread(target=output_reader, args=(proc1, file1))
    t2 = threading.Thread(target=output_reader, args=(proc2, file2))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

sleep.py

#!/usr/bin/env python3

import sys
import time

for i in range(4):
    print(i + int(sys.argv[1]))
    sys.stdout.flush()
    time.sleep(0.5)

After running:

./main.py

stdout get updated every 0.5 seconds for every two lines to contain:

0
10
1
11
2
12
3
13

and each log file contains the respective log for a given process.

Inspired by: https://eli.thegreenplace.net/2017/interacting-with-a-long-running-child-process-in-python/

Tested on Ubuntu 18.04, Python 3.6.7.

SQL Server CASE .. WHEN .. IN statement

It might be easier to read when written out in longhand using the 'simple case' e.g.

CASE DeviceID 
   WHEN '7  ' THEN '01'
   WHEN '10 ' THEN '01'
   WHEN '62 ' THEN '01'
   WHEN '58 ' THEN '01'
   WHEN '60 ' THEN '01'
   WHEN '46 ' THEN '01'
   WHEN '48 ' THEN '01'
   WHEN '50 ' THEN '01'
   WHEN '137' THEN '01'
   WHEN '139' THEN '01'
   WHEN '142' THEN '01'
   WHEN '143' THEN '01'
   WHEN '164' THEN '01'
   WHEN '8  ' THEN '02'
   WHEN '9  ' THEN '02'
   WHEN '63 ' THEN '02'
   WHEN '59 ' THEN '02'
   WHEN '61 ' THEN '02'
   WHEN '47 ' THEN '02'
   WHEN '49 ' THEN '02'
   WHEN '51 ' THEN '02'
   WHEN '138' THEN '02'
   WHEN '140' THEN '02'
   WHEN '141' THEN '02'
   WHEN '144' THEN '02'
   WHEN '165' THEN '02'
   ELSE 'NA' 
END AS clocking

...which kind makes me thing that perhaps you could benefit from a lookup table to which you can JOIN to eliminate the CASE expression entirely.

Using Address Instead Of Longitude And Latitude With Google Maps API

var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
  zoom: 8,
  center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}

function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == 'OK') {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
    });
  } else {
    alert('Geocode was not successful for the following reason: ' + status);
  }
});
}

<body onload="initialize()">
 <div id="map" style="width: 320px; height: 480px;"></div>
 <div>
   <input id="address" type="textbox" value="Sydney, NSW">
   <input type="button" value="Encode" onclick="codeAddress()">
 </div>
</body>

Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding

how to compare two elements in jquery

You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.

Assuming:

<div id="a" class="a"></div>

this:

$('div.a')[0] == $('div#a')[0]

returns true.

How do I add space between two variables after a print in Python

You can do it this way in python3:

print(a,b,end=" ")

MAC addresses in JavaScript

i was looking for the same problem and stumbled upon the following code.

How to get Client MAC address(Web):

To get the client MAC address only way we can rely on JavaScript and Active X control of Microsoft.It is only work in IE if Active X enable for IE. As the ActiveXObject is not available with the Firefox, its not working with the firefox and is working fine in IE.

This script is for IE only:

_x000D_
_x000D_
function showMacAddress() {_x000D_
    var obj = new ActiveXObject("WbemScripting.SWbemLocator");_x000D_
    var s = obj.ConnectServer(".");_x000D_
    var properties = s.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");_x000D_
    var e = new Enumerator(properties);_x000D_
    var output;_x000D_
    output = '<table border="0" cellPadding="5px" cellSpacing="1px" bgColor="#CCCCCC">';_x000D_
    output = output + '<tr bgColor="#EAEAEA"><td>Caption</td><td>MACAddress</td></tr>';_x000D_
    while (!e.atEnd()) {_x000D_
        e.moveNext();_x000D_
        var p = e.item();_x000D_
        if (!p) continue;_x000D_
        output = output + '<tr bgColor="#FFFFFF">';_x000D_
        output = output + '<td>' + p.Caption; +'</td>';_x000D_
        output = output + '<td>' + p.MACAddress + '</td>';_x000D_
        output = output + '</tr>';_x000D_
    }_x000D_
    output = output + '</table>';_x000D_
    document.getElementById("box").innerHTML = output;_x000D_
}_x000D_
_x000D_
showMacAddress();
_x000D_
<div id='box'></div>
_x000D_
_x000D_
_x000D_

How does "cat << EOF" work in bash?

The cat <<EOF syntax is very useful when working with multi-line text in Bash, eg. when assigning multi-line string to a shell variable, file or a pipe.

Examples of cat <<EOF syntax usage in Bash:

1. Assign multi-line string to a shell variable

$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)

The $sql variable now holds the new-line characters too. You can verify with echo -e "$sql".

2. Pass multi-line string to a file in Bash

$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF

The print.sh file now contains:

#!/bin/bash
echo $PWD
echo /home/user

3. Pass multi-line string to a pipe in Bash

$ cat <<EOF | grep 'b' | tee b.txt
foo
bar
baz
EOF

The b.txt file contains bar and baz lines. The same output is printed to stdout.

How can I override inline styles with external CSS?

The only way to override inline style is by using !important keyword beside the CSS rule. The following is an example of it.

_x000D_
_x000D_
div {
        color: blue !important;
       /* Adding !important will give this rule more precedence over inline style */
    }
_x000D_
<div style="font-size: 18px; color: red;">
    Hello, World. How can I change this to blue?
</div>
_x000D_
_x000D_
_x000D_

Important Notes:

  • Using !important is not considered as a good practice. Hence, you should avoid both !important and inline style.

  • Adding the !important keyword to any CSS rule lets the rule forcefully precede over all the other CSS rules for that element.

  • It even overrides the inline styles from the markup.

  • The only way to override is by using another !important rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code.

  • Must Read - CSS Specificity by MDN

Auto increment in MongoDB to store sequence of Unique User ID

As selected answer says you can use findAndModify to generate sequential IDs.

But I strongly disagree with opinion that you should not do that. It all depends on your business needs. Having 12-byte ID may be very resource consuming and cause significant scalability issues in future.

I have detailed answer here.

Show Current Location and Update Location in MKMapView in Swift

For swift 3 and XCode 8 I find this answer:

  • First, you need set privacy into info.plist. Insert string NSLocationWhenInUseUsageDescription with your description why you want get user location. For example, set string "For map in application".

  • Second, use this code example

    @IBOutlet weak var mapView: MKMapView!
    
    private var locationManager: CLLocationManager!
    private var currentLocation: CLLocation?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        mapView.delegate = self
    
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    
        // Check for Location Services
    
        if CLLocationManager.locationServicesEnabled() {
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        }
    }
    
    // MARK - CLLocationManagerDelegate
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        defer { currentLocation = locations.last }
    
        if currentLocation == nil {
            // Zoom to user location
            if let userLocation = locations.last {
                let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
                mapView.setRegion(viewRegion, animated: false)
            }
        }
    }
    
  • Third, set User Location flag in storyboard for mapView.

Best way to convert pdf files to tiff files

using python this is what I ended up with

    import os
    os.popen(' '.join([
                       self._ghostscriptPath + 'gswin32c.exe', 
                       '-q',
                       '-dNOPAUSE',
                       '-dBATCH',
                       '-r300',
                       '-sDEVICE=tiff12nc',
                       '-sPAPERSIZE=a4',
                       '-sOutputFile=%s %s' % (tifDest, pdfSource),
                       ]))

Convert a positive number to negative in C#

long negativeNumber = (long)positiveInt - (long)(int.MaxValue + 1);

Nobody said it had to be any particular negative number.

How to set value to form control in Reactive Forms in Angular

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.

patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.

In this scenario, we will want to use patchValue, since we are only updating user and questioning:

this.qService.editQue([params["id"]]).subscribe(res => {
  this.question = res;
  this.editqueForm.patchValue({
    user: this.question.user,
    questioning: this.question.questioning
  });
});

EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead

const { user, questioning } = this.question;

this.editqueForm.patchValue({
  user,
  questioning
});

Ta-dah!

How to modify JsonNode in Java?

You need to get ObjectNode type object in order to set values. Take a look at this

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

I did what @gbero said, and I changed the Android version number that Studio uses from 22 to 17 and it works.

I am using the backwards compatibility to build for Android ver 22 but to target 17 (idk if that's correctly said, I am still trying to figure this app stuff out) so that triggered the backwards compatibility, which afaik is what the android.support.v7.* is. This is probably a bug with their rendering code. Not sure if clearing the cache as suggested above was needed as rendering didn't work just after invalidating the cache, it started working after I changed the version to render. If I change back to version 22, the rendering breaks, if I switch back to 17, it works again.

my fix

Remove all the elements that occur in one list from another

Use the Python set type. That would be the most Pythonic. :)

Also, since it's native, it should be the most optimized method too.

See:

http://docs.python.org/library/stdtypes.html#set

http://docs.python.org/library/sets.htm (for older python)

# Using Python 2.7 set literal format.
# Otherwise, use: l1 = set([1,2,6,8])
#
l1 = {1,2,6,8}
l2 = {2,3,5,8}
l3 = l1 - l2

Centering in CSS Grid

You want this?

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr;_x000D_
  grid-template-rows: 100vh;_x000D_
  grid-gap: 0px 0px;_x000D_
}_x000D_
_x000D_
.left_bg {_x000D_
  display: subgrid;_x000D_
  background-color: #3498db;_x000D_
  grid-column: 1 / 1;_x000D_
  grid-row: 1 / 1;_x000D_
  z-index: 0;_x000D_
}_x000D_
_x000D_
.right_bg {_x000D_
  display: subgrid;_x000D_
  background-color: #ecf0f1;_x000D_
  grid-column: 2 / 2;_x000D_
  grid_row: 1 / 1;_x000D_
  z-index: 0;_x000D_
}_x000D_
_x000D_
.text {_x000D_
  font-family: Raleway;_x000D_
  font-size: large;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <!--everything on the page-->_x000D_
_x000D_
  <div class="left_bg">_x000D_
    <!--left background color of the page-->_x000D_
    <div class="text">_x000D_
      <!--left side text content-->_x000D_
      <p>Review my stuff</p>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="right_bg">_x000D_
    <!--right background color of the page-->_x000D_
    <div class="text">_x000D_
      <!--right side text content-->_x000D_
      <p>Hire me!</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I check if a Socket is currently connected in Java?

  • socket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • socket.getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • socket.getInetAddress().isReachable(int timeout): From isReachable(int timeout)

    Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

cannot convert data (type interface {}) to type string: need type assertion

According to the Go specification:

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.

A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.

In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.

If you were unsure if it was a string or not, you could test using the two return syntax.

str, ok := data.(string)

If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:

if str, ok := data.(string); ok {
    /* act on str */
} else {
    /* not string */
}

adding text to an existing text element in javascript via DOM

Instead of appending element you can just do.

 document.getElementById("p").textContent += " this has just been added";

_x000D_
_x000D_
document.getElementById("p").textContent += " this has just been added";
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Delayed function calls

There is no standard way to delay a call to a function other than to use a timer and events.

This sounds like the GUI anti pattern of delaying a call to a method so that you can be sure the form has finished laying out. Not a good idea.

How to configure Docker port mapping to use Nginx as an upstream proxy?

AJB's "Option B" can be made to work by using the base Ubuntu image and setting up nginx on your own. (It didn't work when I used the Nginx image from Docker Hub.)

Here is the Docker file I used:

FROM ubuntu
RUN apt-get update && apt-get install -y nginx
RUN ln -sf /dev/stdout /var/log/nginx/access.log
RUN ln -sf /dev/stderr /var/log/nginx/error.log
RUN rm -rf /etc/nginx/sites-enabled/default
EXPOSE 80 443
COPY conf/mysite.com /etc/nginx/sites-enabled/mysite.com
CMD ["nginx", "-g", "daemon off;"]

My nginx config (aka: conf/mysite.com):

server {
    listen 80 default;
    server_name mysite.com;

    location / {
        proxy_pass http://website;
    }
}

upstream website {
    server website:3000;
}

And finally, how I start my containers:

$ docker run -dP --name website website
$ docker run -dP --name nginx --link website:website nginx

This got me up and running so my nginx pointed the upstream to the second docker container which exposed port 3000.

Run certain code every n seconds

Here is a simple example compatible with APScheduler 3.00+:

# note that there are many other schedulers available
from apscheduler.schedulers.background import BackgroundScheduler

sched = BackgroundScheduler()

def some_job():
    print('Every 10 seconds')

# seconds can be replaced with minutes, hours, or days
sched.add_job(some_job, 'interval', seconds=10)
sched.start()

...

sched.shutdown()

Alternatively, you can use the following. Unlike many of the alternatives, this timer will execute the desired code every n seconds exactly (irrespective of the time it takes for the code to execute). So this is a great option if you cannot afford any drift.

import time
from threading import Event, Thread

class RepeatedTimer:

    """Repeat `function` every `interval` seconds."""

    def __init__(self, interval, function, *args, **kwargs):
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.start = time.time()
        self.event = Event()
        self.thread = Thread(target=self._target)
        self.thread.start()

    def _target(self):
        while not self.event.wait(self._time):
            self.function(*self.args, **self.kwargs)

    @property
    def _time(self):
        return self.interval - ((time.time() - self.start) % self.interval)

    def stop(self):
        self.event.set()
        self.thread.join()


# start timer
timer = RepeatedTimer(10, print, 'Hello world')

# stop timer
timer.stop()

Failed to instantiate module error in Angular js

I got this error due to not pointing the script to the correct path. So make absolutely sure that you are pointing to the correct path in you html file.

what is the difference between XSD and WSDL

XSD defines a schema which is a definition of how an XML document can be structured. You can use it to check that a given XML document is valid and follows the rules you've laid out in the schema.

WSDL is a XML document that describes a web service. It shows which operations are available and how data should be structured to send to those operations.

WSDL documents have an associated XSD that show what is valid to put in a WSDL document.

How to generate random positive and negative numbers in Java

public static int generatRandomPositiveNegitiveValue(int max , int min) {
    //Random rand = new Random();
    int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
    return ii;
}

PHP Configuration: It is not safe to rely on the system's timezone settings

Check for syntax errors in the php.ini file, specially before the Date paramaters, that prevent the file from being parsed correctly.

How to present UIAlertController when not in a view controller?

Swift

let alertController = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
//...
var rootViewController = UIApplication.shared.keyWindow?.rootViewController
if let navigationController = rootViewController as? UINavigationController {
    rootViewController = navigationController.viewControllers.first
}
if let tabBarController = rootViewController as? UITabBarController {
    rootViewController = tabBarController.selectedViewController
}
//...
rootViewController?.present(alertController, animated: true, completion: nil)

Objective-C

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
//...
id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
    rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;
}
if([rootViewController isKindOfClass:[UITabBarController class]])
{
    rootViewController = ((UITabBarController *)rootViewController).selectedViewController;
}
//...
[rootViewController presentViewController:alertController animated:YES completion:nil];

JQuery wait for page to finish loading before starting the slideshow?

You probably already know about $(document).ready(...). What you need is a preloading mechanism; something that fetches data (text or images or whatever) before showing it off. This can make a site feel much more professional.

Take a look at jQuery.Preload (there are others). jQuery.Preload has several ways of triggering preloading, and also provides callback functionality (when the image is preloaded, then show it). I have used it heavily, and it works great.

Here's how easy it is to get started with jQuery.Preload:

$(function() {
  // First get the preload fetches under way
  $.preload(["images/button-background.png", "images/button-highlight.png"]);
  // Then do anything else that you would normally do here
  doSomeStuff();
});

`ui-router` $stateParams vs. $state.params

Here in this article is clearly explained: The $state service provides a number of useful methods for manipulating the state as well as pertinent data on the current state. The current state parameters are accessible on the $state service at the params key. The $stateParams service returns this very same object. Hence, the $stateParams service is strictly a convenience service to quickly access the params object on the $state service.

As such, no controller should ever inject both the $state service and its convenience service, $stateParams. If the $state is being injected just to access the current parameters, the controller should be rewritten to inject $stateParams instead.

How does the SQL injection from the "Bobby Tables" XKCD comic work?

TL;DR

-- The application accepts input, in this case 'Nancy', without attempting to
-- sanitize the input, such as by escaping special characters
school=> INSERT INTO students VALUES ('Nancy');
INSERT 0 1

-- SQL injection occurs when input into a database command is manipulated to
-- cause the database server to execute arbitrary SQL
school=> INSERT INTO students VALUES ('Robert'); DROP TABLE students; --');
INSERT 0 1
DROP TABLE

-- The student records are now gone - it could have been even worse!
school=> SELECT * FROM students;
ERROR:  relation "students" does not exist
LINE 1: SELECT * FROM students;
                      ^

This drops (deletes) the student table.

(All code examples in this answer were run on a PostgreSQL 9.1.2 database server.)

To make it clear what's happening, let's try this with a simple table containing only the name field and add a single row:

school=> CREATE TABLE students (name TEXT PRIMARY KEY);
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "students_pkey" for table "students"
CREATE TABLE
school=> INSERT INTO students VALUES ('John');
INSERT 0 1

Let's assume the application uses the following SQL to insert data into the table:

INSERT INTO students VALUES ('foobar');

Replace foobar with the actual name of the student. A normal insert operation would look like this:

--                            Input:   Nancy
school=> INSERT INTO students VALUES ('Nancy');
INSERT 0 1

When we query the table, we get this:

school=> SELECT * FROM students;
 name
-------
 John
 Nancy
(2 rows)

What happens when we insert Little Bobby Tables's name into the table?

--                            Input:   Robert'); DROP TABLE students; --
school=> INSERT INTO students VALUES ('Robert'); DROP TABLE students; --');
INSERT 0 1
DROP TABLE

The SQL injection here is the result of the name of the student terminating the statement and including a separate DROP TABLE command; the two dashes at the end of the input are intended to comment out any leftover code that would otherwise cause an error. The last line of the output confirms that the database server has dropped the table.

It's important to notice that during the INSERT operation the application isn't checking the input for any special characters, and is therefore allowing arbitrary input to be entered into the SQL command. This means that a malicious user can insert, into a field normally intended for user input, special symbols such as quotes along with arbitrary SQL code to cause the database system to execute it, hence SQL injection.

The result?

school=> SELECT * FROM students;
ERROR:  relation "students" does not exist
LINE 1: SELECT * FROM students;
                      ^

SQL injection is the database equivalent of a remote arbitrary code execution vulnerability in an operating system or application. The potential impact of a successful SQL injection attack cannot be underestimated--depending on the database system and application configuration, it can be used by an attacker to cause data loss (as in this case), gain unauthorized access to data, or even execute arbitrary code on the host machine itself.

As noted by the XKCD comic, one way of protecting against SQL injection attacks is to sanitize database inputs, such as by escaping special characters, so that they cannot modify the underlying SQL command and therefore cannot cause execution of arbitrary SQL code. If you use parameterized queries, such as by using SqlParameter in ADO.NET, the input will, at minimum, be automatically sanitized to guard against SQL injection.

However, sanitizing inputs at the application level may not stop more advanced SQL injection techniques. For example, there are ways to circumvent the mysql_real_escape_string PHP function. For added protection, many database systems support prepared statements. If properly implemented in the backend, prepared statements can make SQL injection impossible by treating data inputs as semantically separate from the rest of the command.

Function of Project > Clean in Eclipse

I also faced the same issue with Eclipse when I ran the clean build with Maven, but there is a simple solution for this issue. We just need to run Maven update and then build or direct run the application. I hope it will solve the problem.

"Bitmap too large to be uploaded into a texture"

View level

You can disable hardware acceleration for an individual view at runtime with the following code:

myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

com.sun.jdi.InvocationException occurred invoking method

Well, it might be because of several things as mentioned by others before and after. In my case the problem was same but reason was something else.

In a class (A), I had several objects and one of object was another class (B) with some other objects. During the process, one of the object (String) from class B was null, and then I tried to access that object via parent class (A).

Thus, console will throw null point exception but eclipse debugger will show above mentioned error.

I hope you can do the remaining.

How can I get all sequences in an Oracle database?

select sequence_owner, sequence_name from dba_sequences;


DBA_SEQUENCES -- all sequences that exist 
ALL_SEQUENCES  -- all sequences that you have permission to see 
USER_SEQUENCES  -- all sequences that you own

Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES, there is no SEQUENCE_OWNER column in USER_SEQUENCES.

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Playing HTML5 video on fullscreen in android webview

Cprcrack's answer works very well for API levels 19 and under. Just a minor addition to cprcrack's onShowCustomView will get it working on API level 21+

if (Build.VERSION.SDK_INT >= 21) {
      videoViewContainer.setBackgroundColor(Color.BLACK);
      ((ViewGroup) webView.getParent()).addView(videoViewContainer);
      webView.scrollTo(0,0);  // centers full screen view 
} else {
      activityNonVideoView.setVisibility(View.INVISIBLE);
      ViewGroup.LayoutParams vg = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
      activityVideoView.addView(videoViewContainer,vg);
      activityVideoView.setVisibility(View.VISIBLE);
}

You will also need to reflect the changes in onHideCustomView

Java: How to Indent XML Generated by Transformer

Neither of the suggested solutions worked for me. So I kept on searching for an alternative solution, which ended up being a mixture of the two before mentioned and a third step.

  1. set the indent-number into the transformerfactory
  2. enable the indent in the transformer
  3. wrap the otuputstream with a writer (or bufferedwriter)
//(1)
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute("indent-number", new Integer(2));

//(2)
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");

//(3)
t.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(out, "utf-8"));

You must do (3) to workaround a "buggy" behavior of the xml handling code.

Source: johnnymac75 @ http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446

(If I have cited my source incorrectly please let me know)

How to change mysql to mysqli?

2020+ Answer

I've created a tool called Rector, that handles instant upgrades. There is also mysql ? mysqli set.

It handles:

  • function renaming

  • constant renaming

  • switched arguments

  • non-1:1 function calls changes, e.g.

      $data = mysql_db_name($result, $row);
    

    ?

      mysqli_data_seek($result, $row);
      $fetch = mysql_fetch_row($result);
      $data = $fetch[0];
    

How to use Rector?

1. Install it via Composer

composer require rector/rector --dev

// or in case of composer conflicts
composer require rector/rector-prefixed --dev

2. Create rector.php in project root directory with the Mysql to Mysqli set

<?php

use Rector\Core\Configuration\Option;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {

    $parameters->set(Option::SETS, [
        SetList::MYSQL_TO_MYSQLI,
    ]);
};

3. Let Rector run on e.g. /src directory to only show the diffs

vendor/bin/rector process src --dry-run

4. Let Rector change the code

vendor/bin/rector process src

I've already run it on 2 big PHP projects and it works perfectly.

NHibernate.MappingException: No persister for: XYZ

I my case I fetched an entity without await:

var company = _unitOfWork.Session.GetAsync<Company>(id);

and then I tried to delete it:

await _unitOfWork.Session.DeleteAsync(company);

I could not decipher the error message that I'm deleting a Task<Company> instead of Company:

MappingException: No persister for: System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null],[NHibernate.Impl.SessionImpl+d__54`1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]], NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4]]

What is difference between cacerts and keystore?

Cacerts are details of trusted signing authorities who can issue certs. This what most of the browsers have due to which certs determined to be authentic. Keystone has your service related certs to authenticate clients.

Select count(*) from multiple tables

For a bit of completeness - this query will create a query to give you a count of all of the tables for a given owner.

select 
  DECODE(rownum, 1, '', ' UNION ALL ') || 
  'SELECT ''' || table_name || ''' AS TABLE_NAME, COUNT(*) ' ||
  ' FROM ' || table_name  as query_string 
 from all_tables 
where owner = :owner;

The output is something like

SELECT 'TAB1' AS TABLE_NAME, COUNT(*) FROM TAB1
 UNION ALL SELECT 'TAB2' AS TABLE_NAME, COUNT(*) FROM TAB2
 UNION ALL SELECT 'TAB3' AS TABLE_NAME, COUNT(*) FROM TAB3
 UNION ALL SELECT 'TAB4' AS TABLE_NAME, COUNT(*) FROM TAB4

Which you can then run to get your counts. It's just a handy script to have around sometimes.

How to add more than one machine to the trusted hosts list using winrm

I created a module to make dealing with trusted hosts slightly easier, psTrustedHosts. You can find the repo here on GitHub. It provides four functions that make working with trusted hosts easy: Add-TrustedHost, Clear-TrustedHost, Get-TrustedHost, and Remove-TrustedHost. You can install the module from PowerShell Gallery with the following command:

Install-Module psTrustedHosts -Force

In your example, if you wanted to append hosts 'machineC' and 'machineD' you would simply use the following command:

Add-TrustedHost 'machineC','machineD'

To be clear, this adds hosts 'machineC' and 'machineD' to any hosts that already exist, it does not overwrite existing hosts.

The Add-TrustedHost command supports pipeline processing as well (so does the Remove-TrustedHost command) so you could also do the following:

'machineC','machineD' | Add-TrustedHost

parse html string with jquery

I'm not a 100% sure, but won't

$(data)

produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src")

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src")

How to install mod_ssl for Apache httpd?

I used:

sudo yum install mod24_ssl

and it worked in my Amazon Linux AMI.

Convert character to ASCII numeric value in java

You can check the ASCII´s number with this code.

String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97

If I am wrong, apologies.

How do I create HTML table using jQuery dynamically?

I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html to achieve what you want .

Look at the code below :

HTML:

<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>

JS :

createFormElement("Nickname","nickname")

function createFormElement(labelText, id) {

$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}

This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .

WORKING DEMO:

Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.

It's much easier to construct just the html and change the id s of the label and input according to your needs.

Adding System.Web.Script reference in class library

You need to add a reference to System.Web.Extensions.dll in project for System.Web.Script.Serialization error.

HTTP redirect: 301 (permanent) vs. 302 (temporary)

When a search engine spider finds 301 status code in the response header of a webpage, it understands that this webpage no longer exists, it searches for location header in response pick the new URL and replace the indexed URL with the new one and also transfer pagerank.

So search engine refreshes all indexed URL that no longer exist (301 found) with the new URL, this will retain your old webpage traffic, pagerank and divert it to the new one (you will not lose you traffic of old webpage).

Browser: if a browser finds 301 status code then it caches the mapping of the old URL with the new URL, the client/browser will not attempt to request the original location but use the new location from now on unless the cache is cleared.

enter image description here

When a search engine spider finds 302 status for a webpage, it will only redirect temporarily to the new location and crawl both of the pages. The old webpage URL still exists in the search engine database and it always attempts to request the old location and crawl it. The client/browser will still attempt to request the original location.

enter image description here

Read more about how to implement it in asp.net c# and what is the impact on search engines - http://www.dotnetbull.com/2013/08/301-permanent-vs-302-temporary-status-code-aspnet-csharp-Implementation.html

what is the use of Eval() in asp.net

Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.

It is generally used for late-bound data (not known from start) and usually bound to the smallest part of the data-bound control that contains a whole record. The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.

How to "Open" and "Save" using java

Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.

How to rename a directory/folder on GitHub website?

As a newer user to git, I took the following approach. From the command line, I was able to rename a folder by creating a new folder, copying the files to it, adding and commiting locally and pushing. These are my steps:

$mkdir newfolder 
$cp oldfolder/* newfolder
$git add newfolder 
$git commit -m 'start rename'     
$git push                             #New Folder appears on Github      
$git rm -r oldfolder
$git commit -m 'rename complete' 
$git push                             #Old Folder disappears on Github  

Probably a better way, but it worked for me.

$(document).ready(function() is not working

Set events after loading DOM Elements.

$(function () {
        $(document).on("click","selector",function (e) {
          alert("hi");

        });

    });

How to change the Title of the window in Qt?

void    QWidget::setWindowTitle ( const QString & )

EDIT: If you are using QtDesigner, on the property tab, there is an editable property called windowTitle which can be found under the QWidget section. The property tab can usually be found on the lower right part of the designer window.

Get Category name from Post ID

Use get_the_category() function.

$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);

What is a classpath and how do I set it?

Static member of a class can be called directly without creating object instance. Since the main method is static Java virtual Machine can call it without creating any instance of a class which contains the main method, which is start point of program.

How do I replace text in a selection?

Some of the answers here haven't really helped.

People are showing you how to find stuff, but now how to replace it.

I just had a look, and it looks like it's Ctrl+H for replace, then you get the find dialog as well as a replace dialog. This worked for me.

Colors in JavaScript console

Here is an extreme example with rainbow drop shadow.

_x000D_
_x000D_
var css = "text-shadow: -1px -1px hsl(0,100%,50%), 1px 1px hsl(5.4, 100%, 50%), 3px 2px hsl(10.8, 100%, 50%), 5px 3px hsl(16.2, 100%, 50%), 7px 4px hsl(21.6, 100%, 50%), 9px 5px hsl(27, 100%, 50%), 11px 6px hsl(32.4, 100%, 50%), 13px 7px hsl(37.8, 100%, 50%), 14px 8px hsl(43.2, 100%, 50%), 16px 9px hsl(48.6, 100%, 50%), 18px 10px hsl(54, 100%, 50%), 20px 11px hsl(59.4, 100%, 50%), 22px 12px hsl(64.8, 100%, 50%), 23px 13px hsl(70.2, 100%, 50%), 25px 14px hsl(75.6, 100%, 50%), 27px 15px hsl(81, 100%, 50%), 28px 16px hsl(86.4, 100%, 50%), 30px 17px hsl(91.8, 100%, 50%), 32px 18px hsl(97.2, 100%, 50%), 33px 19px hsl(102.6, 100%, 50%), 35px 20px hsl(108, 100%, 50%), 36px 21px hsl(113.4, 100%, 50%), 38px 22px hsl(118.8, 100%, 50%), 39px 23px hsl(124.2, 100%, 50%), 41px 24px hsl(129.6, 100%, 50%), 42px 25px hsl(135, 100%, 50%), 43px 26px hsl(140.4, 100%, 50%), 45px 27px hsl(145.8, 100%, 50%), 46px 28px hsl(151.2, 100%, 50%), 47px 29px hsl(156.6, 100%, 50%), 48px 30px hsl(162, 100%, 50%), 49px 31px hsl(167.4, 100%, 50%), 50px 32px hsl(172.8, 100%, 50%), 51px 33px hsl(178.2, 100%, 50%), 52px 34px hsl(183.6, 100%, 50%), 53px 35px hsl(189, 100%, 50%), 54px 36px hsl(194.4, 100%, 50%), 55px 37px hsl(199.8, 100%, 50%), 55px 38px hsl(205.2, 100%, 50%), 56px 39px hsl(210.6, 100%, 50%), 57px 40px hsl(216, 100%, 50%), 57px 41px hsl(221.4, 100%, 50%), 58px 42px hsl(226.8, 100%, 50%), 58px 43px hsl(232.2, 100%, 50%), 58px 44px hsl(237.6, 100%, 50%), 59px 45px hsl(243, 100%, 50%), 59px 46px hsl(248.4, 100%, 50%), 59px 47px hsl(253.8, 100%, 50%), 59px 48px hsl(259.2, 100%, 50%), 59px 49px hsl(264.6, 100%, 50%), 60px 50px hsl(270, 100%, 50%), 59px 51px hsl(275.4, 100%, 50%), 59px 52px hsl(280.8, 100%, 50%), 59px 53px hsl(286.2, 100%, 50%), 59px 54px hsl(291.6, 100%, 50%), 59px 55px hsl(297, 100%, 50%), 58px 56px hsl(302.4, 100%, 50%), 58px 57px hsl(307.8, 100%, 50%), 58px 58px hsl(313.2, 100%, 50%), 57px 59px hsl(318.6, 100%, 50%), 57px 60px hsl(324, 100%, 50%), 56px 61px hsl(329.4, 100%, 50%), 55px 62px hsl(334.8, 100%, 50%), 55px 63px hsl(340.2, 100%, 50%), 54px 64px hsl(345.6, 100%, 50%), 53px 65px hsl(351, 100%, 50%), 52px 66px hsl(356.4, 100%, 50%), 51px 67px hsl(361.8, 100%, 50%), 50px 68px hsl(367.2, 100%, 50%), 49px 69px hsl(372.6, 100%, 50%), 48px 70px hsl(378, 100%, 50%), 47px 71px hsl(383.4, 100%, 50%), 46px 72px hsl(388.8, 100%, 50%), 45px 73px hsl(394.2, 100%, 50%), 43px 74px hsl(399.6, 100%, 50%), 42px 75px hsl(405, 100%, 50%), 41px 76px hsl(410.4, 100%, 50%), 39px 77px hsl(415.8, 100%, 50%), 38px 78px hsl(421.2, 100%, 50%), 36px 79px hsl(426.6, 100%, 50%), 35px 80px hsl(432, 100%, 50%), 33px 81px hsl(437.4, 100%, 50%), 32px 82px hsl(442.8, 100%, 50%), 30px 83px hsl(448.2, 100%, 50%), 28px 84px hsl(453.6, 100%, 50%), 27px 85px hsl(459, 100%, 50%), 25px 86px hsl(464.4, 100%, 50%), 23px 87px hsl(469.8, 100%, 50%), 22px 88px hsl(475.2, 100%, 50%), 20px 89px hsl(480.6, 100%, 50%), 18px 90px hsl(486, 100%, 50%), 16px 91px hsl(491.4, 100%, 50%), 14px 92px hsl(496.8, 100%, 50%), 13px 93px hsl(502.2, 100%, 50%), 11px 94px hsl(507.6, 100%, 50%), 9px 95px hsl(513, 100%, 50%), 7px 96px hsl(518.4, 100%, 50%), 5px 97px hsl(523.8, 100%, 50%), 3px 98px hsl(529.2, 100%, 50%), 1px 99px hsl(534.6, 100%, 50%), 7px 100px hsl(540, 100%, 50%), -1px 101px hsl(545.4, 100%, 50%), -3px 102px hsl(550.8, 100%, 50%), -5px 103px hsl(556.2, 100%, 50%), -7px 104px hsl(561.6, 100%, 50%), -9px 105px hsl(567, 100%, 50%), -11px 106px hsl(572.4, 100%, 50%), -13px 107px hsl(577.8, 100%, 50%), -14px 108px hsl(583.2, 100%, 50%), -16px 109px hsl(588.6, 100%, 50%), -18px 110px hsl(594, 100%, 50%), -20px 111px hsl(599.4, 100%, 50%), -22px 112px hsl(604.8, 100%, 50%), -23px 113px hsl(610.2, 100%, 50%), -25px 114px hsl(615.6, 100%, 50%), -27px 115px hsl(621, 100%, 50%), -28px 116px hsl(626.4, 100%, 50%), -30px 117px hsl(631.8, 100%, 50%), -32px 118px hsl(637.2, 100%, 50%), -33px 119px hsl(642.6, 100%, 50%), -35px 120px hsl(648, 100%, 50%), -36px 121px hsl(653.4, 100%, 50%), -38px 122px hsl(658.8, 100%, 50%), -39px 123px hsl(664.2, 100%, 50%), -41px 124px hsl(669.6, 100%, 50%), -42px 125px hsl(675, 100%, 50%), -43px 126px hsl(680.4, 100%, 50%), -45px 127px hsl(685.8, 100%, 50%), -46px 128px hsl(691.2, 100%, 50%), -47px 129px hsl(696.6, 100%, 50%), -48px 130px hsl(702, 100%, 50%), -49px 131px hsl(707.4, 100%, 50%), -50px 132px hsl(712.8, 100%, 50%), -51px 133px hsl(718.2, 100%, 50%), -52px 134px hsl(723.6, 100%, 50%), -53px 135px hsl(729, 100%, 50%), -54px 136px hsl(734.4, 100%, 50%), -55px 137px hsl(739.8, 100%, 50%), -55px 138px hsl(745.2, 100%, 50%), -56px 139px hsl(750.6, 100%, 50%), -57px 140px hsl(756, 100%, 50%), -57px 141px hsl(761.4, 100%, 50%), -58px 142px hsl(766.8, 100%, 50%), -58px 143px hsl(772.2, 100%, 50%), -58px 144px hsl(777.6, 100%, 50%), -59px 145px hsl(783, 100%, 50%), -59px 146px hsl(788.4, 100%, 50%), -59px 147px hsl(793.8, 100%, 50%), -59px 148px hsl(799.2, 100%, 50%), -59px 149px hsl(804.6, 100%, 50%), -60px 150px hsl(810, 100%, 50%), -59px 151px hsl(815.4, 100%, 50%), -59px 152px hsl(820.8, 100%, 50%), -59px 153px hsl(826.2, 100%, 50%), -59px 154px hsl(831.6, 100%, 50%), -59px 155px hsl(837, 100%, 50%), -58px 156px hsl(842.4, 100%, 50%), -58px 157px hsl(847.8, 100%, 50%), -58px 158px hsl(853.2, 100%, 50%), -57px 159px hsl(858.6, 100%, 50%), -57px 160px hsl(864, 100%, 50%), -56px 161px hsl(869.4, 100%, 50%), -55px 162px hsl(874.8, 100%, 50%), -55px 163px hsl(880.2, 100%, 50%), -54px 164px hsl(885.6, 100%, 50%), -53px 165px hsl(891, 100%, 50%), -52px 166px hsl(896.4, 100%, 50%), -51px 167px hsl(901.8, 100%, 50%), -50px 168px hsl(907.2, 100%, 50%), -49px 169px hsl(912.6, 100%, 50%), -48px 170px hsl(918, 100%, 50%), -47px 171px hsl(923.4, 100%, 50%), -46px 172px hsl(928.8, 100%, 50%), -45px 173px hsl(934.2, 100%, 50%), -43px 174px hsl(939.6, 100%, 50%), -42px 175px hsl(945, 100%, 50%), -41px 176px hsl(950.4, 100%, 50%), -39px 177px hsl(955.8, 100%, 50%), -38px 178px hsl(961.2, 100%, 50%), -36px 179px hsl(966.6, 100%, 50%), -35px 180px hsl(972, 100%, 50%), -33px 181px hsl(977.4, 100%, 50%), -32px 182px hsl(982.8, 100%, 50%), -30px 183px hsl(988.2, 100%, 50%), -28px 184px hsl(993.6, 100%, 50%), -27px 185px hsl(999, 100%, 50%), -25px 186px hsl(1004.4, 100%, 50%), -23px 187px hsl(1009.8, 100%, 50%), -22px 188px hsl(1015.2, 100%, 50%), -20px 189px hsl(1020.6, 100%, 50%), -18px 190px hsl(1026, 100%, 50%), -16px 191px hsl(1031.4, 100%, 50%), -14px 192px hsl(1036.8, 100%, 50%), -13px 193px hsl(1042.2, 100%, 50%), -11px 194px hsl(1047.6, 100%, 50%), -9px 195px hsl(1053, 100%, 50%), -7px 196px hsl(1058.4, 100%, 50%), -5px 197px hsl(1063.8, 100%, 50%), -3px 198px hsl(1069.2, 100%, 50%), -1px 199px hsl(1074.6, 100%, 50%), -1px 200px hsl(1080, 100%, 50%), 1px 201px hsl(1085.4, 100%, 50%), 3px 202px hsl(1090.8, 100%, 50%), 5px 203px hsl(1096.2, 100%, 50%), 7px 204px hsl(1101.6, 100%, 50%), 9px 205px hsl(1107, 100%, 50%), 11px 206px hsl(1112.4, 100%, 50%), 13px 207px hsl(1117.8, 100%, 50%), 14px 208px hsl(1123.2, 100%, 50%), 16px 209px hsl(1128.6, 100%, 50%), 18px 210px hsl(1134, 100%, 50%), 20px 211px hsl(1139.4, 100%, 50%), 22px 212px hsl(1144.8, 100%, 50%), 23px 213px hsl(1150.2, 100%, 50%), 25px 214px hsl(1155.6, 100%, 50%), 27px 215px hsl(1161, 100%, 50%), 28px 216px hsl(1166.4, 100%, 50%), 30px 217px hsl(1171.8, 100%, 50%), 32px 218px hsl(1177.2, 100%, 50%), 33px 219px hsl(1182.6, 100%, 50%), 35px 220px hsl(1188, 100%, 50%), 36px 221px hsl(1193.4, 100%, 50%), 38px 222px hsl(1198.8, 100%, 50%), 39px 223px hsl(1204.2, 100%, 50%), 41px 224px hsl(1209.6, 100%, 50%), 42px 225px hsl(1215, 100%, 50%), 43px 226px hsl(1220.4, 100%, 50%), 45px 227px hsl(1225.8, 100%, 50%), 46px 228px hsl(1231.2, 100%, 50%), 47px 229px hsl(1236.6, 100%, 50%), 48px 230px hsl(1242, 100%, 50%), 49px 231px hsl(1247.4, 100%, 50%), 50px 232px hsl(1252.8, 100%, 50%), 51px 233px hsl(1258.2, 100%, 50%), 52px 234px hsl(1263.6, 100%, 50%), 53px 235px hsl(1269, 100%, 50%), 54px 236px hsl(1274.4, 100%, 50%), 55px 237px hsl(1279.8, 100%, 50%), 55px 238px hsl(1285.2, 100%, 50%), 56px 239px hsl(1290.6, 100%, 50%), 57px 240px hsl(1296, 100%, 50%), 57px 241px hsl(1301.4, 100%, 50%), 58px 242px hsl(1306.8, 100%, 50%), 58px 243px hsl(1312.2, 100%, 50%), 58px 244px hsl(1317.6, 100%, 50%), 59px 245px hsl(1323, 100%, 50%), 59px 246px hsl(1328.4, 100%, 50%), 59px 247px hsl(1333.8, 100%, 50%), 59px 248px hsl(1339.2, 100%, 50%), 59px 249px hsl(1344.6, 100%, 50%), 60px 250px hsl(1350, 100%, 50%), 59px 251px hsl(1355.4, 100%, 50%), 59px 252px hsl(1360.8, 100%, 50%), 59px 253px hsl(1366.2, 100%, 50%), 59px 254px hsl(1371.6, 100%, 50%), 59px 255px hsl(1377, 100%, 50%), 58px 256px hsl(1382.4, 100%, 50%), 58px 257px hsl(1387.8, 100%, 50%), 58px 258px hsl(1393.2, 100%, 50%), 57px 259px hsl(1398.6, 100%, 50%), 57px 260px hsl(1404, 100%, 50%), 56px 261px hsl(1409.4, 100%, 50%), 55px 262px hsl(1414.8, 100%, 50%), 55px 263px hsl(1420.2, 100%, 50%), 54px 264px hsl(1425.6, 100%, 50%), 53px 265px hsl(1431, 100%, 50%), 52px 266px hsl(1436.4, 100%, 50%), 51px 267px hsl(1441.8, 100%, 50%), 50px 268px hsl(1447.2, 100%, 50%), 49px 269px hsl(1452.6, 100%, 50%), 48px 270px hsl(1458, 100%, 50%), 47px 271px hsl(1463.4, 100%, 50%), 46px 272px hsl(1468.8, 100%, 50%), 45px 273px hsl(1474.2, 100%, 50%), 43px 274px hsl(1479.6, 100%, 50%), 42px 275px hsl(1485, 100%, 50%), 41px 276px hsl(1490.4, 100%, 50%), 39px 277px hsl(1495.8, 100%, 50%), 38px 278px hsl(1501.2, 100%, 50%), 36px 279px hsl(1506.6, 100%, 50%), 35px 280px hsl(1512, 100%, 50%), 33px 281px hsl(1517.4, 100%, 50%), 32px 282px hsl(1522.8, 100%, 50%), 30px 283px hsl(1528.2, 100%, 50%), 28px 284px hsl(1533.6, 100%, 50%), 27px 285px hsl(1539, 100%, 50%), 25px 286px hsl(1544.4, 100%, 50%), 23px 287px hsl(1549.8, 100%, 50%), 22px 288px hsl(1555.2, 100%, 50%), 20px 289px hsl(1560.6, 100%, 50%), 18px 290px hsl(1566, 100%, 50%), 16px 291px hsl(1571.4, 100%, 50%), 14px 292px hsl(1576.8, 100%, 50%), 13px 293px hsl(1582.2, 100%, 50%), 11px 294px hsl(1587.6, 100%, 50%), 9px 295px hsl(1593, 100%, 50%), 7px 296px hsl(1598.4, 100%, 50%), 5px 297px hsl(1603.8, 100%, 50%), 3px 298px hsl(1609.2, 100%, 50%), 1px 299px hsl(1614.6, 100%, 50%), 2px 300px hsl(1620, 100%, 50%), -1px 301px hsl(1625.4, 100%, 50%), -3px 302px hsl(1630.8, 100%, 50%), -5px 303px hsl(1636.2, 100%, 50%), -7px 304px hsl(1641.6, 100%, 50%), -9px 305px hsl(1647, 100%, 50%), -11px 306px hsl(1652.4, 100%, 50%), -13px 307px hsl(1657.8, 100%, 50%), -14px 308px hsl(1663.2, 100%, 50%), -16px 309px hsl(1668.6, 100%, 50%), -18px 310px hsl(1674, 100%, 50%), -20px 311px hsl(1679.4, 100%, 50%), -22px 312px hsl(1684.8, 100%, 50%), -23px 313px hsl(1690.2, 100%, 50%), -25px 314px hsl(1695.6, 100%, 50%), -27px 315px hsl(1701, 100%, 50%), -28px 316px hsl(1706.4, 100%, 50%), -30px 317px hsl(1711.8, 100%, 50%), -32px 318px hsl(1717.2, 100%, 50%), -33px 319px hsl(1722.6, 100%, 50%), -35px 320px hsl(1728, 100%, 50%), -36px 321px hsl(1733.4, 100%, 50%), -38px 322px hsl(1738.8, 100%, 50%), -39px 323px hsl(1744.2, 100%, 50%), -41px 324px hsl(1749.6, 100%, 50%), -42px 325px hsl(1755, 100%, 50%), -43px 326px hsl(1760.4, 100%, 50%), -45px 327px hsl(1765.8, 100%, 50%), -46px 328px hsl(1771.2, 100%, 50%), -47px 329px hsl(1776.6, 100%, 50%), -48px 330px hsl(1782, 100%, 50%), -49px 331px hsl(1787.4, 100%, 50%), -50px 332px hsl(1792.8, 100%, 50%), -51px 333px hsl(1798.2, 100%, 50%), -52px 334px hsl(1803.6, 100%, 50%), -53px 335px hsl(1809, 100%, 50%), -54px 336px hsl(1814.4, 100%, 50%), -55px 337px hsl(1819.8, 100%, 50%), -55px 338px hsl(1825.2, 100%, 50%), -56px 339px hsl(1830.6, 100%, 50%), -57px 340px hsl(1836, 100%, 50%), -57px 341px hsl(1841.4, 100%, 50%), -58px 342px hsl(1846.8, 100%, 50%), -58px 343px hsl(1852.2, 100%, 50%), -58px 344px hsl(1857.6, 100%, 50%), -59px 345px hsl(1863, 100%, 50%), -59px 346px hsl(1868.4, 100%, 50%), -59px 347px hsl(1873.8, 100%, 50%), -59px 348px hsl(1879.2, 100%, 50%), -59px 349px hsl(1884.6, 100%, 50%), -60px 350px hsl(1890, 100%, 50%), -59px 351px hsl(1895.4, 100%, 50%), -59px 352px hsl(1900.8, 100%, 50%), -59px 353px hsl(1906.2, 100%, 50%), -59px 354px hsl(1911.6, 100%, 50%), -59px 355px hsl(1917, 100%, 50%), -58px 356px hsl(1922.4, 100%, 50%), -58px 357px hsl(1927.8, 100%, 50%), -58px 358px hsl(1933.2, 100%, 50%), -57px 359px hsl(1938.6, 100%, 50%), -57px 360px hsl(1944, 100%, 50%), -56px 361px hsl(1949.4, 100%, 50%), -55px 362px hsl(1954.8, 100%, 50%), -55px 363px hsl(1960.2, 100%, 50%), -54px 364px hsl(1965.6, 100%, 50%), -53px 365px hsl(1971, 100%, 50%), -52px 366px hsl(1976.4, 100%, 50%), -51px 367px hsl(1981.8, 100%, 50%), -50px 368px hsl(1987.2, 100%, 50%), -49px 369px hsl(1992.6, 100%, 50%), -48px 370px hsl(1998, 100%, 50%), -47px 371px hsl(2003.4, 100%, 50%), -46px 372px hsl(2008.8, 100%, 50%), -45px 373px hsl(2014.2, 100%, 50%), -43px 374px hsl(2019.6, 100%, 50%), -42px 375px hsl(2025, 100%, 50%), -41px 376px hsl(2030.4, 100%, 50%), -39px 377px hsl(2035.8, 100%, 50%), -38px 378px hsl(2041.2, 100%, 50%), -36px 379px hsl(2046.6, 100%, 50%), -35px 380px hsl(2052, 100%, 50%), -33px 381px hsl(2057.4, 100%, 50%), -32px 382px hsl(2062.8, 100%, 50%), -30px 383px hsl(2068.2, 100%, 50%), -28px 384px hsl(2073.6, 100%, 50%), -27px 385px hsl(2079, 100%, 50%), -25px 386px hsl(2084.4, 100%, 50%), -23px 387px hsl(2089.8, 100%, 50%), -22px 388px hsl(2095.2, 100%, 50%), -20px 389px hsl(2100.6, 100%, 50%), -18px 390px hsl(2106, 100%, 50%), -16px 391px hsl(2111.4, 100%, 50%), -14px 392px hsl(2116.8, 100%, 50%), -13px 393px hsl(2122.2, 100%, 50%), -11px 394px hsl(2127.6, 100%, 50%), -9px 395px hsl(2133, 100%, 50%), -7px 396px hsl(2138.4, 100%, 50%), -5px 397px hsl(2143.8, 100%, 50%), -3px 398px hsl(2149.2, 100%, 50%), -1px 399px hsl(2154.6, 100%, 50%); font-size: 40px;";_x000D_
_x000D_
console.log("%cExample %s", css, 'all code runs happy');
_x000D_
_x000D_
_x000D_

enter image description here

Java Ordered Map

I think the closest collection you'll get from the framework is the SortedMap

How to get current value of RxJS Subject or Observable?

I encountered the same problem in child components where initially it would have to have the current value of the Subject, then subscribe to the Subject to listen to changes. I just maintain the current value in the Service so it is available for components to access, e.g. :

import {Storage} from './storage';
import {Injectable} from 'angular2/core';
import {Subject}    from 'rxjs/Subject';

@Injectable()
export class SessionStorage extends Storage {

  isLoggedIn: boolean;

  private _isLoggedInSource = new Subject<boolean>();
  isLoggedIn = this._isLoggedInSource.asObservable();
  constructor() {
    super('session');
    this.currIsLoggedIn = false;
  }
  setIsLoggedIn(value: boolean) {
    this.setItem('_isLoggedIn', value, () => {
      this._isLoggedInSource.next(value);
    });
    this.isLoggedIn = value;
  }
}

A component that needs the current value could just then access it from the service, i.e,:

sessionStorage.isLoggedIn

Not sure if this is the right practice :)

Controller 'ngModel', required by directive '...', can't be found

As described here: Angular NgModelController, you should provide the <input with the required controller ngModel

<input submit-required="true" ng-model="user.Name"></input>

JSON and escaping characters

hmm, well here's a workaround anyway:

function JSON_stringify(s, emit_unicode)
{
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) { 
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

test case:

js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"

Get DOM content of cross-domain iframe

If you have access to the iframed page you could use something like easyXDM to make function calls in the iframe and return the data.

If you don't have access to the iframed page you will have to use a server side solution. With PHP you could do something quick and dirty like:

    <?php echo file_get_contents('http://url_of_the_iframe/content.php'); ?> 

How to maintain page scroll position after a jquery event is carried out?

Something to note, when setting the scroll position, make sure you do it in the correct scope. For example, if you're using the scroll position in multiple functions, you would want to set it outside of these functions.

$(document).ready(function() {
    var tempScrollTop = $(window).scrollTop();
    function example() {
        console.log(tempScrollTop);
    };

});

How to add Headers on RESTful call using Jersey Client API

If you want to add a header to all Jersey responses, you could also use a ContainerResponseFilter, from Jersey's filter documentation :

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;

@Provider
public class PoweredByResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {

            responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
    }
}

Make sure that you initialize it correctly in your project using the @Provider annotation or through traditional ways with web.xml.

How to get access token from FB.login method in javascript SDK

_x000D_
_x000D_
window.fbAsyncInit = function () {_x000D_
    FB.init({_x000D_
        appId: 'Your-appId',_x000D_
        cookie: false,  // enable cookies to allow the server to access _x000D_
        // the session_x000D_
        xfbml: true,  // parse social plugins on this page_x000D_
        version: 'v2.0' // use version 2.0_x000D_
    });_x000D_
};_x000D_
_x000D_
// Load the SDK asynchronously_x000D_
(function (d, s, id) {_x000D_
    var js, fjs = d.getElementsByTagName(s)[0];_x000D_
    if (d.getElementById(id)) return;_x000D_
    js = d.createElement(s); js.id = id;_x000D_
    js.src = "//connect.facebook.net/en_US/sdk.js";_x000D_
    fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));_x000D_
_x000D_
   _x000D_
function fb_login() {_x000D_
    FB.login(function (response) {_x000D_
_x000D_
        if (response.authResponse) {_x000D_
            console.log('Welcome!  Fetching your information.... ');_x000D_
            //console.log(response); // dump complete info_x000D_
            access_token = response.authResponse.accessToken; //get access token_x000D_
            user_id = response.authResponse.userID; //get FB UID_x000D_
_x000D_
            FB.api('/me', function (response) {_x000D_
                var email = response.email;_x000D_
                var name = response.name;_x000D_
                window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;_x000D_
                // used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);          _x000D_
            });_x000D_
_x000D_
        } else {_x000D_
            //user hit cancel button_x000D_
            console.log('User cancelled login or did not fully authorize.');_x000D_
_x000D_
        }_x000D_
    }, {_x000D_
        scope: 'email'_x000D_
    });_x000D_
}
_x000D_
<!-- custom image -->_x000D_
<a href="#" onclick="fb_login();"><img src="/Public/assets/images/facebook/facebook_connect_button.png" /></a>_x000D_
_x000D_
<!-- Facebook button -->_x000D_
<fb:login-button scope="public_profile,email" onlogin="fb_login();">_x000D_
                </fb:login-button>
_x000D_
_x000D_
_x000D_

How to fit in an image inside span tag?

Try using a div tag and block for span!

<div>
  <span style="padding-right:3px; padding-top: 3px; display:block;">
    <img class="manImg" src="images/ico_mandatory.gif"></img>
  </span>
</div>

How to differentiate single click event and double click event?

This answer is made obsolete through time, check @kyw's solution.

I created a solution inspired by the gist posted by @AdrienSchuler. Use this solution only when you want to bind a single click AND a double click to an element. Otherwise I recommend using the native click and dblclick listeners.

These are the differences:

  • Vanillajs, No dependencies
  • Don't wait on the setTimeout to handle the click or doubleclick handler
  • When double clicking it first fires the click handler, then the doubleclick handler

Javascript:

function makeDoubleClick(doubleClickCallback, singleClickCallback) {
    var clicks = 0, timeout;
    return function() {
        clicks++;
        if (clicks == 1) {
            singleClickCallback && singleClickCallback.apply(this, arguments);
            timeout = setTimeout(function() { clicks = 0; }, 400);
        } else {
            timeout && clearTimeout(timeout);
            doubleClickCallback && doubleClickCallback.apply(this, arguments);
            clicks = 0;
        }
    };
}

Usage:

var singleClick = function(){ console.log('single click') };
var doubleClick = function(){ console.log('double click') };
element.addEventListener('click', makeDoubleClick(doubleClick, singleClick));

Below is the usage in a jsfiddle, the jQuery button is the behavior of the accepted answer.

jsfiddle

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

Did you forget to add the init.py in your package?

Can I get div's background-image url?

As mentioned already, Blazemongers solution is failing to remove quotes (e.g. returned by Firefox). Since I find Rob Ws solution to be rather complicated, adding my 2 cents here:

$('#div1').click (function(){
  url = $(this).css('background-image').replace(/^url\(['"]?/,'').replace(/['"]?\)$/,'');
  alert(url);
})

How to fix "ImportError: No module named ..." error in Python?

Example solution for adding the library to your PYTHONPATH.

  1. Add the following line into your ~/.bashrc or just run it directly:

    export PYTHONPATH="$PYTHONPATH:$HOME/.python"
    
  2. Then link your required library into your ~/.python folder, e.g.

    ln -s /home/user/work/project/foo ~/.python/
    

How do I fix a Git detached head?

When you're in a detached head situation and created new files, first make sure that these new files are added to the index, for example with:

git add .

But if you've only changed or deleted existing files, you can add (-a) and commit with a message (-m) at the the same time via:

git commit -a -m "my adjustment message"

Then you can simply create a new branch with your current state with:

git checkout -b new_branch_name

You'll have a new branch and all your adjustments will be there in that new branch. You can then continue to push to the remote and/or checkout/pull/merge as you please.

How to set env variable in Jupyter notebook

If you need the variable set before you're starting the notebook, the only solution which worked for me was env VARIABLE=$VARIABLE jupyter notebook with export VARIABLE=value in .bashrc.

In my case tensorflow needs the exported variable for successful importing it in a notebook.

scp copy directory to another server with private key auth

Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and

scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www

it should work !

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

bash "if [ false ];" returns true instead of false -- why?

as noted by @tripleee, this is tangential, at best.

still, in case you arrived here searching for something like that (as i did), here is my solution

having to deal with user acessible configuration files, i use this function :

function isTrue() {
    if [[ "${@^^}" =~ ^(TRUE|OUI|Y|O$|ON$|[1-9]) ]]; then return 0;fi
    return 1
    }

wich can be used like that

if isTrue "$whatever"; then..

You can alter the "truth list" in the regexp, the one in this sample is french compatible and considers strings like "Yeah, yup, on,1, Oui,y,true to be "True".

note that the '^^' provides case insensivity

How can I show current location on a Google Map on Android Marshmallow?

Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.

import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {


    //These variable are initalized here as they need to be used in more than one methid
    private double currentLatitude; //lat of user
    private double currentLongitude; //long of user

    private double latitudeVillageApartmets= 53.385952001750184;
    private double longitudeVillageApartments= -6.599087119102478;


    public static final String TAG = MapsActivity.class.getSimpleName();

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds
 }
    /*These methods all have to do with the map and wht happens if the activity is paused etc*/
    //contains lat and lon of another marker
    private void setUpMap() {

            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
            mMap.addMarker(marker); // adding marker
    }

    //contains your lat and lon
    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("You are here");
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }

        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }

}

There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.

How to print pthread_t

You could try converting it to an unsigned short and then print just the last four hex digits. The resulting value might be unique enough for your needs.

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

Undefined symbols for architecture i386

Add the framework required for the method used in the project target in the "Link Binaries With Libraries" list of Build Phases, it will work easily. Like I have imported to my project

QuartzCore.framework

For the bug

Undefined symbols for architecture i386:

Use async await with Array.map

If you map to an array of Promises, you can then resolve them all to an array of numbers. See Promise.all.

Check if a number has a decimal place/is a whole number

Number.isInteger(23);  // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false: 

Number.isInteger() is part of the ES6 standard and not supported in IE11.

It returns false for NaN, Infinity and non-numeric arguments while x % 1 != 0 returns true.

"Integer number too large" error message for 600851475143

Apart from all the other answers, what you can do is :

long l = Long.parseLong("600851475143");

for example :

obj.function(Long.parseLong("600851475143"));

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

How to add a changed file to an older (not last) commit in Git

Use git rebase. Specifically:

  1. Use git stash to store the changes you want to add.
  2. Use git rebase -i HEAD~10 (or however many commits back you want to see).
  3. Mark the commit in question (a0865...) for edit by changing the word pick at the start of the line into edit. Don't delete the other lines as that would delete the commits.[^vimnote]
  4. Save the rebase file, and git will drop back to the shell and wait for you to fix that commit.
  5. Pop the stash by using git stash pop
  6. Add your file with git add <file>.
  7. Amend the commit with git commit --amend --no-edit.
  8. Do a git rebase --continue which will rewrite the rest of your commits against the new one.
  9. Repeat from step 2 onwards if you have marked more than one commit for edit.

[^vimnote]: If you are using vim then you will have to hit the Insert key to edit, then Esc and type in :wq to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano".

Using Python's os.path, how do I go up one directory?

With using os.path we can go one directory up like that

one_directory_up_path = os.path.dirname('.')

also after finding the directory you want you can join with other file/directory path

other_image_path = os.path.join(one_directory_up_path, 'other.jpg')

TypeScript typed array usage

The translation is correct, the typing of the expression isn't. TypeScript is incorrectly typing the expression new Thing[100] as an array. It should be an error to index Thing, a constructor function, using the index operator. In C# this would allocate an array of 100 elements. In JavaScript this calls the value at index 100 of Thing as if was a constructor. Since that values is undefined it raises the error you mentioned. In JavaScript and TypeScript you want new Array(100) instead.

You should report this as a bug on CodePlex.

How store a range from excel into a Range variable?

Define what GetData is. At the moment it is not defined.

Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

Prepend text to beginning of string

If you want to use the version of Javascript called ES 2015 (aka ES6) or later, you can use template strings introduced by ES 2015 and recommended by some guidelines (like Airbnb's style guide):

const after = "test";
const mystr = `This is: ${after}`;

Django - makemigrations - No changes detected

I had a similar issue with django 3.0, according migrations section in the official documentation, running this was enough to update my table structure:

python manage.py makemigrations
python manage.py migrate

But the output was always the same: 'no change detected' about my models after I executed 'makemigrations' script. I had a syntax error on models.py at the model I wanted to update on db:

field_model : models.CharField(max_length=255, ...)

instead of:

field_model = models.CharField(max_length=255, ...)

Solving this stupid mistake, with those command the migration was done without problems. Maybe this helps someone.

Making a WinForms TextBox behave like your browser's address bar

Here's a helper function taking the solution to the next level - reuse without inheritance.

    public static void WireSelectAllOnFocus( TextBox aTextBox )
    {
        bool lActive = false;
        aTextBox.GotFocus += new EventHandler( ( sender, e ) =>
        {
            if ( System.Windows.Forms.Control.MouseButtons == MouseButtons.None )
            {
                aTextBox.SelectAll();
                lActive = true;
            }
        } );

        aTextBox.Leave += new EventHandler( (sender, e ) => {
            lActive = false;
        } );

        aTextBox.MouseUp += new MouseEventHandler( (sender, e ) => {
            if ( !lActive )
            {
                lActive = true;
                if ( aTextBox.SelectionLength == 0 ) aTextBox.SelectAll();
            }   
        });
    }

To use this simply call the function passing a TextBox and it takes care of all the messy bits for you. I suggest wiring up all your text boxes in the Form_Load event. You can place this function in your form, or if your like me, somewhere in a utility class for even more reuse.

Lombok added but getters and setters not recognized in Intellij IDEA

In MacBook press command+, and then go to plug-in and search for Lombok and then install it.

It will work without restarting IntelliJ IDEA IDE if doesn't work then please try with restart.

Many thanks

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

I had met a similar problem, after i add a scope property of servlet dependency in pom.xml

 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Then it was ok . maybe that will help you.

Is it possible to specify a different ssh port when using rsync?

Another option, in the host you run rsync from, set the port in the ssh config file, ie:

cat ~/.ssh/config
Host host
    Port 2222

Then rsync over ssh will talk to port 2222:

rsync -rvz --progress --remove-sent-files ./dir user@host:/path

"You may need an appropriate loader to handle this file type" with Webpack and Babel

When using Typescript:

In my case I used the newer syntax of webpack v3.11 from their documentation page I just copied the css and style loaders configuration form their website. The commented out code (newer API) causes this error, see below.

  module: {
        loaders: [{
                test: /\.ts$/,
                loaders: ['ts-loader']
            },
            {
                test: /\.css$/,
                loaders: [
                    'style-loader',
                    'css-loader'
                ]
            }
        ]
        // ,
        // rules: [{
        //     test: /\.css$/,
        //     use: [
        //         'style-loader',
        //         'css-loader'
        //     ]
        // }]
    }

The right way is to put this:

    {
        test: /\.css$/,
        loaders: [
            'style-loader',
            'css-loader'
        ]
    }

in the array of the loaders property.

PyCharm import external library

updated on May 26-2018

If the external library is in a folder that is under the project then

File -> Settings -> Project -> Project structure -> select the folder and Mark as Sources!

If not, add content root, and do similar things.

Calculating the sum of two variables in a batch script

You need to use the property /a on the set command.

For example,

set /a "c=%a%+%b%"

This allows you to use arithmetic expressions in the set command, rather than simple concatenation.

Your code would then be:

@set a=3
@set b=4
@set /a "c=%a%+%b%"
echo %c%
@set /a "d=%c%+1"
echo %d%

and would output:

7
8

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

What are the various "Build action" settings in Visual Studio project properties and what do they do?

  • Fakes: Part of the Microsoft Fakes (Unit Test Isolation) Framework. Not available on all Visual Studio versions. Fakes are used to support unit testing in your project, helping you isolate the code you are testing by replacing other parts of the application with stubs or shims. More here: https://msdn.microsoft.com/en-us/library/hh549175.aspx

How to import large sql file in phpmyadmin

I have made a PHP script which is designed to import large database dumps which have been generated by phpmyadmin. It's called PETMI and you can download it here [project page] [gitlab page]. It has been tested with a 1GB database.

Invalid column name sql error

You problem is that your string are unquoted. Which mean that they are interpreted by your database engine as a column name.

You need to create parameters in order to pass your value to the query.

 cmd.CommandText = "INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address);";
 cmd.Parameters.AddWithValue("@Name", txtName.Text);
 cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
 cmd.Parameters.AddWithValue("@Address", txtAddress.Text);

Convert Year/Month/Day to Day of Year in Python

If you have reason to avoid the use of the datetime module, then these functions will work.

def is_leap_year(year):
    """ if year is a leap year return True
        else return False """
    if year % 100 == 0:
        return year % 400 == 0
    return year % 4 == 0

def doy(Y,M,D):
    """ given year, month, day return day of year
        Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
    if is_leap_year(Y):
        K = 1
    else:
        K = 2
    N = int((275 * M) / 9.0) - K * int((M + 9) / 12.0) + D - 30
    return N

def ymd(Y,N):
    """ given year = Y and day of year = N, return year, month, day
        Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """    
    if is_leap_year(Y):
        K = 1
    else:
        K = 2
    M = int((9 * (K + N)) / 275.0 + 0.98)
    if N < 32:
        M = 1
    D = N - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
    return Y, M, D

How to set standard encoding in Visual Studio

I work with Windows7.

Control Panel - Region and Language - Administrative - Language for non-Unicode programs.

After I set "Change system locale" to English(United States). My default encoding of vs2010 change to Windows-1252. It was gb2312 before.

I created a new .cpp file for a C++ project, after checking in the new file to TFS the encoding show Windows-1252 from the properties page of the file.

WooCommerce - get category for product page

Thanks Box. I'm using MyStile Theme and I needed to display the product category name in my search result page. I added this function to my child theme functions.php

Hope it helps others.

/* Post Meta */


if (!function_exists( 'woo_post_meta')) {
    function woo_post_meta( ) {
        global $woo_options;
        global $post;

        $terms = get_the_terms( $post->ID, 'product_cat' );
        foreach ($terms as $term) {
            $product_cat = $term->name;
            break;
        }

?>
<aside class="post-meta">
    <ul>
        <li class="post-category">
            <?php the_category( ', ', $post->ID) ?>
                        <?php echo $product_cat; ?>

        </li>
        <?php the_tags( '<li class="tags">', ', ', '</li>' ); ?>
        <?php if ( isset( $woo_options['woo_post_content'] ) && $woo_options['woo_post_content'] == 'excerpt' ) { ?>
            <li class="comments"><?php comments_popup_link( __( 'Leave a comment', 'woothemes' ), __( '1 Comment', 'woothemes' ), __( '% Comments', 'woothemes' ) ); ?></li>
        <?php } ?>
        <?php edit_post_link( __( 'Edit', 'woothemes' ), '<li class="edit">', '</li>' ); ?>
    </ul>
</aside>
<?php
    }
}


?>

Oracle find a constraint

maybe this can help..

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

Difference between ref and out parameters in .NET

out specifies that the parameter is an output parameters, i.e. it has no value until it is explicitly set by the method.

ref specifies that the value is a reference that has a value, and whose value you can change inside the method.

Terminating a Java Program

  1. System.exit() is a method that causes JVM to exit.
  2. return just returns the control to calling function.
  3. return 8 will return control and value 8 to calling method.

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


How to fix Subversion lock error

use tortoise svn to cleanup with 'break write locks' option checked

ISO C90 forbids mixed declarations and code in C

Up until the C99 standard, all declarations had to come before any statements in a block:

void foo()
{
  int i, j;
  double k;
  char *c;

  // code

  if (c)
  {
    int m, n;

    // more code
  }
  // etc.
}

C99 allowed for mixing declarations and statements (like C++). Many compilers still default to C89, and some compilers (such as Microsoft's) don't support C99 at all.

So, you will need to do the following:

  1. Determine if your compiler supports C99 or later; if it does, configure it so that it's compiling C99 instead of C89;

  2. If your compiler doesn't support C99 or later, you will either need to find a different compiler that does support it, or rewrite your code so that all declarations come before any statements within the block.

Get the selected option id with jQuery

Th easiest way to this is var id = $(this).val(); from inside an event like on change.

How do I get the value of a textbox using jQuery?

Per Jquery docs

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

In order to retrieve the value store in the text box with id txtEmail, you can use

$("#txtEmail").val()

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Just Create New User for MySQL do not use root. there is a problem its security issue

sudo mysql -p -u root

Login into MySQL or MariaDB with root privileges

CREATE USER 'troy121'@'%' IDENTIFIED BY 'mypassword123';

login and create a new user

GRANT ALL PRIVILEGES ON *.* TO 'magento121121'@'%' WITH GRANT OPTION;

and grant privileges to access "." and "@" "%" any location not just only 'localhost'

exit;

if you want to see your privilege table SHOW GRANTS; & Enjoy.

How do I move a redis database from one server to another?

To check where the dump.rdb has to be placed when importing redis data,

start client

$redis-cli

and

then

redis 127.0.0.1:6379> CONFIG GET *
 1) "dir"
 2) "/Users/Admin"

Here /Users/Admin is the location of dump.rdb that is read from server and therefore this is the file that has to be replaced.

Initialize value of 'var' in C# to null

The var keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var keyword has a type. For instance, you'll find that the following code outputs "String".

var myString = "";
Console.Write(myString.GetType().Name);

Furthermore, the code above is equivalent to:

String myString = "";
Console.Write(myString.GetType().Name);

The var keyword is simply C#'s way of saying "I can figure out the type for myString from the context, so don't worry about specifying the type."

var myVariable = (MyType)null or MyType myVariable = null should work because you are giving the C# compiler context to figure out what type myVariable should will be.

For more information:

DLL load failed error when importing cv2

I ran into this problem on Windows 10 (N) with a new Anaconda installation based on Python 3.7 (OpenCV version 4.0). None of the above advice helped (such as installing OpenCV from the unofficial site nor installing VC Redistributable).

I checked DLL dependencies of ...\AppData\Local\conda\conda\envs\foo\Lib\site-packages\cv2\cv2.cp37-win_amd64.pyd using dumpbin.exe according to this github issue. I noticed a library MF.dll, which I figured out belongs to Windows Media Foundation.

So I installed Media Feature Pack for N versions of Windows 10 and voilà, the issue was resolved!

Adding/removing items from a JavaScript object with jQuery

If you are using jQuery you can use the extend function to add new items.

var olddata = {"fruit":{"apples":10,"pears":21}};

var newdata = {};
newdata['vegetables'] = {"carrots": 2, "potatoes" : 5};

$.extend(true, olddata, newdata);

This will generate:

{"fruit":{"apples":10,"pears":21}, "vegetables":{"carrots":2,"potatoes":5}};

Spring JPA selecting specific columns

You can use the answer suggested by @jombie, and:

  • place the interface in a separate file, outside the entity class;
  • use native query or not (the choice depended on your needs);
  • don't override findAll() method for this purpose but use name of your choice;
  • remember to return a List parametrized with your new interface (e.g. List<SmallProject>).

What is the difference between Tomcat, JBoss and Glassfish?

You should use GlassFish for Java EE enterprise applications. Some things to consider:

A web Server means: Handling HTTP requests (usually from browsers).

A Servlet Container (e.g. Tomcat) means: It can handle servlets & JSP.

An Application Server (e.g. GlassFish) means: *It can manage Java EE applications (usually both servlet/JSP and EJBs).


Tomcat - is run by Apache community - Open source and has two flavors:

  1. Tomcat - Web profile - lightweight which is only servlet container and does not support Java EE features like EJB, JMS etc.
  2. Tomcat EE - This is a certified Java EE container, this supports all Java EE technologies.

No commercial support available (only community support)

JBoss - Run by RedHat This is a full-stack support for JavaEE and it is a certified Java EE container. This includes Tomcat as web container internally. This also has two flavors:

  1. Community version called Application Server (AS) - this will have only community support.
  2. Enterprise Application Server (EAP) - For this, you can have a subscription-based license (It's based on the number of Cores you have on your servers.)

Glassfish - Run by Oracle This is also a full stack certified Java EE Container. This has its own web container (not Tomcat). This comes from Oracle itself, so all new specs will be tested and implemented with Glassfish first. So, always it would support the latest spec. I am not aware of its support models.

UIImageView aspect fit and center

I solved this problem like this.

  1. setImage to UIImageView (with UIViewContentModeScaleAspectFit)
  2. get imageSize (CGSize imageSize = imageView.image.size)
  3. UIImageView resize. [imageView sizeThatFits:imageSize]
  4. move position where you want.

I wanted to put UIView on the top center of UICollectionViewCell. so, I used this function.

- (void)setImageToCenter:(UIImageView *)imageView
{
    CGSize imageSize = imageView.image.size;
    [imageView sizeThatFits:imageSize];
    CGPoint imageViewCenter = imageView.center;
     imageViewCenter.x = CGRectGetMidX(self.contentView.frame);
    [imageView setCenter:imageViewCenter];
}

It works for me.

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I ran into the same error, when I just forgot to declare my custom component in my NgModule - check there, if the others solutions won't work for you.

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

you can call window.open without browser blocking only if user does directly some action. Browser send some flag and determine that window opened by user action.

So, you can try this scenario:

  1. var myWindow = window.open('')
  2. draw any loading message in this window
  3. when request done, just call myWindow.location = 'http://google.com'

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

I faced this issue because of lower version of Jdk. Previously I installed Jdk 1.7 and Android Studio 1.5.1, I got this issue. If you install Android Studio 1.5.1 or above JDK 1.8 required

So Installing JDK 1.8 solved this issue.

Why can't Python import Image from PIL?

FWIW, the following worked for me when I had this same error:

pip install --upgrade --force-reinstall pillow

How to delete a folder with files using Java

This works, and while it looks inefficient to skip the directory test, it's not: the test happens right away in listFiles().

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            deleteDir(f);
        }
    }
    file.delete();
}

Update, to avoid following symbolic links:

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            if (! Files.isSymbolicLink(f.toPath())) {
                deleteDir(f);
            }
        }
    }
    file.delete();
}

document.getElementById vs jQuery $()

In case someone else hits this... Here's another difference:

If the id contains characters that are not supported by the HTML standard (see SO question here) then jQuery may not find it even if getElementById does.

This happened to me with an id containing "/" characters (ex: id="a/b/c"), using Chrome:

var contents = document.getElementById('a/b/c');

was able to find my element but:

var contents = $('#a/b/c');

did not.

Btw, the simple fix was to move that id to the name field. JQuery had no trouble finding the element using:

var contents = $('.myclass[name='a/b/c']);

PadLeft function in T-SQL

I created a function:

CREATE FUNCTION [dbo].[fnPadLeft](@int int, @Length tinyint)
RETURNS varchar(255) 
AS 
BEGIN
    DECLARE @strInt varchar(255)

    SET @strInt = CAST(@int as varchar(255))
    RETURN (REPLICATE('0', (@Length - LEN(@strInt))) + @strInt);
END;

Use: select dbo.fnPadLeft(123, 10)

Returns: 0000000123

Remove all occurrences of a value from a list?

To remove all duplicate occurrences and leave one in the list:

test = [1, 1, 2, 3]

newlist = list(set(test))

print newlist

[1, 2, 3]

Here is the function I've used for Project Euler:

def removeOccurrences(e):
  return list(set(e))

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

This worked for me:

git branch

Copy the current branch name to clipboard

git pull origin <paste-branch-name>
git push

Encoding an image file with base64

import base64
from PIL import Image
from io import BytesIO

with open("image.jpg", "rb") as image_file:
    data = base64.b64encode(image_file.read())

im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')

syntax error near unexpected token `('

Try

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Do I need to close() both FileReader and BufferedReader?

As others have pointed out, you only need to close the outer wrapper.

BufferedReader reader = new BufferedReader(new FileReader(fileName));

There is a very slim chance that this could leak a file handle if the BufferedReader constructor threw an exception (e.g. OutOfMemoryError). If your app is in this state, how careful your clean up needs to be might depend on how critical it is that you don't deprive the OS of resources it might want to allocate to other programs.

The Closeable interface can be used if a wrapper constructor is likely to fail in Java 5 or 6:

Reader reader = new FileReader(fileName);
Closeable resource = reader;
try {
  BufferedReader buffered = new BufferedReader(reader);
  resource = buffered;
  // TODO: input
} finally {
  resource.close();
}

Java 7 code should use the try-with-resources pattern:

try (Reader reader = new FileReader(fileName);
    BufferedReader buffered = new BufferedReader(reader)) {
  // TODO: input
}

Determine a user's timezone

I still have not seen a detailed answer here that gets the time zone. You shouldn't need to geocode by IP address or use PHP (lol) or incorrectly guess from an offset.

Firstly a time zone is not just an offset from GMT. It is an area of land in which the time rules are set by local standards. Some countries have daylight savings, and will switch on DST at differing times. It's usually important to get the actual zone, not just the current offset.

If you intend to store this timezone, for instance in user preferences you want the zone and not just the offset. For realtime conversions it won't matter much.

Now, to get the time zone with javascript you can use this:

>> new Date().toTimeString();
"15:46:04 GMT+1200 (New Zealand Standard Time)"
//Use some regular expression to extract the time.

However I found it easier to simply use this robust plugin which returns the Olsen formatted timezone:

https://github.com/scottwater/jquery.detect_timezone

Using Git with Visual Studio

I find that Git, working on whole trees as it does, benefits less from IDE integration than source control tools that are either file based or follow a checkout-edit-commit pattern. Of course there are instances when it can be nice to click on a button to do some history examination, but I don't miss that very much.

The real must-do is to get your .gitignore file full of the things that shouldn't be in a shared repository. Mine generally contain (amongst other stuff) the following:

*.vcproj.*.user
*.ncb
*.aps
*.suo

but this is heavily C++ biased with little or no use of any class wizard style functionality.

My usage pattern is something like the following.

  1. Code, code, code in Visual Studio.

  2. When happy (sensible intermediate point to commit code, switch to Git, stage changes and review diffs. If anything's obviously wrong switch back to Visual Studio and fix, otherwise commit.

Any merge, branch, rebase or other fancy SCM stuff is easy to do in Git from the command prompt. Visual Studio is normally fairly happy with things changing under it, although it can sometimes need to reload some projects if you've altered the project files significantly.

I find that the usefulness of Git outweighs any minor inconvenience of not having full IDE integration but it is, to some extent, a matter of taste.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

This error occurs when the client URL and server URL don't match, including the port number. In this case you need to enable your service for CORS which is cross origin resource sharing.

If you are hosting a Spring REST service then you can find it in the blog post CORS support in Spring Framework.

If you are hosting a service using a Node.js server then

  1. Stop the Node.js server.
  2. npm install cors --save
  3. Add following lines to your server.js

    var cors = require('cors')
    
    app.use(cors()) // Use this after the variable declaration
    

How to get a jqGrid cell value when editing

In my case the contents of my cell is HTML as result of a formatter. I want the value inside anchor tag. By fetching the cell contents and then creating an element out of the html via jQuery I am able to then access the raw value by calling .text() on my newly created element.

var cellContents = grid.getCell(rowid, 'ColNameHere');
console.log($(cellContents)); 
//in my case logs <h3><a href="#">The Value I'm After</a></h3>

var cellRawValue = $(cellContents).text();
console.log(cellRawValue); //outputs "The Value I'm After!"

my answer is based on @LLQ answer, but since in my case my cellContents isn't an input I needed to use .text() instead of .val() to access the raw value so I thought I'd post this in case anyone else is looking for a way to access the raw value of a formatted jqGrid cell.

Create a tar.xz in one command

Switch -J only works on newer systems. The universal command is:

To make .tar.xz archive

tar cf - directory/ | xz -z - > directory.tar.xz

Explanation

  1. tar cf - directory reads directory/ and starts putting it to TAR format. The output of this operation is generated on the standard output.

  2. | pipes standard output to the input of another program...

  3. ... which happens to be xz -z -. XZ is configured to compress (-z) the archive from standard input (-).

  4. You redirect the output from xz to the tar.xz file.

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

C++ Returning reference to local variable

A local variable is memory on the stack, that memory is not automatically invalidated when you go out of scope. From a Function deeper nested (higher on the stack in memory), its perfectly safe to access this memory.

Once the Function returns and ends though, things get dangerous. Usually the memory is not deleted or overwritten when you return, meaning the memory at that adresss is still containing your data - the pointer seems valid.

Until another function builds up the stack and overwrites it. This is why this can work for a while - and then suddenly cease to function after one particularly deeply nested set of functions, or a function with really huge sized or many local objects, reaches that stack-memory again.

It even can happen that you reach the same program part again, and overwrite your old local function variable with the new function variable. All this is very dangerous and should be heavily discouraged. Do not use pointers to local objects!

Use superscripts in R axis labels

This is a quick example

plot(rnorm(30), xlab = expression(paste("4"^"th")))

how to add super privileges to mysql database?

just the query phpmyadmin prints after granting super user. hope help someone with console:

ON $.$ TO-> $=* doesnt show when you put two with a dot between them.

REVOKE ALL PRIVILEGES ON . FROM 'usr'@'localhost'; GRANT ALL PRIVILEGES ON . TO 'usr'@'localhost' REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

and the reverse one, removing grant:

REVOKE ALL PRIVILEGES ON . FROM 'dos007'@'localhost'; REVOKE GRANT OPTION ON . FROM 'dos007'@'localhost'; GRANT ALL PRIVILEGES ON . TO 'dos007'@'localhost' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

checked on vagrant should be working in any mysql

Jinja2 template variable if None Object set a default value

I usually define an nvl function, and put it in globals and filters.

def nvl(*args):
    for item in args:
        if item is not None:
            return item
    return None

app.jinja_env.globals['nvl'] = nvl
app.jinja_env.filters['nvl'] = nvl

Usage in a template:

<span>Welcome {{ nvl(person.nick, person.name, 'Anonymous') }}<span>

// or 

<span>Welcome {{ person.nick | nvl(person.name, 'Anonymous') }}<span>

Using union and order by clause in mysql

You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:

select *
from (
    select 1 as Rank, id, add_date from Table 
    union all
    select 2 as Rank, id, add_date from Table where distance < 5
    union all
    select 3 as Rank, id, add_date from Table where distance between 5 and 15
) a
order by rank, id, add_date desc

Serialize and Deserialize Json and Json Array in Unity

IF you are using Vector3 this is what i did

1- I create a class Name it Player

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Player
{
    public Vector3[] Position;

}

2- then i call it like this

if ( _ispressed == true)
        {
            Player playerInstance = new Player();
            playerInstance.Position = newPos;
            string jsonData = JsonUtility.ToJson(playerInstance);

            reference.Child("Position" + Random.Range(0, 1000000)).SetRawJsonValueAsync(jsonData);
            Debug.Log(jsonData);
            _ispressed = false;
        }

3- and this is the result

"Position":[ {"x":-2.8567452430725099,"y":-2.4323320388793947,"z":0.0}]}

How can I dynamically add items to a Java array?

Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:

/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)

How to check if any value is NaN in a Pandas DataFrame

df.isnull().sum()

This will give you count of all NaN values present in the respective coloums of the DataFrame.

How to open link in new tab on html?

When to use target='_blank' :

The HTML version (Some devices not support it):

<a href="http://chriscoyier.net" target="_blank">This link will open in new window/tab</a>

The JavaScript version for all Devices :

The use of rel="external" is perfectly valid

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    $('a[rel="external"]').attr('target', '_blank');
</script>

and for Jquery can try with the below one:

$("#content a[href^='http://']").attr("target","_blank");

If browser setting don't allow you to open in new windows :

href = "google.com";
onclick="window.open (this.href, ''); return false";

How to use the 'replace' feature for custom AngularJS directives?

replace:true is Deprecated

From the Docs:

replace ([DEPRECATED!], will be removed in next major release - i.e. v2.0)

specify what the template should replace. Defaults to false.

  • true - the template will replace the directive's element.
  • false - the template will replace the contents of the directive's element.

-- AngularJS Comprehensive Directive API

From GitHub:

Caitp-- It's deprecated because there are known, very silly problems with replace: true, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".

-- AngularJS Issue #7636


Update

Note: replace: true is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.

Issues with replace: true

For more information, see

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

printing all contents of array in C#

The easiest one e.g. if you have a string array declared like this string[] myStringArray = new string[];

Console.WriteLine("Array : ");
Console.WriteLine("[{0}]", string.Join(", ", myStringArray));

How to add RSA key to authorized_keys file?

I know I am replying too late but for anyone else who needs this, run following command from your local machine

cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

this has worked perfectly fine. All you need to do is just to replace

[email protected]

with your own user for that particular host

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

json.loads will load a json string into a python dict, json.dumps will dump a python dict to a json string, for example:

>>> json_string = '{"favorited": false, "contributors": null}'
'{"favorited": false, "contributors": null}'
>>> value = json.loads(json_string)
{u'favorited': False, u'contributors': None}
>>> json_dump = json.dumps(value)
'{"favorited": false, "contributors": null}'

So that line is incorrect since you are trying to load a python dict, and json.loads is expecting a valid json string which should have <type 'str'>.

So if you are trying to load the json, you should change what you are loading to look like the json_string above, or you should be dumping it. This is just my best guess from the given information. What is it that you are trying to accomplish?

Also you don't need to specify the u before your strings, as @Cld mentioned in the comments.

How do I apply the for-each loop to every character in a String?

For Travers an String you can also use charAt() with the string.

like :

String str = "xyz"; // given String
char st = str.charAt(0); // for example we take 0 index element 
System.out.println(st); // print the char at 0 index 

charAt() is method of string handling in java which help to Travers the string for specific character.

How to open remote files in sublime text 3

On server

Install rsub:

wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub

On local

  1. Install rsub Sublime3 package:

On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it

  1. Open command line and connect to remote server:

ssh -R 52698:localhost:52698 server_user@server_address

  1. after connect to server run this command on server:

rsub path_to_file/file.txt

  1. File opening auto in Sublime 3

As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.

Junit test case for database insert method with DAO and web service

@Test
public void testSearchManagementStaff() throws SQLException
{
    boolean res=true;
    ManagementDaoImp mdi=new ManagementDaoImp();
    boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
    assertEquals(res,b);
}

Use the auto keyword in C++ STL

The auto keyword is simply asking the compiler to deduce the type of the variable from the initialization.

Even a pre-C++0x compiler knows what the type of an (initialization) expression is, and more often than not, you can see that type in error messages.

#include <vector>
#include <iostream>
using namespace std;

int main()
{
    vector<int>s;
    s.push_back(11);
    s.push_back(22);
    s.push_back(33);
    s.push_back(55);
    for (int it=s.begin();it!=s.end();it++){
        cout<<*it<<endl;
    }
}

Line 12: error: cannot convert '__gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<int*, __gnu_norm::vector<int, std::allocator<int> > >, __gnu_debug_def::vector<int, std::allocator<int> > >' to 'int' in initialization

The auto keyword simply allows you to take advantage of this knowledge - if you (compiler) know the right type, just choose for me!

Pandas dataframe get first row of each group

This will give you the second row of each group (zero indexed, nth(0) is the same as first()):

df.groupby('id').nth(1) 

Documentation: http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group

How to refresh a Page using react-route Link

To refresh page you don't need react-router, simple js:

window.location.reload();

To re-render view in React component, you can just fire update with props/state.

Persistent invalid graphics state error when using ggplot2

I found this to occur when you mix ggplot charts with plot charts in the same session. Using the 'dev.off' solution suggested by Paul solves the issue.

Set mouse focus and move cursor to end of input using jQuery

    function focusCampo(id){
        var inputField = document.getElementById(id);
        if (inputField != null && inputField.value.length != 0){
            if (inputField.createTextRange){
                var FieldRange = inputField.createTextRange();
                FieldRange.moveStart('character',inputField.value.length);
                FieldRange.collapse();
                FieldRange.select();
            }else if (inputField.selectionStart || inputField.selectionStart == '0') {
                var elemLen = inputField.value.length;
                inputField.selectionStart = elemLen;
                inputField.selectionEnd = elemLen;
                inputField.focus();
            }
        }else{
            inputField.focus();
        }
    }

$('#urlCompany').focus(focusCampo('urlCompany'));

works for all ie browsers..

How to install a package inside virtualenv?

Well i don't have an appropriate reason regarding why this behavior occurs but then i just found a small work around

Inside the VirtualEnvironment

pip install -Iv package_name==version_number

now this will install the version in your virtual environment

Additionally you can check inside the virtual environment with this

pip install yolk
yolk -l

This shall give you the details of all the installed packages in both the locations(system and virtualenv)

While some might say its not appropriate to use --system-site-packages (it may be true), but what if you have already done a lot of stuffs inside your virtualenv? Now you dont want to redo everything from the scratch.

You may use this as a hack and be careful from the next time :)

Setting an image button in CSS - image:active

This is what worked for me.

<!DOCTYPE html> 
<form action="desired Link">
  <button>  <img src="desired image URL"/>
  </button>
</form>
<style> 

</style>