Programs & Examples On #Nsinputstream

0

Sort objects in ArrayList by date?

You can use Collections.sort method. It's a static method. You pass it the list and a comparator. It uses a modified mergesort algorithm over the list. That's why you must pass it a comparator to do the pair comparisons.

Collections.sort(myList, new Comparator<MyObject> {
   public int compare(MyObject o1, MyObject o2) {
      DateTime a = o1.getDateTime();
      DateTime b = o2.getDateTime();
      if (a.lt(b)) 
        return -1;
      else if (a.lteq(b)) // it's equals
         return 0;
      else
         return 1;
   }
});

Note that if myList is of a comparable type (one that implements Comparable interface) (like Date, Integer or String) you can omit the comparator and the natural ordering will be used.

Is it possible to cast a Stream in Java 8?

This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast Stream<Object> to a Stream<Client>?

No that wouldn't be possible. This is not new in Java 8. This is specific to generics. A List<Object> is not a super type of List<String>, so you can't just cast a List<Object> to a List<String>.

Similar is the issue here. You can't cast Stream<Object> to Stream<Client>. Of course you can cast it indirectly like this:

Stream<Client> intStream = (Stream<Client>) (Stream<?>)stream;

but that is not safe, and might fail at runtime. The underlying reason for this is, generics in Java are implemented using erasure. So, there is no type information available about which type of Stream it is at runtime. Everything is just Stream.

BTW, what's wrong with your approach? Looks fine to me.

How to customize the background color of a UITableViewCell?

I concur with Seba, I tried to set my alternating row color in the rowForIndexPath delegate method but was getting inconsistent results between 3.2 and 4.2. The following worked great for me.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    if ((indexPath.row % 2) == 1) {
        cell.backgroundColor = UIColorFromRGB(0xEDEDED);
        cell.textLabel.backgroundColor = UIColorFromRGB(0xEDEDED);
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    else
    {
        cell.backgroundColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }

}

how to remove multiple columns in r dataframe?

Adding answer as this was the top hit when searching for "drop multiple columns in r":

The general version of the single column removal, e.g df$column1 <- NULL, is to use list(NULL):

df[ ,c('column1', 'column2')] <- list(NULL)

This also works for position index as well:

df[ ,c(1,2)] <- list(NULL)

This is a more general drop and as some comments have mentioned, removing by indices isn't recommended. Plus the familiar negative subset (used in other answers) doesn't work for columns given as strings:

> iris[ ,-c("Species")]
Error in -"Species" : invalid argument to unary operator

Stop handler.postDelayed()

this may be old, but for those looking for answer you can use this...

public void stopHandler() {
   handler.removeMessages(0);
}

cheers

How do I write a Windows batch script to copy the newest file from a directory?

Bash:

 find -type f -printf "%T@ %p \n" \
     | sort  \
     | tail -n 1  \
     | sed -r "s/^\S+\s//;s/\s*$//" \
     | xargs -iSTR cp STR newestfile

where "newestfile" will become the newestfile

alternatively, you could do newdir/STR or just newdir

Breakdown:

  1. list all files in {time} {file} format.
  2. sort them by time
  3. get the last one
  4. cut off the time, and whitespace from the start/end
  5. copy resulting value

Important

After running this once, the newest file will be whatever you just copied :p ( assuming they're both in the same search scope that is ). So you may have to adjust which filenumber you copy if you want this to work more than once.

Easiest way to split a string on newlines in .NET?

To split on a string you need to use the overload that takes an array of strings:

string[] lines = theText.Split(
    new[] { Environment.NewLine },
    StringSplitOptions.None
);

Edit:
If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:

string[] lines = theText.Split(
    new[] { "\r\n", "\r", "\n" },
    StringSplitOptions.None
);

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

export IGNORE_WARNINGS=1

It does display warnings, but continues with the build

Visual Studio opens the default browser instead of Internet Explorer

With VS 2017, debugging ASP.NET project with Chrome doesn't sign you in with your Google account.

To fix that go to Tools -> Options -> Debugging -> General and turn off the setting Enable JavaScript Debugging for ASP.NET (Chrome and IE).

https://msdnshared.blob.core.windows.net/media/2016/11/debugger-settings-1024x690.png

Map and Reduce in .NET

Linq equivalents of Map and Reduce: If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.

  • Map is Select:

    Enumerable.Range(1, 10).Select(x => x + 2);
    
  • Reduce is Aggregate:

    Enumerable.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
    
  • Filter is Where:

    Enumerable.Range(1, 10).Where(x => x % 2 == 0);
    

https://www.justinshield.com/2011/06/mapreduce-in-c/

Redirect after Login on WordPress

// Used theme's functions.php  
add_action('login_form', 'redirect_after_login'); 
function redirect_after_login() 
{     
global $redirect_to; 
if   (!isset($_GET['redirect_to'])) 
{ 
$redirect_to =   get_option('sample-page');
//  sample-page = your page name after site_url
} }

How to initialize a vector of vectors on a struct?

Like this:

#include <vector>

// ...

std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));

(Pre-C++11 you need to leave whitespace between the angled brackets.)

How to sleep for five seconds in a batch file/cmd

I use the following method entirely based on Windows XP capabilities to do a delay in a batch file:

File DELAY.BAT

@ECHO OFF
REM DELAY seconds

REM GET ENDING SECOND
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100,     S=1%%C%%100, ENDING=(H*60+M)*60+S+%1

REM WAIT FOR SUCH A SECOND
:WAIT
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, CURRENT=(H*60+M)*60+S
IF %CURRENT% LSS %ENDING% GOTO WAIT

You may also insert the day in the calculation so the method also works when the delay interval pass over midnight.

Compare 2 arrays which returns difference

if you also want to compare the order of the answer you can extend the answer to something like this:

Array.prototype.compareTo = function (array2){
    var array1 = this;
    var difference = [];
    $.grep(array2, function(el) {
        if ($.inArray(el, array1) == -1) difference.push(el);
    });
    if( difference.length === 0 ){
        var $i = 0;
        while($i < array1.length){
            if(array1[$i] !== array2[$i]){
                return false;
            }
            $i++;
        }
        return true;
    }
    return false;
}

font size in html code

There are a couple of answers posted here that will give you the text effects you want, but...

The thing about tables is that they are organized collections of labels and data. Having both a label ("Datum") and the value that it labels in the same cell is oh so very wrong. The label should be in a <th> element, with the value in a <td> either in the same row or the same column (depending on the data arrangement you are trying to achieve). You can have <th> elements running either vertically or horizontally or both, but if you don't have heading cells (which is what <th> means), you don't have a table, you just have a meaningless grid of text. It would be preferable, too, to have a <caption> element to label the table as a whole (you don't have to display the caption, but it should be there for accessibility) and have a summary="blah blah blah" attribute in the table tag, again for accessibility. So your HTML should probably look a lot more like this:

<html>
  <head>
    <title>Test page with Table<title>
    <style type="text/css">
      th {
        font-size: 35px;
        font-weight: bold;
        padding-left: 5px;
        padding-bottom: 3px;
      }
    </style>
  </head>
  <body>
    <table id="table_1" summary="This table has both labels and values">
      <caption>Table of Stuff</caption>
      <tr>
        <th>Datum</th>
        <td>November 2010</td>
      </tr>
    </table>
  </body>
</html>

That may not be exactly what you want -- it's hard to tell whether November 2010 is a data point or a label from what you've posted, and "Datum" isn't a helpful label in any case. Play with it a bit, but make sure that when your table is finished it actually has some kind of semantic meaning. If it's not a real table of data, then don't use a <table> to lay it out.

Dynamically create checkbox with JQuery from text input

One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?

Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...

<div id="checkboxes">
    <input type="checkbox" /> Some label<br />
    <input type="checkbox" /> Some other label<br />
</div>

<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>

Based on this markup your jquery could bind to the click event of the button and manipulate the DOM.

$('#addCheckbox').click(function() {
    var text = $('#newCheckText').val();
    $('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

Postgres: How to do Composite keys?

Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too:

 CREATE TABLE tags
      (
               question_id INTEGER NOT NULL,
               tag_id SERIAL NOT NULL,
               tag1 VARCHAR(20),
               tag2 VARCHAR(20),
               tag3 VARCHAR(20),
               PRIMARY KEY(question_id, tag_id)
      );

NOTICE:  CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
    CREATE TABLE
    pg=> \d tags
                                         Table "public.tags"
       Column    |         Type          |                       Modifiers       
    -------------+-----------------------+-------------------------------------------------------
     question_id | integer               | not null
     tag_id      | integer               | not null default nextval('tags_tag_id_seq'::regclass)
     tag1        | character varying(20) |
     tag2        | character varying(20) |
     tag3        | character varying(20) |
    Indexes:
        "tags_pkey" PRIMARY KEY, btree (question_id, tag_id)

Setting the filter to an OpenFileDialog to allow the typical image formats?

For those who don't want to remember the syntax everytime here is a simple encapsulation:

public class FileDialogFilter : List<string>
{
    public string Explanation { get; }

    public FileDialogFilter(string explanation, params string[] extensions)
    {
        Explanation = explanation;
        AddRange(extensions);
    }

    public string GetFileDialogRepresentation()
    {
        if (!this.Any())
        {
            throw new ArgumentException("No file extension is defined.");
        }

        StringBuilder builder = new StringBuilder();

        builder.Append(Explanation);

        builder.Append(" (");
        builder.Append(String.Join(", ", this));
        builder.Append(")");

        builder.Append("|");
        builder.Append(String.Join(";", this));

        return builder.ToString();
    }
}

public class FileDialogFilterCollection : List<FileDialogFilter>
{
    public string GetFileDialogRepresentation()
    {
        return String.Join("|", this.Select(filter => filter.GetFileDialogRepresentation()));
    }
}

Usage:

FileDialogFilter filterImage = new FileDialogFilter("Image Files", "*.jpeg", "*.bmp");
FileDialogFilter filterOffice = new FileDialogFilter("Office Files", "*.doc", "*.xls", "*.ppt");

FileDialogFilterCollection filters = new FileDialogFilterCollection
{
    filterImage,
    filterOffice
};

OpenFileDialog fileDialog = new OpenFileDialog
{
    Filter = filters.GetFileDialogRepresentation()
};

fileDialog.ShowDialog();

Getting or changing CSS class property with Javascript using DOM style

If you are looking for sending color data from backend

def color():
    color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
    return color

CSS: center element within a <div> element

Is the div a fixed width or a fluid width? Either way, for fluid width you could use:

#element { /* this is the child div */
margin-left:auto;
margin-right:auto;
/* Add remaining styling here */
}

Or you could set the parent div to text-align:center; and the child div to text-align:left;.

And left:50%; only centers it according to the whole page when the div is set to position:absolute;. If yous set the div to left:50%; it should do it relative to the parent div's width. For fixed width, do this:

#parent {
width:500px;
}

#child {
left:50%;
margin-left:-100px;
width:200px;
}

Common HTTPclient and proxy

Although this question is very old, but I see still there are no exact answer. I will try to answer the question here.

I believe the question in short here is how to set the proxy settings for the Apache commons HttpClient (org.apache.commons.httpclient.HttpClient).

Code snippet below should work :

HttpClient client = new HttpClient();
HostConfiguration hostConfiguration = client.getHostConfiguration();
hostConfiguration.setProxy("localhost", 8080);
client.setHostConfiguration(hostConfiguration);

Angular 2: How to access an HTTP response body?

I had the same issue too and this worked for me try:

this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
  subscribe((res) => {
    let resSTR = JSON.stringify(res);
    let resJSON = JSON.parse(resStr);
    console.log(resJSON._body);
  })

Get selected item value from Bootstrap DropDown with specific ID

Works GReat.

Category Question Apple Banana Cherry
<input type="text" name="cat_q" id="cat_q">  

$(document).ready(function(){
    $("#btn_cat div a").click(function(){
       alert($(this).text());

    });
});

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

This has to be done during your exe4j configuration. In the fourth step of Exe4j wizard which is Executable Info select> Advanced options select 32-bit or 64-bit. This worked well for me. or else install both JDK tool-kits x64 and x32 in your machine.

How to increase font size in the Xcode editor?

You can use the following:

  1. Press xcode->preferences
  2. select fonts and colors
  3. select ANY font in the list and press cmd+a (select all fonts)
  4. select font size for all editor fonts at the bottom of the window

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

How do I put hint in a asp:textbox

Adding placeholder attributes from code-behind:

txtFilterTerm.Attributes.Add("placeholder", "Filter" + Filter.Name);

Or

txtFilterTerm.Attributes["placeholder"] = "Filter" + Filter.Name;

Adding placeholder attributes from aspx Page

<asp:TextBox type="text" runat="server" id="txtFilterTerm" placeholder="Filter" />

Or

<input type="text" id="txtFilterTerm" placeholder="Filter"/>

Remove a file from the list that will be committed

You have to reset that file to the original state and commit it again using --amend. This is done easiest using git checkout HEAD^.

Prepare demo:

$ git init
$ date >file-a
$ date >file-b
$ git add .
$ git commit -m "Initial commit"
$ date >file-a
$ date >file-b
$ git commit -a -m "the change which should only be file-a"

State before:

$ git show --stat
commit 4aa38f84e04d40a1cb40a5207ccd1a3cb3a4a317 (HEAD -> master)
Date:   Wed Feb 7 17:24:45 2018 +0100

    the change which should only be file-a

 file-a | 2 +-
 file-b | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

Here it comes: restore the previous version

$ git checkout HEAD^ file-b

commit it:

$ git commit --amend file-b
[master 9ef8b8b] the change which should only be file-a
 Date: Wed Feb 7 17:24:45 2018 +0100
 1 file changed, 1 insertion(+), 1 deletion(-)

State after:

$ git show --stat
commit 9ef8b8bab224c4d117f515fc9537255941b75885 (HEAD -> master)
Date:   Wed Feb 7 17:24:45 2018 +0100

    the change which should only be file-a

 file-a | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

Connecting to SQL Server Express - What is my server name?

You should be able to see it in the Services panel. Look for a servicename like Sql Server (MSSQLSERVER). The name in the parentheses is your instance name.

Pass parameter from a batch file to a PowerShell script

Assuming your script is something like the below snippet and named testargs.ps1

param ([string]$w)
Write-Output $w

You can call this at the commandline as:

PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"

This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.

What are the differences between Abstract Factory and Factory design patterns?

Real Life Example. (Easy to remember)

Factory

Imagine you are constructing a house and you approach a carpenter for a door. You give the measurement for the door and your requirements, and he will construct a door for you. In this case, the carpenter is a factory of doors. Your specifications are inputs for the factory, and the door is the output or product from the factory.

Abstract Factory

Now, consider the same example of the door. You can go to a carpenter, or you can go to a plastic door shop or a PVC shop. All of them are door factories. Based on the situation, you decide what kind of factory you need to approach. This is like an Abstract Factory.

I have explained here both Factory method pattern and abstract factory pattern beginning with not using them explaining issues and then solving issues by using the above patterns https://github.com/vikramnagineni/Design-Patterns/tree/master

How to display a confirmation dialog when clicking an <a> link?

Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:

document.body.onclick = function( e ) {
    // Cross-browser handling
    var evt = e || window.event,
        target = evt.target || evt.srcElement;

    // If the element clicked is an anchor
    if ( target.nodeName === 'A' ) {

        // Add the confirm box
        return confirm( 'Are you sure?' );
    }
};

This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.

class Person
  attr_accessor :age
  ...
end

Here, I can see that I may both read and write the age.

class Person
  attr_reader :age
  ...
end

Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.

But what is happening behind the scenes?

If you write:

attr_writer :age

That gets translated into:

def age=(value)
  @age = value
end

If you write:

attr_reader :age

That gets translated into:

def age
  @age
end

If you write:

attr_accessor :age

That gets translated into:

def age=(value)
  @age = value
end

def age
  @age
end

Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?

How do I change the select box arrow

CSS

select.inpSelect {
  //Remove original arrows
  -webkit-appearance: none; 
  //Use png at assets/selectArrow.png for the arrow on the right
  //Set the background color to a BadAss Green color 
  background: url(assets/selectArrow.png) no-repeat right #BADA55;
}

How to convert color code into media.brush?

What version of WPF are you using? I tried in both 3.5 and 4.0, and Fill="#FF000000" should work fine in a in the XAML. There is another syntax, however, if it doesn't. Here's a 3.5 XAML that I tested with two different ways. Better yet would be to use a resource.

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
        <Rectangle.Fill>
            <SolidColorBrush Color="#FF00AE00" />
        </Rectangle.Fill>
    </Rectangle>
</Grid>

Numpy first occurrence of value greater than existing value

given the sorted content of your array, there is an even faster method: searchsorted.

import time
N = 10000
aa = np.arange(-N,N)
%timeit np.searchsorted(aa, N/2)+1
%timeit np.argmax(aa>N/2)
%timeit np.where(aa>N/2)[0][0]
%timeit np.nonzero(aa>N/2)[0][0]

# Output
100000 loops, best of 3: 5.97 µs per loop
10000 loops, best of 3: 46.3 µs per loop
10000 loops, best of 3: 154 µs per loop
10000 loops, best of 3: 154 µs per loop

How to add icon to mat-icon-button

the above CSS can be written in SASS as follows (and it actually includes all button types, instead of just button.mat-button)

button,
a {
    &.mat-button,
    &.mat-raised-button,
    &.mat-flat-button,
    &.mat-stroked-button {
        .mat-icon {
            vertical-align: top;
            font-size: 1.25em;
        }
    }
}

Appending a vector to a vector

std::copy (b.begin(), b.end(), std::back_inserter(a));

This can be used in case the items in vector a have no assignment operator (e.g. const member).

In all other cases this solution is ineffiecent compared to the above insert solution.

How to run shell script on host from docker container?

This answer is just a more detailed version of Bradford Medeiros's solution, which for me as well turned out to be the best answer, so the credit goes to him.

In his answer, he explains WHAT to do (named pipes) but not exactly HOW to do it.

I have to admit I didn't know what are named pipes at the time I read his solution. So I struggled to implement it (while it's actually really simple), but I did succeed, so I'm happy to help by explaining how I did it. So the point of my answer is just detailing the commands you need to run in order to get it working, but again, credit goes to him.

PART 1 - Testing the named pipe concept without docker

On the main host, chose the folder where you want to put your named pipe file, for instance /path/to/pipe/ and a pipe name, for instance mypipe, and then run:

mkfifo /path/to/pipe/mypipe

The pipe is created. Type

ls -l /path/to/pipe/mypipe 

And check the access rights start with "p", such as

prw-r--r-- 1 root root 0 mypipe

Now run:

tail -f /path/to/pipe/mypipe

The terminal is now waiting for data to be sent into this pipe

Now open another terminal window.

And then run:

echo "hello world" > /path/to/pipe/mypipe

Check the first terminal (the one with tail -f), it should display "hello world"

PART 2 - Run commands through the pipe

On the host container, instead of running tail -f which just outputs whatever is sent as input, run this command that will execute it as commands:

eval "$(cat /path/to/pipe/mypipe)"

Then, from the other terminal, try running:

echo "ls -l" > /path/to/pipe/mypipe

Go back to the first terminal and you should see the result of the ls -l command.

PART 3 - Make it listen forever

You may have noticed that in the previous part, right after ls -l output is displayed, it stops listening for commands.

Instead of eval "$(cat /path/to/pipe/mypipe)", run:

while true; do eval "$(cat /path/to/pipe/mypipe)"; done

(you can nohup that)

Now you can send unlimited number of commands one after the other, they will all be executed, not just the first one.

PART 4 - Make it work even when reboot happens

The only caveat is if the host has to reboot, the "while" loop will stop working.

To handle reboot, here what I've done:

Put the while true; do eval "$(cat /path/to/pipe/mypipe)"; done in a file called execpipe.sh with #!/bin/bash header

Don't forget to chmod +x it

Add it to crontab by running

crontab -e

And then adding

@reboot /path/to/execpipe.sh

At this point, test it: reboot your server, and when it's back up, echo some commands into the pipe and check if they are executed. Of course, you aren't able to see the output of commands, so ls -l won't help, but touch somefile will help.

Another option is to modify the script to put the output in a file, such as:

while true; do eval "$(cat /path/to/pipe/mypipe)" &> /somepath/output.txt; done

Now you can run ls -l and the output (both stdout and stderr using &> in bash) should be in output.txt.

PART 5 - Make it work with docker

If you are using both docker compose and dockerfile like I do, here is what I've done:

Let's assume you want to mount the mypipe's parent folder as /hostpipe in your container

Add this:

VOLUME /hostpipe

in your dockerfile in order to create a mount point

Then add this:

volumes:
   - /path/to/pipe:/hostpipe

in your docker compose file in order to mount /path/to/pipe as /hostpipe

Restart your docker containers.

PART 6 - Testing

Exec into your docker container:

docker exec -it <container> bash

Go into the mount folder and check you can see the pipe:

cd /hostpipe && ls -l

Now try running a command from within the container:

echo "touch this_file_was_created_on_main_host_from_a_container.txt" > /hostpipe/mypipe

And it should work!

WARNING: If you have an OSX (Mac OS) host and a Linux container, it won't work (explanation here https://stackoverflow.com/a/43474708/10018801 and issue here https://github.com/docker/for-mac/issues/483 ) because the pipe implementation is not the same, so what you write into the pipe from Linux can be read only by a Linux and what you write into the pipe from Mac OS can be read only by a Mac OS (this sentence might not be very accurate, but just be aware that a cross-platform issue exists).

For instance, when I run my docker setup in DEV from my Mac OS computer, the named pipe as explained above does not work. But in staging and production, I have Linux host and Linux containers, and it works perfectly.

PART 7 - Example from Node.JS container

Here is how I send a command from my node js container to the main host and retrieve the output:

const pipePath = "/hostpipe/mypipe"
const outputPath = "/hostpipe/output.txt"
const commandToRun = "pwd && ls-l"

console.log("delete previous output")
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath)

console.log("writing to pipe...")
const wstream = fs.createWriteStream(pipePath)
wstream.write(commandToRun)
wstream.close()

console.log("waiting for output.txt...") //there are better ways to do that than setInterval
let timeout = 10000 //stop waiting after 10 seconds (something might be wrong)
const timeoutStart = Date.now()
const myLoop = setInterval(function () {
    if (Date.now() - timeoutStart > timeout) {
        clearInterval(myLoop);
        console.log("timed out")
    } else {
        //if output.txt exists, read it
        if (fs.existsSync(outputPath)) {
            clearInterval(myLoop);
            const data = fs.readFileSync(outputPath).toString()
            if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath) //delete the output file
            console.log(data) //log the output of the command
        }
    }
}, 300);

How to install Laravel's Artisan?

Explanation: When you install a new laravel project on your folder(for example myfolder) using the composer, it installs the complete laravel project inside your folder(myfolder/laravel) than artisan is inside laravel.that's, why you see an error,

Could not open input file: artisan

Solution: You have to go inside by command prompt to that location or move laravel files inside your folder.

What is Scala's yield?

I think the accepted answer is great, but it seems many people have failed to grasp some fundamental points.

First, Scala's for comprehensions are equivalent to Haskell's do notation, and it is nothing more than a syntactic sugar for composition of multiple monadic operations. As this statement will most likely not help anyone who needs help, let's try again… :-)

Scala's for comprehensions is syntactic sugar for composition of multiple operations with map, flatMap and filter. Or foreach. Scala actually translates a for-expression into calls to those methods, so any class providing them, or a subset of them, can be used with for comprehensions.

First, let's talk about the translations. There are very simple rules:

  1. This

    for(x <- c1; y <- c2; z <-c3) {...}
    

    is translated into

    c1.foreach(x => c2.foreach(y => c3.foreach(z => {...})))
    
  2. This

    for(x <- c1; y <- c2; z <- c3) yield {...}
    

    is translated into

    c1.flatMap(x => c2.flatMap(y => c3.map(z => {...})))
    
  3. This

    for(x <- c; if cond) yield {...}
    

    is translated on Scala 2.7 into

    c.filter(x => cond).map(x => {...})
    

    or, on Scala 2.8, into

    c.withFilter(x => cond).map(x => {...})
    

    with a fallback into the former if method withFilter is not available but filter is. Please see the section below for more information on this.

  4. This

    for(x <- c; y = ...) yield {...}
    

    is translated into

    c.map(x => (x, ...)).map((x,y) => {...})
    

When you look at very simple for comprehensions, the map/foreach alternatives look, indeed, better. Once you start composing them, though, you can easily get lost in parenthesis and nesting levels. When that happens, for comprehensions are usually much clearer.

I'll show one simple example, and intentionally omit any explanation. You can decide which syntax was easier to understand.

l.flatMap(sl => sl.filter(el => el > 0).map(el => el.toString.length))

or

for {
  sl <- l
  el <- sl
  if el > 0
} yield el.toString.length

withFilter

Scala 2.8 introduced a method called withFilter, whose main difference is that, instead of returning a new, filtered, collection, it filters on-demand. The filter method has its behavior defined based on the strictness of the collection. To understand this better, let's take a look at some Scala 2.7 with List (strict) and Stream (non-strict):

scala> var found = false
found: Boolean = false

scala> List.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3
7
9

scala> found = false
found: Boolean = false

scala> Stream.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3

The difference happens because filter is immediately applied with List, returning a list of odds -- since found is false. Only then foreach is executed, but, by this time, changing found is meaningless, as filter has already executed.

In the case of Stream, the condition is not immediatelly applied. Instead, as each element is requested by foreach, filter tests the condition, which enables foreach to influence it through found. Just to make it clear, here is the equivalent for-comprehension code:

for (x <- List.range(1, 10); if x % 2 == 1 && !found) 
  if (x == 5) found = true else println(x)

for (x <- Stream.range(1, 10); if x % 2 == 1 && !found) 
  if (x == 5) found = true else println(x)

This caused many problems, because people expected the if to be considered on-demand, instead of being applied to the whole collection beforehand.

Scala 2.8 introduced withFilter, which is always non-strict, no matter the strictness of the collection. The following example shows List with both methods on Scala 2.8:

scala> var found = false
found: Boolean = false

scala> List.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3
7
9

scala> found = false
found: Boolean = false

scala> List.range(1,10).withFilter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3

This produces the result most people expect, without changing how filter behaves. As a side note, Range was changed from non-strict to strict between Scala 2.7 and Scala 2.8.

Using If else in SQL Select statement

sql server 2012

  with
  student as 
(select sid,year from (
values (101,5),(102,5),(103,4),(104,3),(105,2),(106,1),(107,4)
) as student(sid,year)
)
select iif(year=5,sid,year) as myCol,* from student


 myCol  sid year
101 101 5
102 102 5
4   103 4
3   104 3
2   105 2
1   106 1
4   107 4

git ignore exception

Since Git 2.7.0 Git will take exceptions into account. From the official release notes:

  • Allow a later "!/abc/def" to override an earlier "/abc" that appears in the same .gitignore file to make it easier to express "everything in /abc directory is ignored, except for ...".

https://raw.githubusercontent.com/git/git/master/Documentation/RelNotes/2.7.0.txt

edit: apparently this doesn't work any more since Git 2.8.0

while-else-loop

I don't see why there is a encapsulation of a while...

Use

//Use the appropriate start and end...
for(int rowIndex = 0, e = 65536; i < e; ++i){        
    if(rowIndex >= dataColLinker.size()) {
         dataColLinker.add(value);
     } else {
        dataColLinker.set(rowIndex, value);
     }    
}

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

Which UUID version to use?

Postgres documentation describes the differences between UUIDs. A couple of them:

V3:

uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

V4:

uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

Highlight a word with jQuery

Why using a selfmade highlighting function is a bad idea

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

Use an existing plugin

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.

Have a look at mark.js

mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms

DEMO

Alternatively you can see this fiddle.

Usage example:

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

It's free and developed open-source on GitHub (project reference).

How do you format an unsigned long long int using printf?

How do you format an unsigned long long int using printf?

Since C99 use an "ll" (ell-ell) before the conversion specifiers o,u,x,X.

In addition to base 10 options in many answers, there are base 16 and base 8 options:

Choices include

unsigned long long num = 285212672;
printf("Base 10: %llu\n", num);
num += 0xFFF; // For more interesting hex/octal output.
printf("Base 16: %llX\n", num); // Use uppercase A-F
printf("Base 16: %llx\n", num); // Use lowercase a-f
printf("Base  8: %llo\n", num);
puts("or 0x,0X prefix");
printf("Base 16: %#llX %#llX\n", num, 0ull); // When non-zero, print leading 0x
printf("Base 16: %#llx %#llx\n", num, 0ull);
printf("Base 16: 0x%llX\n", num); // My hex fave: lower case prefix, with A-F

Output

Base 10: 285212672
Base 16: 11000FFF
Base 16: 11000fff
Base  8: 2100007777
or 0x,0X prefix
Base 16: 0X11000FFF 0
Base 16: 0x11000fff 0
Base 16: 0x11000FFF

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

On Windows 7, I had this problem multiple times, each time with different error messages. Basically, the IDE is sending to the wrong port.

To fix this, simply go to menu ToolsPorts → [select the COM port that your board is on].

Make sure to double check your board's port:

  1. Start Device Manager

    Start Menu

  2. Make sure your Arduino driver is listed under the port matching your IDE's port settings (mentioned above)

    Device Manager

  3. My board is listed under port COM1. If you want, you can simply change the port in the driver's advanced settings:

    Enter image description here

How to list files using dos commands?

If you just want to get the file names and not directory names then use :

dir /b /a-d > file.txt

Why is my CSS bundling not working with a bin deployed MVC4 app?

I had the same problem and it turned out to be a stupid mistake, the css files were not included in the project so they weren't published, make sure you view all files in the solution and add them to the project.

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

In Excel 2010 it is easy, just takes a few more steps for each list items.

The following steps must be completed for each item within the validation list. (Have the worksheet open to where the drop down was created)

1) Click on cell with drop down list.
2) Select which answer to apply format to.
3) Click on "Home" tab, then click the "Styles" tool button on the ribbon.
4) Click "Conditional Formatting", in drop down list click the "*New Rule" option.
5) Select a Rule Type: "Format only cells that contain"
6) Edit the Rule Description: "Cell Value", "equal to", click the cell formula icon in the formula bar (far right), select which worksheet the validation list was created in, select the cell within the list to which you wish to apply the formatting.

Formula should look something like: ='Workbook Data'!$A$2

7) Click the formula icon again to return to format menu.
8) Click on Format button beside preview pane.
9) Select all format options desired.
10) Press "OK" twice.

You are finished with only one item within list. Repeat steps 1 thru 10 until all drop down list items are finished.

How to validate domain name in PHP?

If you can run shell commands, following is the best way to determine if a domain is registered.

This function returns false, if domain name isn't registered else returns domain name.

function get_domain_name($domain) { 
    //Step 1 - Return false if any shell sensitive chars or space/tab were found
    if(escapeshellcmd($domain)!=$domain || count(explode(".", $domain))<2 || preg_match("/[\s\t]/", $domain)) {
            return false;
    }

    //Step 2 - Get the root domain in-case of subdomain
    $domain = (count(explode(".", $domain))>2 ? strtolower(explode(".", $domain)[count(explode(".", $domain))-2].".".explode(".", $domain)[count(explode(".", $domain))-1]) : strtolower($domain));

    //Step 3 - Run shell command 'dig' to get SOA servers for the domain extension
    $ns = shell_exec(escapeshellcmd("dig +short SOA ".escapeshellarg(explode(".", $domain)[count(explode(".", $domain))-1]))); 

    //Step 4 - Return false if invalid extension (returns NULL), or take the first server address out of output
    if($ns===NULL) {
            return false;
    }
    $ns = (((preg_split('/\s+/', $ns)[0])[strlen(preg_split('/\s+/', $ns)[0])-1]==".") ? substr(preg_split('/\s+/', $ns)[0], 0, strlen(preg_split('/\s+/', $ns)[0])-1) : preg_split('/\s+/', $ns)[0]);

    //Step 5 - Run another dig using the obtained address for our domain, and return false if returned NULL else return the domain name. This assumes an authoritative NS is assigned when a domain is registered, can be improved to filter more accurately.
    $ans = shell_exec(escapeshellcmd("dig +noall +authority ".escapeshellarg("@".$ns)." ".escapeshellarg($domain))); 
    return (($ans===NULL) ? false : ((strpos($ans, $ns)>-1) ? false : $domain));
}

Pros

  1. Works on any domain, while php dns functions may fail on some domains. (my .pro domain failed on php dns)
  2. Works on fresh domains without any dns (like A) records
  3. Unicode friendly

Cons

  1. Usage of shell execution, probably

How to diff a commit with its parent?

If you know how far back, you can try something like:

# Current branch vs. parent
git diff HEAD^ HEAD

# Current branch, diff between commits 2 and 3 times back
git diff HEAD~3 HEAD~2

Prior commits work something like this:

# Parent of HEAD
git show HEAD^1

# Grandparent
git show HEAD^2

There are a lot of ways you can specify commits:

# Great grandparent
git show HEAD~3

See this page for details.

What's the difference between text/xml vs application/xml for webservice response

application/xml is seen by svn as binary type whereas text/xml as text file for which a diff can be displayed.

How to clear a textbox once a button is clicked in WPF?

I use this. I think this is the simpliest way to do it:

 textBoxName.Clear();

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

I know this is an older thread but I just bumped into this. If the user is trying to run inserts on the Identity column after some other session Set IDENTITY_INSERT ON, then he is bound to get the above error.

Setting the Identity Insert value and the subsequent Insert DML commands are to be run by the same session.

Here @Beginner was setting Identity Insert ON separately and then running the inserts from his application. That is why he got the below Error:

Cannot insert explicit value for identity column in table 'Baskets' when 
IDENTITY_INSERT is set to OFF.

Count number of rows matching a criteria

to get the number of observations the number of rows from your Dataset would be more valid:

nrow(dat[dat$sCode == "CA",])

How to run crontab job every week on Sunday

Following is the format of the crontab file.

{minute} {hour} {day-of-month} {month} {day-of-week} {user} {path-to-shell-script}

So, to run each sunday at midnight (Sunday is 0 usually, 7 in some rare cases) :

0 0 * * 0 root /path_to_command

How to update SQLAlchemy row entry?

I wrote telegram bot, and have some problem with update rows. Use this example, if you have Model

def update_state(chat_id, state):
    try:
        value = Users.query.filter(Users.chat_id == str(chat_id)).first()
        value.state = str(state)
        db.session.flush()
        db.session.commit()
        #db.session.close()
    except:
        print('Error in def update_state')

Why use db.session.flush()? That's why >>> SQLAlchemy: What's the difference between flush() and commit()?

How can I get a value from a map?

map.at("key") throws exception if missing key

If k does not match the key of any element in the container, the function throws an out_of_range exception.

http://www.cplusplus.com/reference/map/map/at/

How to generate UML diagrams (especially sequence diagrams) from Java code?

I suggest PlantUML. this tools is very usefull and easy to use. PlantUML have a plugin for Netbeans that you can create UML diagram from your java code.

you can install PlantUML plugin in the netbeans by this method:

Netbeans Menu -> Tools -> Plugin

Now select Available Plugins and then find PlantUML and install it.

For more information go to website: www.plantuml.com

System.web.mvc missing

Add the reference again from ./packages/Microsoft.AspNet.Mvc.[version]/lib/net45/System.Web.Mvc.dll

How to remove all white spaces in java

Try:

  string output = YourString.replaceAll("\\s","")

s - indicates space character (tab characters etc)

Byte Array in Python

Dietrich's answer is probably just the thing you need for what you describe, sending bytes, but a closer analogue to the code you've provided for example would be using the bytearray type.

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>> 

Which command in VBA can count the number of characters in a string variable?

Do you mean counting the number of characters in a string? That's very simple

Dim strWord As String
Dim lngNumberOfCharacters as Long

strWord = "habit"
lngNumberOfCharacters = Len(strWord)
Debug.Print lngNumberOfCharacters

How to test REST API using Chrome's extension "Advanced Rest Client"

From the screenshot I can see that you want to pass "user" and "password" values to the service. You have send the parameter values in the request header part which is wrong. The values are sent in the request body and not in the request header. Also your syntax is wrong. Correct syntax is: {"user":"user_val","password":"password_val"}. Also check what is the the content type. It should match with the content type you have set to your service.

How to remove a file from the index in git?

Only use git rm --cached [file] to remove a file from the index.

git reset <filename> can be used to remove added files from the index given the files are never committed.

% git add First.txt
% git ls-files
First.txt
% git commit -m "First"   
% git ls-files            
First.txt
% git reset First.txt
% git ls-files              
First.txt

NOTE: git reset First.txt has no effect on index after the commit.

Which brings me to the topic of git restore --staged <file>. It can be used to (presumably after the first commit) remove added files from the index given the files are never committed.

% git add Second.txt              
% git status        
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
    new file:   Second.txt
% git ls-files       
First.txt
Second.txt
% git restore --staged Second.txt
% git ls-files 
First.txt
% git add Second.txt 
% git commit -m "Second"
% git status            
On branch master
nothing to commit, working tree clean
% git ls-files 
First.txt         
Second.txt
Desktop/Test% git restore --staged .
Desktop/Test% git ls-files
First.txt                   
Second.txt
Desktop/Test% git reset .                    
Desktop/Test% git ls-files
First.txt
Second.txt
% git rm --cached -r .
rm 'First.txt'
rm 'Second.txt'
% git ls-files  

tl;dr Look at last 15 lines. If you don't want to be confused with first commit, second commit, before commit, after commit.... always use git rm --cached [file]

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

VBA subs are no macros. A VBA sub can be a macro, but it is not a must.

The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.

The more elegant way is, to design and write your own VBA code without using the macro features!

VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.

If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".

In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.

It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.

In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.

Matching strings with wildcard

Just FYI, you could use the VB.NET Like-Operator:

string text = "x is not the same as X and yz not the same as YZ";
bool contains = LikeOperator.LikeString(text,"*X*YZ*", Microsoft.VisualBasic.CompareMethod.Binary);  

Use CompareMethod.Text if you want to ignore the case.

You need to add using Microsoft.VisualBasic.CompilerServices;.

Android EditText delete(backspace) key event

It's been a while since you asked but I just had the same issue. As already mentioned by Estel the problem with key listeners is that they only work with hardware keyboards. To do this with an IME (soft keyboard), the solution is a bit more elaborate.

The single method we actually want to override is sendKeyEvent in the EditText's InputConnection class. This method is called when key events occur in an IME. But in order to override this, we need to implement a custom EditText which overrides the onCreateInputConnection method, wrapping the default InputConnection object in a proxy class! :|

Sounds complicated, but here's the simplest example I could contrive:

public class ZanyEditText extends EditText {

    private Random r = new Random();

    public ZanyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ZanyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ZanyEditText(Context context) {
        super(context);
    }

    public void setRandomBackgroundColor() {
        setBackgroundColor(Color.rgb(r.nextInt(256), r.nextInt(256), r
                .nextInt(256)));
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new ZanyInputConnection(super.onCreateInputConnection(outAttrs),
                true);
    }

    private class ZanyInputConnection extends InputConnectionWrapper {

        public ZanyInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
        }

        @Override
        public boolean sendKeyEvent(KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                ZanyEditText.this.setRandomBackgroundColor();
                // Un-comment if you wish to cancel the backspace:
                // return false;
            }
            return super.sendKeyEvent(event);
        }

    }

}

The line with the call to setRandomBackgroundColor is where my special backspace action occurs. In this case, changing the EditText's background colour.

If you're inflating this from XML remember to use the full package name as the tag:

<cc.buttfu.test.ZanyEditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/somefield"
></cc.buttfu.test.ZanyEditText>

How to open a new HTML page using jQuery?

Use window.open("file2.html");

Syntax

var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);

Return value and parameters

windowObjectReference 

A reference to the newly created window. If the call failed, it will be null. The reference can be used to access properties and methods of the new window provided it complies with Same origin policy security requirements.

strUrl 

The URL to be loaded in the newly opened window. strUrl can be an HTML document on the web, image file or any resource supported by the browser.

strWindowName 

A string name for the new window. The name can be used as the target of links and forms using the target attribute of an <a> or <form> element. The name should not contain any blank space. Note that strWindowName does not specify the title of the new window.

strWindowFeatures 

Optional parameter listing the features (size, position, scrollbars, etc.) of the new window. The string must not contain any blank space, each feature name and value must be separated by a comma.

How to make a radio button look like a toggle button

I know this is an old question, but since I was just looking to do this, I thought I would post what I ended up with. Because I am using Bootstrap, I went with a Bootstrap option.

HTML

<div class="col-xs-12">
    <div class="form-group">
        <asp:HiddenField ID="hidType" runat="server" />
        <div class="btn-group" role="group" aria-label="Selection type" id="divType">
            <button type="button" class="btn btn-default BtnType" data-value="1">Food</button>                        
            <button type="button" class="btn btn-default BtnType" data-value="2">Drink</button>
        </div>
    </div>
</div>

jQuery

$(document).ready(function () {
    $('#divType button').click(function () {
        $(this).addClass('active').siblings().removeClass('active');
        $('#<%= hidType.ClientID%>').val($(this).data('value'));
        //alert($(this).data('value'));             
    });
});

I chose to store the value in a hidden field so that it would be easy for me to get the value server-side.

Using variables in Nginx location rules

You could do the opposite of what you proposed.

location (/test)/ {
   set $folder $1;
}

location (/test_/something {
   set $folder $1;
}

YouTube Autoplay not working

mute=1 or muted=1 as suggested by @Fab will work. However, if you wish to enable autoplay with sound you should add allow="autoplay" to your embedded <iframe>.

<iframe type="text/html" src="https://www.youtube.com/embed/-ePDPGXkvlw?autoplay=1" frameborder="0" allow="autoplay"></iframe>

This is officially supported and documented in Google's Autoplay Policy Changes 2017 post

Iframe delegation A feature policy allows developers to selectively enable and disable use of various browser features and APIs. Once an origin has received autoplay permission, it can delegate that permission to cross-origin iframes with a new feature policy for autoplay. Note that autoplay is allowed by default on same-origin iframes.

<!-- Autoplay is allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay">

<!-- Autoplay and Fullscreen are allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay; fullscreen">

When the feature policy for autoplay is disabled, calls to play() without a user gesture will reject the promise with a NotAllowedError DOMException. And the autoplay attribute will also be ignored.

String is immutable. What exactly is the meaning?

An immutable object is an object whose state cannot be modified after it is created.

So a = "ABC" <-- immutable object. "a" holds reference to the object. And, a = "DEF" <-- another immutable object, "a" holds reference to it now.

Once you assign a string object, that object can not be changed in memory.

In summary, what you did is to change the reference of "a" to a new string object.

Web.Config Debug/Release

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

How do I escape ampersands in batch files?

& is used to separate commands. Therefore you can use ^ to escape the &.

How to generate random float number in C

Try:

float x = (float)rand()/(float)(RAND_MAX/a);

To understand how this works consider the following.

N = a random value in [0..RAND_MAX] inclusively.

The above equation (removing the casts for clarity) becomes:

N/(RAND_MAX/a)

But division by a fraction is the equivalent to multiplying by said fraction's reciprocal, so this is equivalent to:

N * (a/RAND_MAX)

which can be rewritten as:

a * (N/RAND_MAX)

Considering N/RAND_MAX is always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 and a.

Alternatively, you can use the following, which effectively does the breakdown I showed above. I actually prefer this simply because it is clearer what is actually going on (to me, anyway):

float x = ((float)rand()/(float)(RAND_MAX)) * a;

Note: the floating point representation of a must be exact or this will never hit your absolute edge case of a (it will get close). See this article for the gritty details about why.

Sample

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[])
{
    srand((unsigned int)time(NULL));

    float a = 5.0;
    for (int i=0;i<20;i++)
        printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
    return 0;
}

Output

1.625741
3.832026
4.853078
0.687247
0.568085
2.810053
3.561830
3.674827
2.814782
3.047727
3.154944
0.141873
4.464814
0.124696
0.766487
2.349450
2.201889
2.148071
2.624953
2.578719

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

For people who find this old posting on the web by searching for the error message, there is another possible cause of the problem.

You could just have a typo in your call to the script, even if you have already done the things described in the other excellent answer. So check to make sure you can used the right spelling in your script tags.

Deleting an object in java?

Yea, java is Garbage collected, it will delete the memory for you.

How to format a Java string with leading zero?

Using Guava's Strings utility class:

Strings.padStart("Apple", 8, '0');

Adding ID's to google map markers

I have a simple Location class that I use to handle all of my marker-related things. I'll paste my code below for you to take a gander at.

The last line(s) is what actually creates the marker objects. It loops through some JSON of my locations, which look something like this:

{"locationID":"98","name":"Bergqvist Järn","note":null,"type":"retail","address":"Smidesvägen 3","zipcode":"69633","city":"Askersund","country":"Sverige","phone":"0583-120 35","fax":null,"email":null,"url":"www.bergqvist-jb.com","lat":"58.891079","lng":"14.917371","contact":null,"rating":"0","distance":"45.666885421019"}

Here is the code:

If you look at the target() method in my Location class, you'll see that I keep references to the infowindow's and can simply open() and close() them because of a reference.

See a live demo: http://ww1.arbesko.com/en/locator/ (type in a Swedish city, like stockholm, and hit enter)

var Location = function() {
    var self = this,
        args = arguments;

    self.init.apply(self, args);
};

Location.prototype = {
    init: function(location, map) {
        var self = this;

        for (f in location) { self[f] = location[f]; }

        self.map = map;
        self.id = self.locationID;

        var ratings = ['bronze', 'silver', 'gold'],
            random = Math.floor(3*Math.random());

        self.rating_class = 'blue';

        // this is the marker point
        self.point = new google.maps.LatLng(parseFloat(self.lat), parseFloat(self.lng));
        locator.bounds.extend(self.point);

        // Create the marker for placement on the map
        self.marker = new google.maps.Marker({
            position: self.point,
            title: self.name,
            icon: new google.maps.MarkerImage('/wp-content/themes/arbesko/img/locator/'+self.rating_class+'SmallMarker.png'),
            shadow: new google.maps.MarkerImage(
                                        '/wp-content/themes/arbesko/img/locator/smallMarkerShadow.png',
                                        new google.maps.Size(52, 18),
                                        new google.maps.Point(0, 0),
                                        new google.maps.Point(19, 14)
                                    )
        });

        google.maps.event.addListener(self.marker, 'click', function() {
            self.target('map');
        });

        google.maps.event.addListener(self.marker, 'mouseover', function() {
            self.sidebarItem().mouseover();
        });

        google.maps.event.addListener(self.marker, 'mouseout', function() {
            self.sidebarItem().mouseout();
        });

        var infocontent = Array(
            '<div class="locationInfo">',
                '<span class="locName br">'+self.name+'</span>',
                '<span class="locAddress br">',
                    self.address+'<br/>'+self.zipcode+' '+self.city+' '+self.country,
                '</span>',
                '<span class="locContact br">'
        );

        if (self.phone) {
            infocontent.push('<span class="item br locPhone">'+self.phone+'</span>');
        }

        if (self.url) {
            infocontent.push('<span class="item br locURL"><a href="http://'+self.url+'">'+self.url+'</a></span>');
        }

        if (self.email) {
            infocontent.push('<span class="item br locEmail"><a href="mailto:'+self.email+'">Email</a></span>');
        }

        // Add in the lat/long
        infocontent.push('</span>');

        infocontent.push('<span class="item br locPosition"><strong>Lat:</strong> '+self.lat+'<br/><strong>Lng:</strong> '+self.lng+'</span>');

        // Create the infowindow for placement on the map, when a marker is clicked
        self.infowindow = new google.maps.InfoWindow({
            content: infocontent.join(""),
            position: self.point,
            pixelOffset: new google.maps.Size(0, -15) // Offset the infowindow by 15px to the top
        });

    },

    // Append the marker to the map
    addToMap: function() {
        var self = this;

        self.marker.setMap(self.map);
    },

    // Creates a sidebar module for the item, connected to the marker, etc..
    sidebarItem: function() {
        var self = this;

        if (self.sidebar) {
            return self.sidebar;
        }

        var li = $('<li/>').attr({ 'class': 'location', 'id': 'location-'+self.id }),
            name = $('<span/>').attr('class', 'locationName').html(self.name).appendTo(li),
            address = $('<span/>').attr('class', 'locationAddress').html(self.address+' <br/> '+self.zipcode+' '+self.city+' '+self.country).appendTo(li);

        li.addClass(self.rating_class);

        li.bind('click', function(event) {
            self.target();
        });

        self.sidebar = li;

        return li;
    },

    // This will "target" the store. Center the map and zoom on it, as well as 
    target: function(type) {
        var self = this;

        if (locator.targeted) {
            locator.targeted.infowindow.close();
        }

        locator.targeted = this;

        if (type != 'map') {
            self.map.panTo(self.point);
            self.map.setZoom(14);
        };

        // Open the infowinfow
        self.infowindow.open(self.map);
    }
};

for (var i=0; i < locations.length; i++) {
    var location = new Location(locations[i], self.map);
    self.locations.push(location);

    // Add the sidebar item
    self.location_ul.append(location.sidebarItem());

    // Add the map!
    location.addToMap();
};

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Submit two forms with one button

If you have a regular submit button, you could add an onclick event to it that does the follow:

document.getElementById('otherForm').submit();

How do I import .sql files into SQLite 3?

Use sqlite3 database.sqlite3 < db.sql. You'll need to make sure that your files contain valid SQL for SQLite.

How to allow download of .json file with ASP.NET

When adding support for mimetype (as suggested by @ProVega) then it is also best practice to remove the type before adding it - this is to prevent unexpected errors when deploying to servers where support for the type already exists, for example:

<staticContent>
    <remove fileExtension=".json" />
    <mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>

What is __init__.py for?

It facilitates importing other python files. When you placed this file in a directory (say stuff)containing other py files, then you can do something like import stuff.other.

root\
    stuff\
         other.py

    morestuff\
         another.py

Without this __init__.py inside the directory stuff, you couldn't import other.py, because Python doesn't know where the source code for stuff is and unable to recognize it as a package.

How to display div after click the button in Javascript?

<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>

<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>

<div id="toggle" style="display:none">Hello</div>

How to create an array of 20 random bytes?

If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom.

Java 6 & 7:

SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

Java 8 (even more secure):

byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);

What does "./" (dot slash) refer to in terms of an HTML file path location?

You can use the following list as quick reference:

   /   = Root directory
   .   = This location
   ..  = Up a directory
   ./  = Current directory
   ../ = Parent of current directory
   ../../ = Two directories backwards

Useful article: https://css-tricks.com/quick-reminder-about-file-paths/

Eclipse: Enable autocomplete / content assist

I am not sure if this has to be explicitly enabled anywhere..but for this to work in the first place you need to include the javadoc jar files with the related jars in your project. Then when you do a Cntrl+Space it shows autocomplete and javadocs.

Bootstrap change div order with pull-right, pull-left on 3 columns

Try this...

<div class="row">
    <div class="col-xs-3">
        Menu
    </div>
    <div class="col-xs-9">
        <div class="row">
          <div class="col-sm-4 col-sm-push-8">
          Right content
          </div>
          <div class="col-sm-8 col-sm-pull-4">
          Content
          </div>
       </div>
    </div>
</div>

Bootply

EOFError: end of file reached issue with Net::HTTP

If the URL is using https instead of http, you need to add the following line:

parsed_url = URI.parse(url)
http = Net::HTTP.new(parsed_url.host, parsed_url.port)
http.use_ssl = true

Note the additional http.use_ssl = true.

And the more appropriate code which would handle both http and https will be similar to the following one.

url = URI.parse(domain)
req = Net::HTTP::Post.new(url.request_uri)
req.set_form_data({'name'=>'Sur Max', 'email'=>'[email protected]'})
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")
response = http.request(req)

See more in my blog: EOFError: end of file reached issue when post a form with Net::HTTP.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

As you can see here:

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Difference between @GetMapping & @RequestMapping

@GetMapping supports the consumes attribute like @RequestMapping.

How do I check that a Java String is not all whitespaces?

Slightly shorter than what was mentioned by Carl Smotricz:

!string.trim().isEmpty();

How to parse JSON array in jQuery?

I know this is pretty long after your post, but wanted to post for others who might be experiencing this issue and stumble across this post as I did.

It seems there's something about jquery's $.each that changes the nature of the elements in the array.

I wanted to do the following:

$.getJSON('/ajax/get_messages.php', function(data) {

    /* data: 

    [{"title":"Failure","details":"Unsuccessful. Please try again.","type":"error"},
    {"title":"Information Message","details":"A basic informational message - Please be aware","type":"info"}]

    */

    console.log ("Data0Title: " + data[0].title);
    // prints "Data0Title: Failure"

    console.log ("Data0Type: " + data[0].type);
    // prints "Data0Type: error"

    console.log ("Data0Details: " + data[0].details);
    // prints "Data0Details: Unsuccessful. Please try again"


    /* Loop through data array and print messages to console */

});

To accomplish the loop, I first tried using a jquery $.each to loop through the data array. However, as the OP notes, this doesn't work right:

$.each(data, function(nextMsg) {    
    console.log (nextMsg.title + " (" + nextMsg.type + "): " + nextMsg.details);
    // prints 
    // "undefined (undefined): undefined
    // "undefined (undefined): undefined
});

This didn't exactly make sense since I am able to access the data[0] elements when using a numeric key on the data array. So since using a numerical index worked, I tried (successfully) replacing the $.each block with a for loop:

var i=0;
for (i=0;i<data.length;i++){
    console.log (data[i].title + " (" + data[i].type + "): " + data[i].details);
    // prints
    // "Failure (error): Unsuccessful. Please try again"
    // "Information Message (info): A basic informational message - Please be aware"
}

So I don't know the underlying problem, a basic, old fashioned javascript for loop seems to be a functional alternative to jquery's $.each

PostgreSQL JOIN data from 3 tables

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id

LINQ Using Max() to select a single row

I don't see why you are grouping here.

Try this:

var maxValue = table.Max(x => x.Status)
var result = table.First(x => x.Status == maxValue);

An alternate approach that would iterate table only once would be this:

var result = table.OrderByDescending(x => x.Status).First();

This is helpful if table is an IEnumerable<T> that is not present in memory or that is calculated on the fly.

Always show vertical scrollbar in <select>

add:

overflow-y: scroll

in your css bud.

How to Convert datetime value to yyyymmddhhmmss in SQL server?

FORMAT() is slower than CONVERT(). This answer is slightly better than @jpx's answer because it only does a replace on the time part of the date.

112 = yyyymmdd - no format change needed

108 = hh:mm:ss - remove :

SELECT CONVERT(VARCHAR, GETDATE(), 112) + 
       REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '')

Android Studio suddenly cannot resolve symbols

Android Studio 1.3

  1. Open Module Settings
  2. Click on your module under Modules menu
  3. In the properties tab, set the Source Compatibility and Target Compatibility to your java version.

I did nothing else and it worked for me.

How can I access an internal class from an external assembly?

I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)] to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.

 Install-Package Mono.Cecil

And the code like:

static readonly string[] s_toInject = {
  // alternatively "MyAssembly, PublicKey=0024000004800000... etc."
  "MyAssembly"
};

static void Main(string[] args) {
  const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";

   var parameters = new ReaderParameters();
   var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
   foreach (var toInject in s_toInject) {
     var ca = new CustomAttribute(
       asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
                      typeof(string)})));
     ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
     asm.Assembly.CustomAttributes.Add(ca);
   }
   asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
   // note if the assembly is strongly-signed you need to resign it like
   // asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
   //   StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
   // });
}

How to select first child with jQuery?

As @Roko mentioned you can do this in multiple ways.

1.Using the jQuery first-child selector - SnoopCode

   $(document).ready(function(){
    $(".alldivs onediv:first-child").css("background-color","yellow");
        }
  1. Using jQuery eq Selector - SnoopCode

     $( "body" ).find( "onediv" ).eq(1).addClass( "red" );
    
  2. Using jQuery Id Selector - SnoopCode

       $(document).ready(function(){
         $("#div1").css("background-color: red;");
       });
    

ASP.NET MVC3 Razor - Html.ActionLink style

Here's the signature.

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

What you are doing is mixing the values and the htmlAttributes together. values are for URL routing.

You might want to do this.

@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null, 
     new { @style="text-transform:capitalize;" });

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

How to use jQuery to select a dropdown option?

Use the following code if you want to select an option with a specific value:

$('select>option[value="' + value + '"]').prop('selected', true);

How to get the innerHTML of selectable jquery element?

The parameter ui has a property called selected which is a reference to the selected dom element, you can call innerHTML on that element.

Your code $('.ui-selected').innerHTML tries to return the innerHTML property of a jQuery wrapper element for a dom element with class ui-selected

$(function () {
    $("#select-image").selectable({
        selected: function (event, ui) {
            var $variable = ui.selected.innerHTML; // or $(ui.selected).html()
            console.log($variable);
        }
    });
});

Demo: Fiddle

git diff between cloned and original remote repository

Another reply to your questions (assuming you are on master and already did "git fetch origin" to make you repo aware about remote changes):

1) Commits on remote branch since when local branch was created:

git diff HEAD...origin/master

2) I assume by "working copy" you mean your local branch with some local commits that are not yet on remote. To see the differences of what you have on your local branch but that does not exist on remote branch run:

git diff origin/master...HEAD

3) See the answer by dbyrne.

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

Postgres "psql not recognized as an internal or external command"

Enter this path in your System environment variable.

C:\Program Files\PostgreSQL\[YOUR PG VERSION]\bin

In this case i'm using version 10. If you check the postgres folder you are going to see your current versions.

In my own case i used the following on separate lines:

C:\Program Files\PostgreSQL\10\bin
C:\Program Files\PostgreSQL\10\lib

What is /dev/null 2>&1?

I use >> /dev/null 2>&1 for a silent cronjob. A cronjob will do the job, but not send a report to my email.

As far as I know, don't remove /dev/null. It's useful, especially when you run cPanel, it can be used for throw-away cronjob reports.

Combining paste() and expression() functions in plot labels

EDIT: added a new example for ggplot2 at the end

See ?plotmath for the different mathematical operations in R

You should be able to use expression without paste. If you use the tilda (~) symbol within the expression function it will assume there is a space between the characters, or you could use the * symbol and it won't put a space between the arguments

Sometimes you will need to change the margins in you're putting superscripts on the y-axis.

par(mar=c(5, 4.3, 4, 2) + 0.1)
plot(1:10, xlab = expression(xLab ~ x^2 ~ m^-2),
     ylab = expression(yLab ~ y^2 ~ m^-2),
     main="Plot 1")

enter image description here

plot(1:10, xlab = expression(xLab * x^2 * m^-2),
     ylab = expression(yLab * y^2 * m^-2),
     main="Plot 2")

enter image description here

plot(1:10, xlab = expression(xLab ~ x^2 * m^-2),
     ylab = expression(yLab ~ y^2 * m^-2),
     main="Plot 3")

enter image description here

Hopefully you can see the differences between plots 1, 2 and 3 with the different uses of the ~ and * symbols. An extra note, you can use other symbols such as plotting the degree symbol for temperatures for or mu, phi. If you want to add a subscript use the square brackets.

plot(1:10, xlab = expression('Your x label' ~ mu[3] * phi),
     ylab = expression("Temperature (" * degree * C *")"))

enter image description here

Here is a ggplot example using expression with a nonsense example

require(ggplot2)

Or if you have the pacman library installed you can use p_load to automatically download and load and attach add-on packages

# require(pacman)
# p_load(ggplot2)

data = data.frame(x = 1:10, y = 1:10)

ggplot(data, aes(x,y)) + geom_point() + 
  xlab(expression(bar(yourUnits) ~ g ~ m^-2 ~ OR ~ integral(f(x)*dx, a,b))) + 
  ylab(expression("Biomass (g per" ~ m^3 *")")) + theme_bw()

enter image description here

How to copy to clipboard using Access/VBA?

VB 6 provides a Clipboard object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.

If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.

However, a simpler alternative is to use the DataObject class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.

For example, to place some text on the clipboard, you could use the following code:

Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"
clipboard.PutInClipboard

Or, to copy text from the clipboard into a string variable:

Dim clipboard As MSForms.DataObject
Dim strContents As String

Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText

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

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

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

My case is related to Greg B's -- Visual Studio creates two sites when SSL is enabled -- one for secure, and one for normal http requests. However Visual Studio chooses two ports at random, and depending on how you start the debugger you might be pointing towards the wrong page for the request type. Especially if you edit the URL but don't change the port number.

Seeing these posts jogged my memory.

I know this isn't APACHE related, but it is definitely a page that people with that error will find..

How to handle back button in activity

You can handle it like this:

for API level 5 and greater

@Override
public void onBackPressed() {
    // your code.
}

older than API 5

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // your code
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

How can I remove an element from a list, with lodash?

You can now use _.reject which allows you to filter based on what you need to get rid of, instead of what you need to keep.

unlike _.pull or _.remove that only work on arrays, ._reject is working on any Collection

obj.subTopics = _.reject(obj.subTopics, (o) => {
  return o.number >= 32;
});

How can I count the number of children?

You don't need jQuery for this. You can use JavaScript's .childNodes.length.

Just make sure to subtract 1 if you don't want to include the default text node (which is empty by default). Thus, you'd use the following:

var count = elem.childNodes.length - 1;

Xcode build failure "Undefined symbols for architecture x86_64"

In my case, I built a custom framework with Deployment target set to 9.1, but the Deployment target of my app was lower, which supports 8.1. Minimize the custom framework Deployment target solved my problem.

C/C++ check if one bit is set in, i.e. int variable

While it is quite late to answer now, there is a simple way one could find if Nth bit is set or not, simply using POWER and MODULUS mathematical operators.

Let us say we want to know if 'temp' has Nth bit set or not. The following boolean expression will give true if bit is set, 0 otherwise.

  • ( temp MODULUS 2^N+1 >= 2^N )

Consider the following example:

  • int temp = 0x5E; // in binary 0b1011110 // BIT 0 is LSB

If I want to know if 3rd bit is set or not, I get

  • (94 MODULUS 16) = 14 > 2^3

So expression returns true, indicating 3rd bit is set.

How to add multiple columns to pandas dataframe in one assignment?

I am not comfortable using "Index" and so on...could come up as below

df.columns
Index(['A123', 'B123'], dtype='object')

df=pd.concat([df,pd.DataFrame(columns=list('CDE'))])

df.rename(columns={
    'C':'C123',
    'D':'D123',
    'E':'E123'
},inplace=True)


df.columns
Index(['A123', 'B123', 'C123', 'D123', 'E123'], dtype='object')

How to download the latest artifact from Artifactory repository?

You could also use Artifactory Query Language to get the latest artifact.

The following shell script is just an example. It uses 'items.find()' (which is available in the non-Pro version), e.g. items.find({ "repo": {"$eq":"my-repo"}, "name": {"$match" : "my-file*"}}) that searches for files that have a repository name equal to "my-repo" and match all files that start with "my-file". Then it uses the shell JSON parser ./jq to extract the latest file by sorting by the date field 'updated'. Finally it uses wget to download the artifact.

#!/bin/bash

# Artifactory settings
host="127.0.0.1"
username="downloader"
password="my-artifactory-token"

# Use Artifactory Query Language to get the latest scraper script (https://www.jfrog.com/confluence/display/RTF/Artifactory+Query+Language)
resultAsJson=$(curl -u$username:"$password" -X POST  http://$host/artifactory/api/search/aql -H "content-type: text/plain" -d 'items.find({ "repo": {"$eq":"my-repo"}, "name": {"$match" : "my-file*"}})')

# Use ./jq to pars JSON
latestFile=$(echo $resultAsJson | jq -r '.results | sort_by(.updated) [-1].name')

# Download the latest scraper script
wget -N -P ./libs/ --user $username --password $password http://$host/artifactory/my-repo/$latestFile

How to define hash tables in Bash?

Two things, you can use memory instead of /tmp in any kernel 2.6 by using /dev/shm (Redhat) other distros may vary. Also hget can be reimplemented using read as follows:

function hget {

  while read key idx
  do
    if [ $key = $2 ]
    then
      echo $idx
      return
    fi
  done < /dev/shm/hashmap.$1
}

In addition by assuming that all keys are unique, the return short circuits the read loop and prevents having to read through all entries. If your implementation can have duplicate keys, then simply leave out the return. This saves the expense of reading and forking both grep and awk. Using /dev/shm for both implementations yielded the following using time hget on a 3 entry hash searching for the last entry :

Grep/Awk:

hget() {
    grep "^$2 " /dev/shm/hashmap.$1 | awk '{ print $2 };'
}

$ time echo $(hget FD oracle)
3

real    0m0.011s
user    0m0.002s
sys     0m0.013s

Read/echo:

$ time echo $(hget FD oracle)
3

real    0m0.004s
user    0m0.000s
sys     0m0.004s

on multiple invocations I never saw less then a 50% improvement. This can all be attributed to fork over head, due to the use of /dev/shm.

CURL and HTTPS, "Cannot resolve host"

add yourlocalhost
ex. 127.0.0.1 cards.localhost in the /etc/hosts directory. Now restart apache server

How to sort by Date with DataTables jquery plugin?

Click on the "show details" link under Date (dd/mm/YYY), then you can copy and paste that plugin code provided there


Update: I think you can just switch the order of the array, like so:

jQuery.fn.dataTableExt.oSort['us_date-asc']  = function(a,b) {
    var usDatea = a.split('/');
    var usDateb = b.split('/');

    var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
    var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;

    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
    var usDatea = a.split('/');
    var usDateb = b.split('/');

    var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
    var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;

    return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
};

All I did was switch the __date_[1] (day) and __date_[0] (month), and replaced uk with us so you won't get confused. I think that should take care of it for you.


Update #2: You should be able to just use the date object for comparison. Try this:

jQuery.fn.dataTableExt.oSort['us_date-asc']  = function(a,b) {
 var x = new Date(a),
     y = new Date(b);
 return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
 var x = new Date(a),
     y = new Date(b);
 return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
};

Browse and display files in a git repo without cloning

Take a look at http://git-scm.com/book/en/Git-Internals-Transfer-Protocols for info on how to do this over some transport protocols. Note this won't work for standard git over SSH.

For git over SSH, an up-to-date server-side git should allow you to git-archive directly from the remote, which you could then e.g. pipe to "tar t" to get a list of all files in a given commit.

Trigger Change event when the Input value changed programmatically?

You are using jQuery, right? Separate JavaScript from HTML.

You can use trigger or triggerHandler.

var $myInput = $('#changeProgramatic').on('change', ChangeValue);

var anotherFunction = function() {
  $myInput.val('Another value');
  $myInput.trigger('change');
};

JavaScript: IIF like statement

Something like this:

for (/* stuff */)
{
    var x = '<option value="' + col + '" '
        + (col === 'screwdriver' ? 'selected' : '')
        + '>Very roomy</option>';
    // snip...
}

Converting map to struct

The simplest way would be to use https://github.com/mitchellh/mapstructure

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

If you want to do it yourself, you could do something like this:

http://play.golang.org/p/tN8mxT_V9h

func SetField(obj interface{}, name string, value interface{}) error {
    structValue := reflect.ValueOf(obj).Elem()
    structFieldValue := structValue.FieldByName(name)

    if !structFieldValue.IsValid() {
        return fmt.Errorf("No such field: %s in obj", name)
    }

    if !structFieldValue.CanSet() {
        return fmt.Errorf("Cannot set %s field value", name)
    }

    structFieldType := structFieldValue.Type()
    val := reflect.ValueOf(value)
    if structFieldType != val.Type() {
        return errors.New("Provided value type didn't match obj field type")
    }

    structFieldValue.Set(val)
    return nil
}

type MyStruct struct {
    Name string
    Age  int64
}

func (s *MyStruct) FillStruct(m map[string]interface{}) error {
    for k, v := range m {
        err := SetField(s, k, v)
        if err != nil {
            return err
        }
    }
    return nil
}

func main() {
    myData := make(map[string]interface{})
    myData["Name"] = "Tony"
    myData["Age"] = int64(23)

    result := &MyStruct{}
    err := result.FillStruct(myData)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(result)
}

ASP.NET: Session.SessionID changes between requests

There is another, more insidious reason, why this may occur even when the Session object has been initialized as demonstrated by Cladudio.

In the Web.config, if there is an <httpCookies> entry that is set to requireSSL="true" but you are not actually using HTTPS: for a specific request, then the session cookie is not sent (or maybe not returned, I'm not sure which) which means that you end up with a brand new session for each request.

I found this one the hard way, spending several hours going back and forth between several commits in my source control, until I found what specific change had broken my application.

get path for my .exe

In a Windows Forms project:

For the full path (filename included): string exePath = Application.ExecutablePath;
For the path only: string appPath = Application.StartupPath;

Turning off hibernate logging console output

There are several parts of hibernate logging you can control based on the logger hierarchy of the hibernate package (more on logger hierarchy here).

    <!-- Log everything in hibernate -->
    <Logger name="org.hibernate" level="info" additivity="false">
      <AppenderRef ref="Console" />
    </Logger>

    <!-- Log SQL statements -->
    <Logger name="org.hibernate.SQL" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

    <!-- Log JDBC bind parameters -->
    <Logger name="org.hibernate.type.descriptor.sql" level="trace" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

The above was taken from here.

Additionally you could have the property show-sql:true in your configuration file since that supersedes the logging framework settings. More on that here.

If Radio Button is selected, perform validation on Checkboxes

Full validation example with javascript:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Radio button: full validation example with javascript</title>
        <script>
            function send() {
                var genders = document.getElementsByName("gender");
                if (genders[0].checked == true) {
                    alert("Your gender is male");
                } else if (genders[1].checked == true) {
                    alert("Your gender is female");
                } else {
                    // no checked
                    var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
                    document.getElementById('msg').innerHTML = msg;
                    return false;
                }
                return true;
            }

            function reset_msg() {
                document.getElementById('msg').innerHTML = '';
            }
        </script>
    </head>
    <body>
        <form action="" method="POST">
            <label>Gender:</label>
            <br />
            <input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
            <br />
            <input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
            <br />
            <div id="msg"></div>
            <input type="submit" value="send>>" onclick="return send();" />
        </form>
    </body>
</html>

Regards,

Fernando

In AVD emulator how to see sdcard folder? and Install apk to AVD?

  1. switch to DDMS perspective
  2. select the emulator in devices list, whose sdcard you want to explore.
  3. open File Explorer tab on right hand side.
  4. expand tree structure. mnt/sdcard/

refer to image belowenter image description here


To install apk manually: copy your apk to to sdk/platform-tools folder and run following command in the same folder

adb install apklocation.apk

Increment value in mysql update query

Who needs to update string and numbers SET @a = 0; UPDATE obj_disposition SET CODE = CONCAT('CD_', @a:=@a+1);

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

Just in case anyone will search for it - I used it on several sites, always the customization and RD possibilities were a perfect fit for what I needed. Simple and it is free to use:

Clickable CSS Maps

One note for more scripts on a site: I had some annoying problems with getting to work a map (that worked as a graphic menu) in Drupal 7. There where many other script used, and after handling them, I got stuck with the map - it still didn't work, although the jquery.cssmap.js, CSS (both local) and the script in the where in the right place. Firebug showed me an error and I suddenly eureka - a simple oversight, I left the script code as it was in the example and there was a conflict. Just change the front function "$" to "jQuery" (or other handler) and it works perfect. :]

Here's what I ment (of course you can put it before instead of the ):

_x000D_
_x000D_
<script type="text/javascript">_x000D_
      jQuery(function($){_x000D_
        $('#map-country').cssMap({'size' : 810});_x000D_
       });_x000D_
    </script>
_x000D_
_x000D_
_x000D_

String comparison using '==' vs. 'strcmp()'

Don't use == in PHP. It will not do what you expect. Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical.

For example '1e3' == '1000' returns true. You should use === instead.

Installing Git on Eclipse

egit was included in Indigo (2011) and should be there in all future Eclipse versions after that.

Just go to ![(Help->Install New Software)]

Then Work with: --All Available Sites--

Then type egit underneath and wait (may take a while) ! Then click the checkbox and install.

cast or convert a float to nvarchar?

For anyone willing to try a different method, they can use this:

select FORMAT([Column_Name], '') from YourTable

This will easily change any float value to nvarchar.

Markdown open a new window link

It is very dependent of the engine that you use for generating html files. If you are using Hugo for generating htmls you have to write down like this:

<a href="https://example.com" target="_blank" rel="noopener"><span>Example Text</span> </a>.

How to load property file from classpath?

If you use the static method and load the properties file from the classpath folder so you can use the below code :

//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));

Simple way to encode a string according to a password?

This works but password length should be exactly 8. This is simple and requires pyDes.

from pyDes import *

def encode(data,password):
    k = des(password, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
    d = k.encrypt(data)
    return d

def decode(data,password):
    k = des(password, CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
    d = k.decrypt(data)
    return d

x = encode('John Doe', 'mypass12')
y = decode(x,'mypass12')

print x
print y

OUTPUT:

³.\Þ\åS¾+æÅ`;Ê
John Doe

Picasso v/s Imageloader v/s Fresco vs Glide

Neither Glide nor Picasso is perfect. The way Glide loads an image to memory and do the caching is better than Picasso which let an image loaded far faster. In addition, it also helps preventing an app from popular OutOfMemoryError. GIF Animation loading is a killing feature provided by Glide. Anyway Picasso decodes an image with better quality than Glide.

Which one do I prefer? Although I use Picasso for such a very long time, I must admit that I now prefer Glide. But I would recommend you to change Bitmap Format to ARGB_8888 and let Glide cache both full-size image and resized one first. The rest would do your job great!

  • Method count of Picasso and Glide are at 840 and 2678 respectively.
  • Picasso (v2.5.1)'s size is around 118KB while Glide (v3.5.2)'s is around 430KB.
  • Glide creates cached images per size while Picasso saves the full image and process it, so on load it shows faster with Glide but uses more memory.
  • Glide use less memory by default with RGB_565.

+1 For Picasso Palette Helper.

There is a post that talk a lot about Picasso vs Glide post

Spring CORS No 'Access-Control-Allow-Origin' header is present

We had the same issue and we resolved it using Spring's XML configuration as below:

Add this in your context xml file

<mvc:cors>
    <mvc:mapping path="/**"
        allowed-origins="*"
        allowed-headers="Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Authorization, X-Requested-With, requestId, Correlation-Id"
        allowed-methods="GET, PUT, POST, DELETE"/>
</mvc:cors>

How can I create and style a div using JavaScript?

This will be inside a function or script tag with custom CSS with classname as Custom

 var board = document.createElement('div');
 board.className = "Custom";
 board.innerHTML = "your data";
 console.log(count);
 document.getElementById('notification').appendChild(board);

VMWare Player vs VMWare Workstation

Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.

Get and Set Screen Resolution

Answer from different solutions to get Display Resolution

  1. Get the scaling factor

  2. Get Screen.PrimaryScreen.Bounds.Width and Screen.PrimaryScreen.Bounds.Height multiple by scaling factor result

    #region Display Resolution
    
     [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
     public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
    
     public enum DeviceCap
     {
         VERTRES = 10,
         DESKTOPVERTRES = 117
     }
    
    
     public static double GetWindowsScreenScalingFactor(bool percentage = true)
     {
         //Create Graphics object from the current windows handle
         Graphics GraphicsObject = Graphics.FromHwnd(IntPtr.Zero);
         //Get Handle to the device context associated with this Graphics object
         IntPtr DeviceContextHandle = GraphicsObject.GetHdc();
         //Call GetDeviceCaps with the Handle to retrieve the Screen Height
         int LogicalScreenHeight = GetDeviceCaps(DeviceContextHandle, (int)DeviceCap.VERTRES);
         int PhysicalScreenHeight = GetDeviceCaps(DeviceContextHandle, (int)DeviceCap.DESKTOPVERTRES);
         //Divide the Screen Heights to get the scaling factor and round it to two decimals
         double ScreenScalingFactor = Math.Round(PhysicalScreenHeight / (double)LogicalScreenHeight, 2);
         //If requested as percentage - convert it
         if (percentage)
         {
             ScreenScalingFactor *= 100.0;
         }
         //Release the Handle and Dispose of the GraphicsObject object
         GraphicsObject.ReleaseHdc(DeviceContextHandle);
         GraphicsObject.Dispose();
         //Return the Scaling Factor
         return ScreenScalingFactor;
     }
    
     public static Size GetDisplayResolution()
     {
         var sf = GetWindowsScreenScalingFactor(false);
         var screenWidth = Screen.PrimaryScreen.Bounds.Width * sf;
         var screenHeight = Screen.PrimaryScreen.Bounds.Height * sf;
         return new Size((int)screenWidth, (int)screenHeight);
     }
    
     #endregion
    

to check display resolution

var size = GetDisplayResolution();
Console.WriteLine("Display Resoluton: " + size.Width + "x" + size.Height);

jquery beforeunload when closing (not leaving) the page?

Try this, loading data via ajax and displaying through return statement.

<script type="text/javascript">
function closeWindow(){

    var Data = $.ajax({
        type : "POST",
        url : "file.txt",  //loading a simple text file for sample.
        cache : false,
        global : false,
        async : false,
        success : function(data) {
            return data;
        }

    }).responseText;


    return "Are you sure you want to leave the page? You still have "+Data+" items in your shopping cart";
}

window.onbeforeunload = closeWindow;
</script>

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

Remove element by id

You could make a remove function so that you wouldn't have to think about it every time:

function removeElement(id) {
    var elem = document.getElementById(id);
    return elem.parentNode.removeChild(elem);
}

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 

Italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>

Bold:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>

Bold-italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>

Light:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>

Light-italic:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :

Medium:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>

Medium-italic:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>

Black:

<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

Add this to your code for fixed height and add one scroll.

.fixedbox {
    max-height: auto;
    overflow-y: scroll;
}

jQuery DatePicker with today as maxDate

If you're using bootstrap 3 date time picker, try this:

$('.selector').datetimepicker({ maxDate: $.now() });

Simplest way to merge ES6 Maps/Sets?

It does not make any sense to call new Set(...anArrayOrSet) when adding multiple elements (from either an array or another set) to an existing set.

I use this in a reduce function, and it is just plain silly. Even if you have the ...array spread operator available, you should not use it in this case, as it wastes processor, memory, and time resources.

// Add any Map or Set to another
function addAll(target, source) {
  if (target instanceof Map) {
    Array.from(source.entries()).forEach(it => target.set(it[0], it[1]))
  } else if (target instanceof Set) {
    source.forEach(it => target.add(it))
  }
}

Demo Snippet

_x000D_
_x000D_
// Add any Map or Set to another_x000D_
function addAll(target, source) {_x000D_
  if (target instanceof Map) {_x000D_
    Array.from(source.entries()).forEach(it => target.set(it[0], it[1]))_x000D_
  } else if (target instanceof Set) {_x000D_
    source.forEach(it => target.add(it))_x000D_
  }_x000D_
}_x000D_
_x000D_
const items1 = ['a', 'b', 'c']_x000D_
const items2 = ['a', 'b', 'c', 'd']_x000D_
const items3 = ['d', 'e']_x000D_
_x000D_
let set_x000D_
_x000D_
set = new Set(items1)_x000D_
addAll(set, items2)_x000D_
addAll(set, items3)_x000D_
console.log('adding array to set', Array.from(set))_x000D_
_x000D_
set = new Set(items1)_x000D_
addAll(set, new Set(items2))_x000D_
addAll(set, new Set(items3))_x000D_
console.log('adding set to set', Array.from(set))_x000D_
_x000D_
const map1 = [_x000D_
  ['a', 1],_x000D_
  ['b', 2],_x000D_
  ['c', 3]_x000D_
]_x000D_
const map2 = [_x000D_
  ['a', 1],_x000D_
  ['b', 2],_x000D_
  ['c', 3],_x000D_
  ['d', 4]_x000D_
]_x000D_
const map3 = [_x000D_
  ['d', 4],_x000D_
  ['e', 5]_x000D_
]_x000D_
_x000D_
const map = new Map(map1)_x000D_
addAll(map, new Map(map2))_x000D_
addAll(map, new Map(map3))_x000D_
console.log('adding map to map',_x000D_
  'keys', Array.from(map.keys()),_x000D_
  'values', Array.from(map.values()))
_x000D_
_x000D_
_x000D_

Programmatically scroll a UIScrollView

You can scroll to some point in a scroll view with one of the following statements in Objective-C

[scrollView setContentOffset:CGPointMake(x, y) animated:YES];

or Swift

scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true)

See the guide "Scrolling the Scroll View Content" from Apple as well.

To do slideshows with UIScrollView, you arrange all images in the scroll view, set up a repeated timer, then -setContentOffset:animated: when the timer fires.

But a more efficient approach is to use 2 image views and swap them using transitions or simply switching places when the timer fires. See iPhone Image slideshow for details.

PostgreSQL: Which version of PostgreSQL am I running?

Execute command

psql -V

Where

V must be in capital.

How do you change the character encoding of a postgres database?

Daniel Kutik's answer is correct, but it can be even more safe, with database renaming.

So, the truly safe way is:

  1. Create new database with the different encoding and name
  2. Dump your database
  3. Restore dump to the new DB
  4. Test that your application runs correctly with the new DB
  5. Rename old DB to something meaningful
  6. Rename new DB
  7. Test application again
  8. Drop the old database

In case of emergency, just rename DBs back

Renaming a directory in C#

There is no difference between moving and renaming; you should simply call Directory.Move.

In general, if you're only doing a single operation, you should use the static methods in the File and Directory classes instead of creating FileInfo and DirectoryInfo objects.

For more advice when working with files and directories, see here.

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

What does "pending" mean for request in Chrome Developer Window?

I had a similar issue with application/json ajax calls. In ff/IE they were fine. In chrome in the Developer Network window Status was always (pending) because a different status code was being returned.

In my case I changed my Json response to send a HttpStatusCode of 200 then Chrome was fine and the Status Text changed to 200 OK.

For example using ASP.NET Web Api

 return new HttpResponseMessage(HttpStatusCode.OK ) {
            Content = request.Content
        };

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

Bypass invalid SSL certificate errors when calling web services in .Net

I was having same error using DownloadString; and was able to make it works as below with suggestions on this page

System.Net.WebClient client = new System.Net.WebClient();            
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string sHttpResonse = client.DownloadString(sUrl);

Detect Safari browser

Note: always try to detect the specific behavior you're trying to fix, instead of targeting it with isSafari?

As a last resort, detect Safari with this regex:

var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

It uses negative look-arounds and it excludes Chrome, Edge, and all Android browsers that include the Safari name in their user agent.

When do we need curly braces around shell variables?

Variables are declared and assigned without $ and without {}. You have to use

var=10

to assign. In order to read from the variable (in other words, 'expand' the variable), you must use $.

$var      # use the variable
${var}    # same as above
${var}bar # expand var, and append "bar" too
$varbar   # same as ${varbar}, i.e expand a variable called varbar, if it exists.

This has confused me sometimes - in other languages we refer to the variable in the same way, regardless of whether it's on the left or right of an assignment. But shell-scripting is different, $var=10 doesn't do what you might think it does!

Change string color with NSAttributedString?

With Swift 4, NSAttributedStringKey has a static property called foregroundColor. foregroundColor has the following declaration:

static let foregroundColor: NSAttributedStringKey

The value of this attribute is a UIColor object. Use this attribute to specify the color of the text during rendering. If you do not specify this attribute, the text is rendered in black.

The following Playground code shows how to set the text color of an NSAttributedString instance with foregroundColor:

import UIKit

let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)

The code below shows a possible UIViewController implementation that relies on NSAttributedString in order to update the text and text color of a UILabel from a UISlider:

import UIKit

enum Status: Int {
    case veryBad = 0, bad, okay, good, veryGood

    var display: (text: String, color: UIColor) {
        switch self {
        case .veryBad:  return ("Very bad", .red)
        case .bad:      return ("Bad", .orange)
        case .okay:     return ("Okay", .yellow)
        case .good:     return ("Good", .green)
        case .veryGood: return ("Very good", .blue)
        }
    }

    static let minimumValue = Status.veryBad.rawValue
    static let maximumValue = Status.veryGood.rawValue
}
final class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var slider: UISlider!
    var currentStatus: Status = Status.veryBad {
        didSet {
            // currentStatus is our model. Observe its changes to update our display
            updateDisplay()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Prepare slider
        slider.minimumValue = Float(Status.minimumValue)
        slider.maximumValue = Float(Status.maximumValue)

        // Set display
        updateDisplay()
    }

    func updateDisplay() {
        let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
        let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
        label.attributedText = attributedString
        slider.value = Float(currentStatus.rawValue)
    }

    @IBAction func updateCurrentStatus(_ sender: UISlider) {
        let value = Int(sender.value.rounded())
        guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
        currentStatus = status
    }

}

Note however that you don't really need to use NSAttributedString for such an example and can simply rely on UILabel's text and textColor properties. Therefore, you can replace your updateDisplay() implementation with the following code:

func updateDisplay() {
    label.text = currentStatus.display.text
    label.textColor = currentStatus.display.color
    slider.value = Float(currentStatus.rawValue)
}

Cannot add or update a child row: a foreign key constraint fails

Maybe whilst you added the userID column, there is a data for that certain table that it is established so it will have a default value of 0, try adding the column without the NOT NULL

ImportError: No module named requests

Adding Third-party Packages to the Application

Follow this link https://cloud.google.com/appengine/docs/python/tools/libraries27?hl=en#vendoring

step1 : Have a file by named a file named appengine_config.py in the root of your project, then add these lines:

from google.appengine.ext import vendor

Add any libraries installed in the "lib" folder.

vendor.add('lib')

Step 2: create a directory and name it "lib" under root directory of project.

step 3: use pip install -t lib requests

step 4 : deploy to app engine.

Can I have multiple Xcode versions installed?

All the updates for new version of xcode will be available in appstore if you have installed the version from appstore. If you just paste the downloaded version appstore will show install not update. Hence keep the stable version downloaded from appstore in your applications folder.

To try new beta releases i usually put it in separate drive and unzip and install it there. This will avoid confusion while working on stable version.

To avoid confusion you can keep only the stable version in your dock and open the beta version from spotlight(Command + Space). This will place beta temporarily on dock. But it will make sure you don't accidentally edit your client project in beta version.

Most Important:- Working on same project on two different xcode might create some unwanted results. Like there was a bug in interface builder that got introduced in certain version of xcode. Which broke the constraints. It got fixed again in the next one.

Keep track of release notes to know exactly what are additional features and what are known issues.

Resize to fit image in div, and center horizontally and vertically

NOT SUPPORTED BY IE

More info here: Can I Use?

_x000D_
_x000D_
.container {_x000D_
  overflow: hidden;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
.container img {_x000D_
  object-fit: cover;_x000D_
  width: 100%;_x000D_
  min-height: 100%;_x000D_
}
_x000D_
<div class='container'>_x000D_
    <img src='http://i.imgur.com/H9lpVkZ.jpg' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I convert tabs to spaces in every file of a directory?

I like the "find" example above for the recursive application. To adapt it to be non-recursive, only changing files in the current directory that match a wildcard, the shell glob expansion can be sufficient for small amounts of files:

ls *.java | awk '{print "expand -t 4 ", $0, " > /tmp/e; mv /tmp/e ", $0}' | sh -v

If you want it silent after you trust that it works, just drop the -v on the sh command at the end.

Of course you can pick any set of files in the first command. For example, list only a particular subdirectory (or directories) in a controlled manner like this:

ls mod/*/*.php | awk '{print "expand -t 4 ", $0, " > /tmp/e; mv /tmp/e ", $0}' | sh

Or in turn run find(1) with some combination of depth parameters etc:

find mod/ -name '*.php' -mindepth 1 -maxdepth 2 | awk '{print "expand -t 4 ", $0, " > /tmp/e; mv /tmp/e ", $0}' | sh

How to make HTML table cell editable?

Try this code.

$(function () {
 $("td").dblclick(function () {
    var OriginalContent = $(this).text();

    $(this).addClass("cellEditing");
    $(this).html("<input type="text" value="&quot; + OriginalContent + &quot;" />");
    $(this).children().first().focus();

    $(this).children().first().keypress(function (e) {
        if (e.which == 13) {
            var newContent = $(this).val();
            $(this).parent().text(newContent);
            $(this).parent().removeClass("cellEditing");
        }
    });

 $(this).children().first().blur(function(){
    $(this).parent().text(OriginalContent);
    $(this).parent().removeClass("cellEditing");
 });
 });
});

You can also visit this link for more details :

How to inspect FormData?

Angular

var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

formData.forEach((value,key) => {
  console.log(key+" "+value)
});

Not: When I am working on Angular 5 (with TypeScript 2.4.2), I tried as above and it works except a static checking error but also for(var pair of formData.entries()) is not working.

_x000D_
_x000D_
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

formData.forEach((value,key) => {
  console.log(key+" "+value)
});
_x000D_
_x000D_
_x000D_

Check at Stackblitz

SQL Query to concatenate column values from multiple rows in Oracle

For those who must solve this problem using Oracle 9i (or earlier), you will probably need to use SYS_CONNECT_BY_PATH, since LISTAGG is not available.

To answer the OP, the following query will display the PID from Table A and concatenate all the DESC columns from Table B:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT a.pid, seq, description
              FROM table_a a, table_b b
              WHERE a.pid = b.pid(+)
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

There may also be instances where keys and values are all contained in one table. The following query can be used where there is no Table A, and only Table B exists:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT pid, seq, description
              FROM table_b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

All values can be reordered as desired. Individual concatenated descriptions can be reordered in the PARTITION BY clause, and the list of PIDs can be reordered in the final ORDER BY clause.


Alternately: there may be times when you want to concatenate all the values from an entire table into one row.

The key idea here is using an artificial value for the group of descriptions to be concatenated.

In the following query, the constant string '1' is used, but any value will work:

SELECT SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY unique_id ORDER BY pid, seq) rnum, description
       FROM (
              SELECT '1' unique_id, b.pid, b.seq, b.description
              FROM table_b b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1;

Individual concatenated descriptions can be reordered in the PARTITION BY clause.

Several other answers on this page have also mentioned this extremely helpful reference: https://oracle-base.com/articles/misc/string-aggregation-techniques

SQLException : String or binary data would be truncated

With Linq To SQL I debugged by logging the context, eg. Context.Log = Console.Out Then scanned the SQL to check for any obvious errors, there were two:

-- @p46: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value1]
-- @p8: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value2]

the last one I found by scanning the table schema against the values, the field was nvarchar(20) but the value was 22 chars

-- @p41: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [1234567890123456789012]

What is @RenderSection in asp.net MVC

If you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()
        @RenderSection("scripts", required: false)
    </body>
</html>

then you can have an index.cshtml content view like this

@section scripts {
     <script type="text/javascript">alert('hello');</script>
}

the required indicates whether or not the view using the layout page must have a scripts section

Circle-Rectangle collision detection (intersection)

For those have to calculate Circle/Rectangle collision in Geographic Coordinates with SQL,
this is my implementation in oracle 11 of e.James suggested algorithm.

In input it requires circle coordinates, circle radius in km and two vertices coordinates of the rectangle:

CREATE OR REPLACE FUNCTION "DETECT_CIRC_RECT_COLLISION"
(
    circleCenterLat     IN NUMBER,      -- circle Center Latitude
    circleCenterLon     IN NUMBER,      -- circle Center Longitude
    circleRadius        IN NUMBER,      -- circle Radius in KM
    rectSWLat           IN NUMBER,      -- rectangle South West Latitude
    rectSWLon           IN NUMBER,      -- rectangle South West Longitude
    rectNELat           IN NUMBER,      -- rectangle North Est Latitude
    rectNELon           IN NUMBER       -- rectangle North Est Longitude
)
RETURN NUMBER
AS
    -- converts km to degrees (use 69 if miles)
    kmToDegreeConst     NUMBER := 111.045;

    -- Remaining rectangle vertices 
    rectNWLat   NUMBER;
    rectNWLon   NUMBER;
    rectSELat   NUMBER;
    rectSELon   NUMBER;

    rectHeight  NUMBER;
    rectWIdth   NUMBER;

    circleDistanceLat   NUMBER;
    circleDistanceLon   NUMBER;
    cornerDistanceSQ    NUMBER;

BEGIN
    -- Initialization of remaining rectangle vertices  
    rectNWLat := rectNELat;
    rectNWLon := rectSWLon;
    rectSELat := rectSWLat;
    rectSELon := rectNELon;

    -- Rectangle sides length calculation
    rectHeight := calc_distance(rectSWLat, rectSWLon, rectNWLat, rectNWLon);
    rectWidth := calc_distance(rectSWLat, rectSWLon, rectSELat, rectSELon);

    circleDistanceLat := abs( (circleCenterLat * kmToDegreeConst) - ((rectSWLat * kmToDegreeConst) + (rectHeight/2)) );
    circleDistanceLon := abs( (circleCenterLon * kmToDegreeConst) - ((rectSWLon * kmToDegreeConst) + (rectWidth/2)) );

    IF circleDistanceLon > ((rectWidth/2) + circleRadius) THEN
        RETURN -1;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLat > ((rectHeight/2) + circleRadius) THEN
        RETURN -1;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLon <= (rectWidth/2) THEN
        RETURN 0;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLat <= (rectHeight/2) THEN
        RETURN 0;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;


    cornerDistanceSQ := POWER(circleDistanceLon - (rectWidth/2), 2) + POWER(circleDistanceLat - (rectHeight/2), 2);

    IF cornerDistanceSQ <=  POWER(circleRadius, 2) THEN
        RETURN 0;  --  -1 => NO Collision ; 0 => Collision Detected
    ELSE
        RETURN -1;  --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    RETURN -1;  --  -1 => NO Collision ; 0 => Collision Detected
END;    

What is the difference between Java RMI and RPC?

Remote Procedure Call (RPC) is a inter process communication which allows calling a function in another process residing in local or remote machine.

Remote method invocation (RMI) is an API, which implements RPC in java with support of object oriented paradigms.

  1. You can think of invoking RPC is like calling a C procedure. RPC supports primitive data types where as RMI support method parameters/return types as java objects.

  2. RMI is easy to program unlike RPC. You can think your business logic in terms of objects instead of a sequence of primitive data types.

  3. RPC is language neutral unlike RMI, which is limited to java

  4. RMI is little bit slower to RPC

Have a look at this article for RPC implementation in C

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

There are 4 ways that I know of:

  • import the certificate to your app and use it for the connection
  • disable certificate checking
  • add your certificate to the trusted system certificates in Android
  • buy a verified certificate that is accepted by Android

I assume you don't want to pay for this, so I think the most elegant solution is the first one, what can be accomplished this way:

http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html

jQuery get the name of a select option

For anyone who comes across this late, like me.

As others have stated, name isn't a valid attribute of an option element. Combining the accepted answer above with the answer from this other question, you get:

$(this).find('option:selected').text();

dyld: Library not loaded: @rpath/libswiftCore.dylib

I am on Xcode 8.3.2. For me the issue was the AppleWWDRCA certificate was in both system and login keychain. Removed both and then added to just login keychain, now it runs fine again. 2 days lost

Uri not Absolute exception getting while calling Restful Webservice

For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: @Value annotation.

How do I escape a single quote in SQL Server?

How about:

insert into my_table values('hi, my name' + char(39) + 's tim.')

Pretty-Print JSON Data to a File using Python

You should use the optional argument indent.

header, output = client.request(twitterRequest, method="GET", body=None,
                            headers=None, force_auth_header=True)

# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()

SSIS expression: convert date to string

for the sake of completeness, you could use:

(DT_STR,8, 1252) (YEAR(GetDate()) * 10000 + MONTH(GetDate()) * 100 + DAY(GetDate()))

for YYYYMMDD or

RIGHT("000000" + (DT_STR,8, 1252) (DAY(GetDate()) * 1000000 + MONTH(GetDate()) * 10000 + YEAR(GetDate())), 8)

for DDMMYYYY (without hyphens). If you want / need the date as integer (e.g. for _key-columns in DWHs), just remove the DT_STR / RIGTH function and do just the math.

Error on line 2 at column 1: Extra content at the end of the document

I think you are creating a document that looks like this:

<mycatch>
    ....
</mycatch>
<mycatch>
    ....
</mycatch>

This is not a valid XML document as it has more than one root element. You must have a single top-level element, as in

<mydocument>      
  <mycatch>
      ....
  </mycatch>
  <mycatch>
      ....
  </mycatch>
  ....
</mydocument>

RuntimeWarning: DateTimeField received a naive datetime

Just to fix the error to set current time

from django.utils import timezone
import datetime

datetime.datetime.now(tz=timezone.utc) # you can use this value

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

This problem occurs when we update the same object of session, which we have used to fetch the object from database.

You can use merge method of hibernate instead of update method.

e.g. First use session.get() and then you can use session.merge (object). This method will not create any problem. We can also use merge() method to update object in database.

how to access iFrame parent page using jquery?

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

Merging two arrays in .NET

Assuming the destination array has enough space, Array.Copy() will work. You might also try using a List<T> and its .AddRange() method.

How do I change a tab background color when using TabLayout?

You can change the background or ripple color of each Tab like this:

    //set ripple color for each tab
    for(int n = 0; n < mTabLayout.getTabCount(); n++){

        View tab = ((ViewGroup)mTabLayout.getChildAt(0)).getChildAt(n);

        if(tab != null && tab.getBackground() instanceof RippleDrawable){
            RippleDrawable rippleDrawable = (RippleDrawable)tab.getBackground();
            if (rippleDrawable != null) {
                rippleDrawable.setColor(ColorStateList.valueOf(rippleColor));
            }
        }
    }