Programs & Examples On #Dir

Abbreviation for a directory, a virtual container within a digital file system.

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

Yes. There is a simple way to remove everything in iPython. In iPython console, just type:

%reset

Then system will ask you to confirm. Press y. If you don't want to see this prompt, simply type:

%reset -f

This should work..

Command to list all files in a folder as well as sub-folders in windows

The below post gives the solution for your scenario.

dir /s /b /o:gn

/S Displays files in specified directory and all subdirectories.

/B Uses bare format (no heading information or summary).

/O List by files in sorted order.

Simple linked list in C++

Here is my implementation.

#include <iostream>

using namespace std;

template< class T>
struct node{
    T m_data;
    node* m_next_node;

    node(T t_data, node* t_node) :
        m_data(t_data), m_next_node(t_node){}

    ~node(){
        std::cout << "Address :" << this << " Destroyed" << std::endl;
    }
};

template<class T>
class linked_list {
public:
    node<T>* m_list;

    linked_list(): m_list(nullptr){}

    void add_node(T t_data) {
        node<T>* _new_node = new node<T>(t_data, nullptr);
        _new_node->m_next_node = m_list;
        m_list = _new_node;
    }


    void populate_nodes(node<T>* t_node) {
        if  (t_node != nullptr) {
            std::cout << "Data =" << t_node->m_data
                      << ", Address =" << t_node->m_next_node
                      << std::endl;
            populate_nodes(t_node->m_next_node);
        }
    }

    void delete_nodes(node<T>* t_node) {
        if (t_node != nullptr) {
            delete_nodes(t_node->m_next_node);
        }
        delete(t_node);
    }

};


int main()
{
    linked_list<float>* _ll = new linked_list<float>();

    _ll->add_node(1.3);
    _ll->add_node(5.5);
    _ll->add_node(10.1);
    _ll->add_node(123);
    _ll->add_node(4.5);
    _ll->add_node(23.6);
    _ll->add_node(2);

    _ll->populate_nodes(_ll->m_list);

    _ll->delete_nodes(_ll->m_list);

    delete(_ll);

    return 0;
}

enter image description here

Python math module

pow is built into the language(not part of the math library). The problem is that you haven't imported math.

Try this:

import math
math.sqrt(4)

How can I disable a specific LI element inside a UL?

I usualy use <li> to include <a> link. I disabled click action writing like this; You may not include <a> link, then you will ignore my post.

_x000D_
_x000D_
a.noclick       {_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<a class="noclick" href="#">this is disabled</a>
_x000D_
_x000D_
_x000D_

Latest jQuery version on Google's CDN

Here's an updated link.

There are updated now and then, just keep checking for the latest version.

How to clear Route Caching on server: Laravel 5.2.37

If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.

php artisan cache:clear

php artisan route:cache

It should work.

sqlite database default time value 'now'

i believe you can use

CREATE TABLE test (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  t TIMESTAMP
  DEFAULT CURRENT_TIMESTAMP
);

as of version 3.1 (source)

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

I wanted to find a string between / and #, but # is sometimes optional. Here is the regex I use:

  (?<=\/)([^#]+)(?=#*)

Java java.sql.SQLException: Invalid column index on preparing statement

As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....

The ? and the OR needs to be seperated by a space character. Do it wherever needed in the query string.

How to execute function in SQL Server 2008

It looks like there's something else called Afisho_rankimin in your DB so the function is not being created. Try calling your function something else. E.g.

CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
   BEGIN
       Declare @rankimi int
       Select @rankimi=dbo.RESTORANTET.Rankimi
       From RESTORANTET
       Where  dbo.RESTORANTET.ID_Rest=@emri_rest
       RETURN @rankimi
  END
  GO

Note that you need to call this only once, not every time you call the function. After that try calling

SELECT dbo.Afisho_rankimin1(5) AS Rankimi 

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

Normally this error means that a connection was established with a server but that connection was closed by the remote server. This could be due to a slow server, a problem with the remote server, a network problem, or (maybe) some kind of security error with data being sent to the remote server but I find that unlikely.

Normally a network error will resolve itself given a bit of time, but it sounds like you’ve already given it a bit of time.

cURL sometimes having issue with SSL and SSL certificates. I think that your Apache and/or PHP was compiled with a recent version of the cURL and cURL SSL libraries plus I don't think that OpenSSL was installed in your web server.

Although I can not be certain However, I believe cURL has historically been flakey with SSL certificates, whereas, Open SSL does not.

Anyways, try installing Open SSL on the server and try again and that should help you get rid of this error.

how to load url into div tag

$(document).ready(function() {
 $('#content').load('your_url_here');
});

Remove CSS class from element with JavaScript (no jQuery)

var element = document.getElementById('example_id');
var remove_class = 'example_class';

element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');

How to run a single RSpec test?

Run the commands from your project's root directory:

# run all specs in the project's spec folder
bundle exec rspec 

# run specs nested under a directory, like controllers
bundle exec rspec spec/controllers

# run a single test file
bundle exec rspec spec/controllers/groups_controller_spec.rb

# run a test or subset of tests within a file
# e.g., if the 'it', 'describe', or 'context' block you wish to test
# starts at line 45, run:
bundle exec rspec spec/controllers/groups_controller_spec.rb:45

Bootstrap 3 dropdown select

Try this:

<div class="form-group">
     <label class="control-label" for="Company">Company</label>
     <select id="Company" class="form-control" name="Company">
         <option value="small">small</option>
         <option value="medium">medium</option>
         <option value="large">large</option>
     </select> 
 </div>

Git Symlinks in Windows

Short answer: They are now supported nicely, if you can enable developer mode.

From https://blogs.windows.com/buildingapps/2016/12/02/symlinks-windows-10/

Now in Windows 10 Creators Update, a user (with admin rights) can first enable Developer Mode, and then any user on the machine can run the mklink command without elevating a command-line console.

What drove this change? The availability and use of symlinks is a big deal to modern developers:

Many popular development tools like git and package managers like npm recognize and persist symlinks when creating repos or packages, respectively. When those repos or packages are then restored elsewhere, the symlinks are also restored, ensuring disk space (and the user’s time) isn’t wasted.

Easy to overlook with all the other announcements of the "Creator's update", but if you enable Developer Mode, you can create symlinks without elevated privileges. You might have to re-install git and make sure symlink support is enabled, as it's not by default.

Symbolic Links aren't enabled by default

How to remove responsive features in Twitter Bootstrap 3?

Source from: http://getbootstrap.com/getting-started/#disable-responsive

  1. Omit the viewport <meta> mentioned in the CSS docs
  2. Override the width on the .container for each grid tier with a single width, for example width: 970px !important; Be sure that this comes after the default Bootstrap CSS. You can optionally avoid the !important with media queries or some selector-fu.
  3. If using navbars, remove all navbar collapsing and expanding behavior.
  4. For grid layouts, use .col-xs-* classes in addition to, or in place of, the medium/large ones. Don't worry, the extra-small device grid scales to all resolutions.

How do I position a div relative to the mouse pointer using jQuery?

var mouseX;
var mouseY;
$(document).mousemove( function(e) {
   mouseX = e.pageX; 
   mouseY = e.pageY;
});  
$(".classForHoverEffect").mouseover(function(){
  $('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});

the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,

$(".classForHoverEffect").mouseout(function(){
  $('#DivToShow').fadeOut('slow');
});

If you DIV is already positioned, you can simply use

$('.classForHoverEffect').hover(function(){
  $('#DivToShow').fadeIn('slow');
});

Also, keep in mind, your DIV style needs to be set to display:none; in order for it to fadeIn or show.

Java, return if trimmed String in List contains String

String search = "A";
for(String s : myList)
    if(s.contains(search)) return true;
return false;

This will iterate over each string in the list, and check if it contains the string you're looking for. If it's only spaces you want to trap for, you can do this:

String search = "A";
for(String s : myList)
    if(s.replaceAll(" ","").contains(search)) return true;
return false;

which will first replace spaces with empty strings before searching. Additionally, if you just want to trim the string first, you can do:

String search = "A";
for(String s : myList)
    if(s.trim().contains(search)) return true;
return false;

git: How to ignore all present untracked files?

In case you are not on Unix like OS, this would work on Windows using PowerShell

git status --porcelain | ?{ $_ -match "^\?\? " }| %{$_ -replace "^\?\? ",""} | Add-Content .\.gitignore

However, .gitignore file has to have a new empty line, otherwise it will append text to the last line no matter if it has content.

This might be a better alternative:

$gi=gc .\.gitignore;$res=git status --porcelain|?{ $_ -match "^\?\? " }|%{ $_ -replace "^\?\? ", "" }; $res=$gi+$res; $res | Out-File .\.gitignore

Where does Hive store files in HDFS?

In Hive terminal type:

hive> set hive.metastore.warehouse.dir;

(it will print the path)

How to get random value out of an array?

You get a random number out of an array as follows:

$randomValue = $rand[array_rand($rand,1)];

How to remove carriage returns and new lines in Postgresql?

OP asked specifically about regexes since it would appear there's concern for a number of other characters as well as newlines, but for those just wanting strip out newlines, you don't even need to go to a regex. You can simply do:

select replace(field,E'\n','');

I think this is an SQL-standard behavior, so it should extend back to all but perhaps the very earliest versions of Postgres. The above tested fine for me in 9.4 and 9.2

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Try this in the console:

JSON.parse(undefined)

Here is what you will get:

Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

In other words, your app is attempting to parse undefined, which is not valid JSON.

There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode).

window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn)  // oops, misspelled!

The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't.

Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint. This will give you pretty good confidence that there are no typos.

How can I run a html file from terminal?

python -mhtmllib test.html or curl http://www.comanyname.com/somepage.html|python -mhtmllib -

Getting unique items from a list

In .Net 2.0 I`m pretty sure about this solution:

public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
     List<T> uniques = new List<T>();
     foreach (T item in source)
     {
         if (!uniques.Contains(item)) uniques.Add(item);
     }
     return uniques;
}

How do I download a binary file over HTTP?

I know that this is an old question, but Google threw me here and I think I found a simpler answer.

In Railscasts #179, Ryan Bates used the Ruby standard class OpenURI to do much of what was asked like this:

(Warning: untested code. You might need to change/tweak it.)

require 'open-uri'

File.open("/my/local/path/sample.flv", "wb") do |saved_file|
  # the following "open" is provided by open-uri
  open("http://somedomain.net/flv/sample/sample.flv", "rb") do |read_file|
    saved_file.write(read_file.read)
  end
end

How to trim a string to N chars in Javascript?

I suggest to use an extension for code neatness. Note that extending an internal object prototype could potentially mess with libraries that depend on them.

String.prototype.trimEllip = function (length) {
  return this.length > length ? this.substring(0, length) + "..." : this;
}

And use it like:

var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)

XML Error: There are multiple root elements

You need to enclose your <parent> elements in a surrounding element as XML Documents can have only one root node:

<parents> <!-- I've added this tag -->
    <parent>
        <child>
            Text
        </child>
    </parent>
    <parent>
        <child>
            <grandchild>
                Text
            </grandchild>
            <grandchild>
                Text
            </grandchild>
        </child>
        <child>
            Text
        </child>
    </parent>
</parents> <!-- I've added this tag -->

As you're receiving this markup from somewhere else, rather than generating it yourself, you may have to do this yourself by treating the response as a string and wrapping it with appropriate tags, prior to attempting to parse it as XML.

So, you've a couple of choices:

  1. Get the provider of the web service to return you actual XML that has one root node
  2. Pre-process the XML, as I've suggested above, to add a root node
  3. Pre-process the XML to split it into multiple chunks (i.e. one for each <parent> node) and process each as a distinct XML Document

Does :before not work on img elements?

This one works for me:

html

<ul>
    <li> name here </li>
</ul>

CSS

ul li::before {
    content: url(../images/check.png);
}

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

In your PHP code you have set the incorrect port, this is what the code should be

<?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db     = 'test_db13';

The port in your code is set to 3360 when it should be 3306, however as this is the default port, you don't need to specify.

convert htaccess to nginx

Online tools to translate Apache .htaccess to Nginx rewrite tools include:

Note that these tools will convert to equivalent rewrite expressions using if statements, but they should be converted to try_files. See:

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

Center image horizontally within a div

Style.css

img#center-img{

 display: block;
 margin: auto;
}

Html

<html>
  <body>
    <div>
      <img src='pic.png' id='center-img'>
    </div>
  </body>
</html>

JPA Query.getResultList() - use in a generic way

I had the same problem and a simple solution that I found was:

List<Object[]> results = query.getResultList();
for (Object[] result: results) {
    SomeClass something = (SomeClass)result[1];
    something.doSomething;
}

I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.

What's the difference between an Angular component and module

Well, it's too late to post an answer, but I feel my explanation will be easy to understand for beginners with Angular. The following is one of the examples that I give during my presentation.

Consider your angular Application as a building. A building can have N number of apartments in it. An apartment is considered as a module. An Apartment can then have N number of rooms which correspond to the building blocks of an Angular application named components.

Now each apartment (Module)` will have rooms (Components), lifts (Services) to enable larger movement in and out the apartments, wires (Pipes) to transform around and make it useful in the apartments.

You will also have places like swimming pool, tennis court which are being shared by all building residents. So these can be considered as components inside SharedModule.

Basically, the difference is as follows,

Table showing key differences between Module and Component

Follow my slides to understand the building blocks of an Angular application

Here is my session on Building Blocks of Angular for beginners

What is the Git equivalent for revision number?

Git does not have the same concept of revision numbers as subversion. Instead each given snapshot made with a commit is tagged by a SHA1 checksum. Why? There are several problems with a running revno in a distributed version control system:

First, since development is not linear at all, the attachment of a number is rather hard as a problem to solve in a way which will satisfy your need as a programmer. Trying to fix this by adding a number might quickly become problematic when the number does not behave as you expect.

Second, revision numbers may be generated on different machines. This makes synchronization of numbers much harder - especially since connectivity is one-way; you may not even have access to all machines that has the repository.

Third, in git, somewhat pioneered by the now defunct OpenCM system, the identity of a commit (what the commit is) is equivalent to its name (the SHA id). This naming = identity concept is very strong. When you sit with a commit name in hand it also identifies the commit in an unforgeable way. This in turn lets you check all of your commits back to the first initial one for corruption with the git fsck command.

Now, since we have a DAG (Directed Acyclic Graph) of revisions and these constitute the current tree, we need some tools to solve your problem: How do we discriminate different versions. First, you can omit part of the hash if a given prefix, 1516bd say, uniquely identifies your commit. But this is also rather contrived. Instead, the trick is to use tags and or branches. A tag or branch is akin to a "yellow stick it note" you attach to a given commit SHA1-id. Tags are, in essence, meant to be non-moving whereas a branch will move when new commits are made to its HEAD. There are ways to refer to a commit around a tag or branch, see the man page of git-rev-parse.

Usually, if you need to work on a specific piece of code, that piece is undergoing changes and should as such be a branch with a saying topic name. Creating lots of branches (20-30 per programmer is not unheard of, with some 4-5 published for others to work on) is the trick for effective git. Every piece of work should start as its own branch and then be merged in when it is tested. Unpublished branches can be rewritten entirely and this part of destroying history is a force of git.

When the change is accepted into master it somewhat freezes and becomes archeology. At that point, you can tag it, but more often a reference to the particular commit is made in a bug tracker or issue tracker via the sha1 sum. Tags tend to be reserved for version bumps and branch points for maintenance branches (for old versions).

What is a reasonable length limit on person "Name" fields?

The average first name is about 6 letters. That leaves 43 for a last name. :) Seems like you could probably shorten it if you like.

The main question is how many rows do you think you will have? I don't think varchar(50) is going to kill you until you get several million rows.

Jquery function return value

I'm not entirely sure of the general purpose of the function, but you could always do this:

function getMachine(color, qty) {
    var retval;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            retval = thisArray[3];
            return false;
        }
    });
    return retval;
}

var retval = getMachine(color, qty);

handling DATETIME values 0000-00-00 00:00:00 in JDBC

I solved the problem considerating '00-00-....' isn't a valid date, then, I changed my SQL column definition adding "NULL" expresion to permit null values:

SELECT "-- Tabla item_pedido";
CREATE TABLE item_pedido (
    id INTEGER AUTO_INCREMENT PRIMARY KEY,
    id_pedido INTEGER,
    id_item_carta INTEGER,
    observacion VARCHAR(64),
    fecha_estimada TIMESTAMP,
    fecha_entrega TIMESTAMP NULL, // HERE IS!!.. NULL = DELIVERY DATE NOT SET YET
    CONSTRAINT fk_item_pedido_id_pedido FOREIGN KEY (id_pedido)
        REFERENCES pedido(id),...

Then, I've to be able to insert NULL values, that means "I didnt register that timestamp yet"...

SELECT "++ INSERT item_pedido";
INSERT INTO item_pedido VALUES
(01, 01, 01, 'Ninguna', ADDDATE(@HOY, INTERVAL 5 MINUTE), NULL),
(02, 01, 02, 'Ninguna', ADDDATE(@HOY, INTERVAL 3 MINUTE), NULL),...

The table look that:

mysql> select * from item_pedido;
+----+-----------+---------------+-------------+---------------------+---------------------+
| id | id_pedido | id_item_carta | observacion | fecha_estimada      | fecha_entrega       |
+----+-----------+---------------+-------------+---------------------+---------------------+
|  1 |         1 |             1 | Ninguna     | 2013-05-19 15:09:48 | NULL                |
|  2 |         1 |             2 | Ninguna     | 2013-05-19 15:07:48 | NULL                |
|  3 |         1 |             3 | Ninguna     | 2013-05-19 15:24:48 | NULL                |
|  4 |         1 |             6 | Ninguna     | 2013-05-19 15:06:48 | NULL                |
|  5 |         2 |             4 | Suave       | 2013-05-19 15:07:48 | 2013-05-19 15:09:48 |
|  6 |         2 |             5 | Seco        | 2013-05-19 15:07:48 | 2013-05-19 15:12:48 |
|  7 |         3 |             5 | Con Mayo    | 2013-05-19 14:54:48 | NULL                |
|  8 |         3 |             6 | Bilz        | 2013-05-19 14:57:48 | NULL                |
+----+-----------+---------------+-------------+---------------------+---------------------+
8 rows in set (0.00 sec)

Finally: JPA in action:

@Stateless
@LocalBean
public class PedidosServices {
    @PersistenceContext(unitName="vagonpubPU")
    private EntityManager em;

    private Logger log = Logger.getLogger(PedidosServices.class.getName());

    @SuppressWarnings("unchecked")
    public List<ItemPedido> obtenerPedidosRetrasados() {
        log.info("Obteniendo listado de pedidos retrasados");
        Query qry = em.createQuery("SELECT ip FROM ItemPedido ip, Pedido p WHERE" +
                " ip.fechaEntrega=NULL" +
                " AND ip.idPedido=p.id" +
                " AND ip.fechaEstimada < :arg3" +
                " AND (p.idTipoEstado=:arg0 OR p.idTipoEstado=:arg1 OR p.idTipoEstado=:arg2)");
        qry.setParameter("arg0", Tipo.ESTADO_BOUCHER_ESPERA_PAGO);
        qry.setParameter("arg1", Tipo.ESTADO_BOUCHER_EN_SERVICIO);
        qry.setParameter("arg2", Tipo.ESTADO_BOUCHER_RECIBIDO);
        qry.setParameter("arg3", new Date());

        return qry.getResultList();
    }

At last all its work. I hope that help you.

PostgreSQL next value of the sequences?

I stumbled upon this question b/c I was trying to find the next sequence value by table. This didn't answer my question however this is how its done, and it may help those looking for the sequence value not by name but by table:

SELECT nextval(pg_get_serial_sequence('<your_table>', 'id')) AS new_id; 

Hope it helps :)

How to identify and switch to the frame in selenium webdriver when frame does not have id

you can use cssSelector,

driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

What is the javascript filename naming convention?

I generally prefer hyphens with lower case, but one thing not yet mentioned is that sometimes it's nice to have the file name exactly match the name of a single module or instantiable function contained within.

For example, I have a revealing module declared with var knockoutUtilityModule = function() {...} within its own file named knockoutUtilityModule.js, although objectively I prefer knockout-utility-module.js.

Similarly, since I'm using a bundling mechanism to combine scripts, I've taken to defining instantiable functions (templated view models etc) each in their own file, C# style, for maintainability. For example, ProductDescriptorViewModel lives on its own inside ProductDescriptorViewModel.js (I use upper case for instantiable functions).

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

Add CSS to <head> with JavaScript?

Here's a simple way.

/**
 * Add css to the document
 * @param {string} css
 */
function addCssToDocument(css){
  var style = document.createElement('style')
  style.innerText = css
  document.head.appendChild(style)
}

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

Here's the proper way to do things:

<?PHP
$sql = 'some query...';
$result = mysql_query($q);

if (! $result){
   throw new My_Db_Exception('Database error: ' . mysql_error());
}

while($row = mysql_fetch_assoc($result)){
  //handle rows.
}

Note the check on (! $result) -- if your $result is a boolean, it's certainly false, and it means there was a database error, meaning your query was probably bad.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

In my case , issue was completely different. I have two classes let's say c1 & c2. Between C1 & C2 dependency is OneToMany. Now if i am saving C1 in DB it was throwing above error.

Resolution of this problem was to get first C2's id from consumer request and find C2 via repository call.Afterwards save c2 into C1 object .Now if i am saving C1, it's working fine.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

I haven't worked much with Appcelerator Titanium, but I'll put my understanding of it at the end.

I can speak a bit more to the differences between PhoneGap and Xamarin, as I work with these two 5 (or more) days a week.

If you are already familiar with C# and JavaScript, then the question I guess is, does the business logic lie in an area more suited to JavaScript or C#?

PhoneGap

PhoneGap is designed to allow you to write your applications using JavaScript and HTML, and much of the functionality that they do provide is designed to mimic the current proposed specifications for the functionality that will eventually be available with HTML5. The big benefit of PhoneGap in my opinion is that since you are doing the UI with HTML, it can easily be ported between platforms. The downside is, because you are porting the same UI between platforms, it won't feel quite as at home in any of them. Meaning that, without further tweaking, you can't have an application that feels fully at home in iOS and Android, meaning that it has the iOS and Android styling. The majority of your logic can be written using JavaScript, which means it too can be ported between platforms. If the current PhoneGap API does most of what you want, then it's pretty easy to get up and running. If however, there are things you need from the device that are not in the API, then you get into the fun of Plugin Development, which will be in the native device's development language of choice (with one caveat, but I'll get to that), which means you would likely need to get up to speed quickly in Objective-C, Java, etc. The good thing about this model, is you can usually adapt many different native libraries to serve your purpose, and many libraries already have PhoneGap Plugins. Although you might not have much experience with these languages, there will at least be a plethora of examples to work from.

Xamarin

Xamarin.iOS and Xamarin.Android (also known as MonoTouch and MonoDroid), are designed to allow you to have one library of business logic, and use this within your application, and hook it into your UI. Because it's based on .NET 4.5, you get some awesome lambda notations, LINQ, and a whole bunch of other C# awesomeness, which can make writing your business logic less painful. The downside here is that Xamarin expects that you want to make your applications truly feel native on the device, which means that you will likely end up rewriting your UI for each platform, before hooking it together with the business logic. I have heard about MvvmCross, which is designed to make this easier for you, but I haven't really had an opportunity to look into it yet. If you are familiar with the MVVM system in C#, you may want to have a look at this. When it comes to native libraries, MonoTouch becomes interesting. MonoTouch requires a Binding library to tell your C# code how to link into the underlying Objective-C and Java code. Some of these libraries will already have bindings, but if yours doesn't, creating one can be, interesting. Xamarin has made a tool called Objective Sharpie to help with this process, and for the most part, it will get you 95% of the way there. The remaining 5% will probably take 80% of your time attempting to bind a library.

Update

As noted in the comments below, Xamarin has released Xamarin Forms which is a cross platform abstraction around the platform specific UI components. Definitely worth the look.

PhoneGap / Xamarin Hybrid

Now because I said I would get to it, the caveat mentioned in PhoneGap above, is a Hybrid approach, where you can use PhoneGap for part, and Xamarin for part. I have quite a bit of experience with this, and I would caution you against it. Highly. The problem with this, is it is such a no mans' land that if you ever run into issues, almost no one will have come close to what you're doing, and will question what you're trying to do greatly. It is doable, but it's definitely not fun.

Appcelerator Titanium

As I mentioned before, I haven't worked much with Appcelerator Titanium, So for the differences between them, I will suggest you look at Comparing Titanium and Phonegap or Comparison between Corona, Phonegap, Titanium as it has a very thorough description of the differences. Basically, it appears that though they both use JavaScript, how that JavaScript is interpreted is slightly different. With Titanium, you will be writing your JavaScript to the Titanium SDK, whereas with PhoneGap, you will write your application using the PhoneGap API. As PhoneGap is very HTML5 and JavaScript standards compliant, you can use pretty much any JavaScript libraries you want, such as JQuery. With PhoneGap your user interface will be composed of HTML and CSS. With Titanium, you will benefit from their Cross-platform XML which appears to generate Native components. This means it will definitely have a better native look and feel.

How to select the first element of a set with JSTL?

Since i have have just one element in my Set the order is not important So I can access to the first element like this :

${ attachments.iterator().next().id }

How to get a list of current open windows/process with Java?

The below program will be compatible with Java 9+ version only...

To get the CurrentProcess information,

public class CurrentProcess {
    public static void main(String[] args) {
        ProcessHandle handle = ProcessHandle.current();
        System.out.println("Current Running Process Id: "+handle.pid());
        ProcessHandle.Info info = handle.info();
        System.out.println("ProcessHandle.Info : "+info);
    }
}

For all running processes,

import java.util.List;
import java.util.stream.Collectors;

public class AllProcesses {
    public static void main(String[] args) {
        ProcessHandle.allProcesses().forEach(processHandle -> {
            System.out.println(processHandle.pid()+" "+processHandle.info());
        });
    }
}

Best approach to real time http streaming to HTML5 video client

One way to live-stream a RTSP-based webcam to a HTML5 client (involves re-encoding, so expect quality loss and needs some CPU-power):

  • Set up an icecast server (could be on the same machine you web server is on or on the machine that receives the RTSP-stream from the cam)
  • On the machine receiving the stream from the camera, don't use FFMPEG but gstreamer. It is able to receive and decode the RTSP-stream, re-encode it and stream it to the icecast server. Example pipeline (only video, no audio):

    gst-launch-1.0 rtspsrc location=rtsp://192.168.1.234:554 user-id=admin user-pw=123456 ! rtph264depay ! avdec_h264 ! vp8enc threads=2 deadline=10000 ! webmmux streamable=true ! shout2send password=pass ip=<IP_OF_ICECAST_SERVER> port=12000 mount=cam.webm
    

=> You can then use the <video> tag with the URL of the icecast-stream (http://127.0.0.1:12000/cam.webm) and it will work in every browser and device that supports webm

How to format a string as a telephone number in C#

If your looking for a (US) phone number to be converted in real time. I suggest using this extension. This method works perfectly without filling in the numbers backwards. The String.Format solution appears to work backwards. Just apply this extension to your string.

public static string PhoneNumberFormatter(this string value)
{
    value = new Regex(@"\D").Replace(value, string.Empty);
    value = value.TrimStart('1');

    if (value.Length == 0)
        value = string.Empty;
    else if (value.Length < 3)
        value = string.Format("({0})", value.Substring(0, value.Length));
    else if (value.Length < 7)
        value = string.Format("({0}) {1}", value.Substring(0, 3), value.Substring(3, value.Length - 3));
    else if (value.Length < 11)
        value = string.Format("({0}) {1}-{2}", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));
    else if (value.Length > 10)
    {
        value = value.Remove(value.Length - 1, 1);
        value = string.Format("({0}) {1}-{2}", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));
    }
    return value;
}

Git: See my last commit

git log -1 --stat

could work

Spring Boot - Handle to Hibernate SessionFactory

Great work Andreas. I created a bean version so the SessionFactory could be autowired.

import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

....

@Autowired
private EntityManagerFactory entityManagerFactory;

@Bean
public SessionFactory getSessionFactory() {
    if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
        throw new NullPointerException("factory is not a hibernate factory");
    }
    return entityManagerFactory.unwrap(SessionFactory.class);
}

Get city name using geolocation

Here is another go at it .. Adding more to the accepted answer possibly more comprehensive .. of course switch -case will make it look for elegant.

function parseGeoLocationResults(result) {
    const parsedResult = {}
    const {address_components} = result;

    for (var i = 0; i < address_components.length; i++) {
        for (var b = 0; b < address_components[i].types.length; b++) {
            if (address_components[i].types[b] == "street_number") {
                //this is the object you are looking for
                parsedResult.street_number = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "route") {
                //this is the object you are looking for
                parsedResult.street_name = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "sublocality_level_1") {
                //this is the object you are looking for
                parsedResult.sublocality_level_1 = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "sublocality_level_2") {
                //this is the object you are looking for
                parsedResult.sublocality_level_2 = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "sublocality_level_3") {
                //this is the object you are looking for
                parsedResult.sublocality_level_3 = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "neighborhood") {
                //this is the object you are looking for
                parsedResult.neighborhood = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "locality") {
                //this is the object you are looking for
                parsedResult.city = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "administrative_area_level_1") {
                //this is the object you are looking for
                parsedResult.state = address_components[i].long_name;
                break;
            }

            else if (address_components[i].types[b] == "postal_code") {
                //this is the object you are looking for
                parsedResult.zip = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "country") {
                //this is the object you are looking for
                parsedResult.country = address_components[i].long_name;
                break;
            }
        }
    }
    return parsedResult;
}

What's the difference between struct and class in .NET?

Difference between Structs and Classes:

  • Structs are value type whereas Classes are reference type.
  • Structs are stored on the stack whereas Classes are stored on the heap.
  • Value types hold their value in memory where they are declared, but reference type holds a reference to an object memory.
  • Value types destroyed immediately after the scope is lost whereas reference type only the variable destroy after the scope is lost. The object is later destroyed by the garbage collector.
  • When you copy struct into another struct, a new copy of that struct gets created modified of one struct won't affect the value of the other struct.
  • When you copy a class into another class, it only copies the reference variable.
  • Both the reference variable point to the same object on the heap. Change to one variable will affect the other reference variable.
  • Structs can not have destructors, but classes can have destructors.
  • Structs can not have explicit parameterless constructors whereas classes can. Structs don't support inheritance, but classes do. Both support inheritance from an interface.
  • Structs are sealed type.

How to detect when keyboard is shown and hidden

Swift 4:

  NotificationCenter.default.addObserver( self, selector: #selector(ControllerClassName.keyboardWillShow(_:)),
  name: Notification.Name.UIKeyboardWillShow,
  object: nil)
  NotificationCenter.default.addObserver(self, selector: #selector(ControllerClassName.keyboardWillHide(_:)),
  name: Notification.Name.UIKeyboardWillHide,
  object: nil)

Next, adding method to stop listening for notifications when the object’s life ends:-

Then add the promised methods from above to the view controller:
deinit {
  NotificationCenter.default.removeObserver(self)
}
func adjustKeyboardShow(_ open: Bool, notification: Notification) {
  let userInfo = notification.userInfo ?? [:]
  let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
  let height = (keyboardFrame.height + 20) * (open ? 1 : -1)
  scrollView.contentInset.bottom += height
  scrollView.scrollIndicatorInsets.bottom += height
}

@objc func keyboardWillShow(_ notification: Notification) {
  adjustKeyboardShow(true, notification: notification)
}
@objc func keyboardWillHide(_ notification: Notification) {
  adjustKeyboardShow(false, notification: notification)
}

What does -Xmn jvm option stands for

From here:

-Xmn : the size of the heap for the young generation

Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".

And a more "official" source from IBM:

-Xmn

Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.

Comparing boxed Long values 127 and 128

TL;DR

Java caches boxed Integer instances from -128 to 127. Since you are using == to compare objects references instead of values, only cached objects will match. Either work with long unboxed primitive values or use .equals() to compare your Long objects.

Long (pun intended) version

Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.

Java caches Integer objects instances from the range -128 to 127. That said:

  • If you set to N Long variables the value 127 (cached), the same object instance will be pointed by all references. (N variables, 1 instance)
  • If you set to N Long variables the value 128 (not cached), you will have an object instance pointed by every reference. (N variables, N instances)

That's why this:

Long val1 = 127L;
Long val2 = 127L;

System.out.println(val1 == val2);

Long val3 = 128L;
Long val4 = 128L;

System.out.println(val3 == val4);

Outputs this:

true
false

For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true.

On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false on the comparison between them.

That happens solely because you are comparing two Long object references, not long primitive values, with the == operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with == operator.

Changing these variables to primitive long types will prevent this from happening, but in case you need to keep your code using Long objects, you can safely make these comparisons with the following approaches:

System.out.println(val3.equals(val4));                     // true
System.out.println(val3.longValue() == val4.longValue());  // true
System.out.println((long)val3 == (long)val4);              // true

(Proper null checking is necessary, even for castings)

IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.

Reference links:

Python error message io.UnsupportedOperation: not readable

There are few modes to open file (read, write etc..)

If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.

more modes:

  • r. Opens a file for reading only.
  • rb. Opens a file for reading only in binary format.
  • r+ Opens a file for both reading and writing.
  • rb+ Opens a file for both reading and writing in binary format.
  • w. Opens a file for writing only.
  • you can find more modes in here

How to sort an array of objects by multiple fields?

This is a recursive algorithm to sort by multiple fields while having the chance to format values before comparison.

var data = [
{
    "id": 1,
    "ship": null,
    "product": "Orange",
    "quantity": 7,
    "price": 92.08,
    "discount": 0
},
{
    "id": 2,
    "ship": "2017-06-14T23:00:00.000Z".toDate(),
    "product": "Apple",
    "quantity": 22,
    "price": 184.16,
    "discount": 0
},
...
]
var sorts = ["product", "quantity", "ship"]

// comp_val formats values and protects against comparing nulls/undefines
// type() just returns the variable constructor
// String.lower just converts the string to lowercase.
// String.toDate custom fn to convert strings to Date
function comp_val(value){
    if (value==null || value==undefined) return null
    var cls = type(value)
    switch (cls){
        case String:
            return value.lower()
    }
    return value
}

function compare(a, b, i){
    i = i || 0
    var prop = sorts[i]
    var va = comp_val(a[prop])
    var vb = comp_val(b[prop])

    // handle what to do when both or any values are null
    if (va == null || vb == null) return true

    if ((i < sorts.length-1) && (va == vb)) {
        return compare(a, b, i+1)
    } 
    return va > vb
}

var d = data.sort(compare);
console.log(d);

If a and b are equal it will just try the next field until none is available.

Django request.GET

Here is a good way to do it.

from django.utils.datastructures import MultiValueDictKeyError
try:
    message = 'You submitted: %r' % request.GET['q']
except MultiValueDictKeyError:
    message = 'You submitted nothing!'

You don't need to check again if q is in GET request. The call in the QueryDict.get already does that to you.

display:inline vs display:block

Display : block will take the whole line i.e without line break

Display :inline will take only exact space that it requires.

 #block
  {
   display : block;
   background-color:red;
   border:1px solid;
  }

 #inline
 {
  display : inline;
  background-color:red;
  border:1px solid;
 }

You can refer example in this fiddle http://jsfiddle.net/RJXZM/1/.

Performance of Java matrix math libraries?

We have used COLT for some pretty large serious financial calculations and have been very happy with it. In our heavily profiled code we have almost never had to replace a COLT implementation with one of our own.

In their own testing (obviously not independent) I think they claim within a factor of 2 of the Intel hand-optimised assembler routines. The trick to using it well is making sure that you understand their design philosophy, and avoid extraneous object allocation.

Regular expression for a hexadecimal number?

It's worth mentioning that detecting an MD5 (which is one of the examples) can be done with:

[0-9a-fA-F]{32}

How to import multiple .csv files at once?

With many files and many cores, fread xargs cat (described below) is about 50x faster than the fastest solution in the top 3 answers.

rbindlist lapply read.delim  500s <- 1st place & accepted answer
rbindlist lapply fread       250s <- 2nd & 3rd place answers
rbindlist mclapply fread      10s
fread xargs cat                5s

Time to read 121401 csvs into a single data.table. Each time is an average of three runs then rounded. Each csv has 3 columns, one header row, and, on average, 4.510 rows. Machine is a GCP VM with 96 cores.

The top three answers by @A5C1D2H2I1M1N2O1R2T1, @leerssej, and @marbel and are all essentially the same: apply fread (or read.delim) to each file, then rbind/rbindlist the resulting data.tables. I usually use the rbindlist(lapply(list.files("*.csv"),fread)) form.

This is better than other R-internal alternatives, and fine for a small number of large csvs, but not the best for a large number of small csvs when speed matters. In that case, it can be much faster to first use cat, as @Spacedman suggests in the 4th-ranked answer. I'll add some detail on how to do this from within R:

x = fread(cmd='cat *.csv', header=F)

However, what if each csv has a header?

x = fread(cmd="awk 'NR==1||FNR!=1' *.csv", header=T)

And what if you have so many files that the *.csv shell glob fails?

x = fread(cmd='find . -name "*.csv" | xargs cat', header=F)

And what if all files have a header AND there are too many files?

header = fread(cmd='find . -name "*.csv" | head -n1 | xargs head -n1', header=T)
x = fread(cmd='find . -name "*.csv" | xargs tail -q -n+2', header=F)
names(x) = names(header)

And what if the resulting concatenated csv is too big for system memory?

system('find . -name "*.csv" | xargs cat > combined.csv')
x = fread('combined.csv', header=F)

With headers?

system('find . -name "*.csv" | head -n1 | xargs head -n1 > combined.csv')
system('find . -name "*.csv" | xargs tail -q -n+2 >> combined.csv')
x = fread('combined.csv', header=T)

Finally, what if you don't want all .csv in a directory, but rather a specific set of files? (Also, they all have headers.) (This is my use case.)

fread(text=paste0(system("xargs cat|awk 'NR==1||$1!=\"<column one name>\"'",input=paths,intern=T),collapse="\n"),header=T,sep="\t")

and this is about the same speed as plain fread xargs cat :)

Note: for data.table pre-v1.11.6 (19 Sep 2018), omit the cmd= from fread(cmd=.

Addendum: using the parallel library's mclapply in place of serial lapply, e.g., rbindlist(lapply(list.files("*.csv"),fread)) is also much faster than rbindlist lapply fread.

To sum up, if you're interested in speed, and have many files and many cores, fread xargs cat is about 50x faster than the fastest solution in the top 3 answers.

How can I listen for a click-and-hold in jQuery?

Here's my current implementation:

$.liveClickHold = function(selector, fn) {

    $(selector).live("mousedown", function(evt) {

        var $this = $(this).data("mousedown", true);

        setTimeout(function() {
            if ($this.data("mousedown") === true) {
                fn(evt);
            }
        }, 500);

    });

    $(selector).live("mouseup", function(evt) {
        $(this).data("mousedown", false);
    });

}

In Angular, What is 'pathmatch: full' and what effect does it have?

While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full does if you don't know how the router works in the first place.


Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section.

  1. It may be obvious but let's first point out that query parameters (?from=134) and fragments (#section) do not play any role in path matching. Only the base url (/users/james/articles) matters.

  2. Angular splits URLs into segments. The segments of /users/james/articles are, of course, users, james and articles.

  3. The router configuration is a tree structure with a single root node. Each Route object is a node, which may have children nodes, which may in turn have other children or be leaf nodes.

The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.

E.g. if your target URL is /a/b/c but the router is only able to match either /a/b or /a/b/c/d, then there is no match and the application will not render anything.

Finally, routes with redirectTo behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full. But we will get to this later.

Default (prefix) path matching

The reasoning behind the name prefix is that such a route configuration will check if the configured path is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.

Anyway, let's say this is our root-level router configuration:

const routes: Routes = [
  {
    path: 'products',
    children: [
      {
        path: ':productID',
        component: ProductComponent,
      },
    ],
  },
  {
    path: ':other',
    children: [
      {
        path: 'tricks',
        component: TricksComponent,
      },
    ],
  },
  {
    path: 'user',
    component: UsersonComponent,
  },
  {
    path: 'users',
    children: [
      {
        path: 'permissions',
        component: UsersPermissionsComponent,
      },
      {
        path: ':userID',
        children: [
          {
            path: 'comments',
            component: UserCommentsComponent,
          },
          {
            path: 'articles',
            component: UserArticlesComponent,
          },
        ],
      },
    ],
  },
];

Note that every single Route object here uses the default matching strategy, which is prefix. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:

  1. Iterate over the root array looking for a an exact match for the first URL segment - users.
  2. 'products' !== 'users', so skip that branch. Note that we are using an equality check rather than a .startsWith() or .includes() - only full segment matches count!
  3. :other matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james and articles), thus the router looks for children.
  • The only child of :other is tricks, which is !== 'james', hence not a match.
  1. Angular then retraces back to the root array and continues from there.
  2. 'user' !== 'users, skip branch.
  3. 'users' === 'users - the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).
  • 'permissions' !== 'james', skip it.
  • :userID matches anything, thus we have a match for the james segment. However this is still not a full match, thus we need to look for a child which would match articles.
    1. We can see that :userID has a child route articles, which gives us a full match! Thus the application renders UserArticlesComponent.

Full URL (full) matching

Example 1

Imagine now that the users route configuration object looked like this:

{
  path: 'users',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

Note the usage of pathMatch: full. If this were the case, steps 1-5 would be the same, however step 6 would be different:

  1. 'users' !== 'users/james/articles - the segment does not match because the path configuration users with pathMatch: full does not match the full URL, which is users/james/articles.
  2. Since there is no match, we are skipping this branch.
  3. At this point we reached the end of the router configuration without having found a match. The application renders nothing.

Example 2

What if we had this instead:

{
  path: 'users/:userID',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'comments',
      component: UserCommentsComponent,
    },
    {
      path: 'articles',
      component: UserArticlesComponent,
    },
  ],
}

users/:userID with pathMatch: full matches only users/james thus it's a no-match once again, and the application renders nothing.

Example 3

Let's consider this:

{
  path: 'users',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      pathMatch: 'full',
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

In this case:

  1. 'users' === 'users - the segment matches, but james/articles still remains unmatched. Let's look for children.
  • 'permissions' !== 'james' - skip.
  • :userID' can only match a single segment, which would be james. However, it's a pathMatch: full route, and it must match james/articles (the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!
  1. Again, we failed to find any match for the URL and the application renders nothing.

As you may have noticed, a pathMatch: full configuration is basically saying this:

Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.

Redirects

Any Route which has defined a redirectTo will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix strategy, a partial match is enough to cause a redirect. Here's a good example:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];

For our initial URL (/users/james/articles), here's what would happen:

  1. 'not-found' !== 'users' - skip it.
  2. 'users' === 'users' - we have a match.
  3. This match has a redirectTo: 'not-found', which is applied immediately.
  4. The target URL changes to not-found.
  5. The router begins matching again and finds a match for not-found right away. The application renders NotFoundComponent.

Now consider what would happen if the users route also had pathMatch: full:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    pathMatch: 'full',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];
  1. 'not-found' !== 'users' - skip it.
  2. users would match the first segment of the URL, but the route configuration requires a full match, thus skip it.
  3. 'users/:userID' matches users/james. articles is still not matched but this route has children.
  • We find a match for articles in the children. The whole URL is now matched and the application renders UserArticlesComponent.

Empty path (path: '')

The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'users',
        component: BadUsersComponent,
      }
    ]
  },
  {
    path: 'users',
    component: GoodUsersComponent,
  },
];

Let's say we are trying to access /users:

  • path: '' will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users!
  • We can see that there is a child users, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent.

Now back to the original question

The OP used this router configuration:

const routes: Routes = [
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
  {
    path: '**',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
];

If we are navigating to the root URL (/), here's how the router would resolve that:

  1. welcome does not match an empty segment, so skip it.
  2. path: '' matches the empty segment. It has a pathMatch: 'full', which is also satisfied as we have matched the whole URL (it had a single empty segment).
  3. A redirect to welcome happens and the application renders WelcomeComponent.

What if there was no pathMatch: 'full'?

Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }) because if you put this Route above welcome, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)

Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).

What about path: '**'?

path: '**' will match absolutely anything (af/frewf/321532152/fsa is a match) with or without a pathMatch: 'full'.

Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' } completely redundant in this setup.

Funnily enough, it is perfectly fine to have this configuration:

const routes: Routes = [
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
];

If we navigate to /welcome, path: '**' will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.

How to use css style in php

Absolute easiest way (with your current code) is to add a require_once("path/to/file") statement to your php code.

<?php
require_once("../myCSSfile.css");
echo "<table>";
...

Also, as an aside: the opening <?php tag does not have a > on the end, and the closing ?> php tag does not start with <. Weird, but true.

Possible to view PHP code of a website?

By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).

Unique device identification

I have following idea how you can deal with such Access Device ID (ADID):

Gen ADID

  • prepare web-page https://mypage.com/manager-login where trusted user e.g. Manager can login from device - that page should show button "Give access to this device"
  • when user press button, page send request to server to generate ADID
  • server gen ADID, store it on whitelist and return to page
  • then page store it in device localstorage
  • trusted user now logout.

Use device

  • Then other user e.g. Employee using same device go to https://mypage.com/statistics and page send to server request for statistics including parameter ADID (previous stored in localstorage)
  • server checks if the ADID is on the whitelist, and if yes then return data

In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.

You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.

In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain xyz.com to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.

UPDATE

Simpler approach based on links:

  • Manager login to system using any device and generate ONE-TIME USE LINK https://mypage.com/access-link/ZD34jse24Sfses3J (which works e.g. 24h).
  • Then manager send this link to employee (or someone else; e.g. by email) which put that link into device and server returns ADID to device which store it in Local Storage. After that link above stops working - so only the system and device know ADID
  • Then employee using this device can read data from https://mypage.com/statistics because it has ADID which is on servers whitelist

Remove element by id

This one actually comes from Firefox... for once, IE was ahead of the pack and allowed the removal of an element directly.

This is just my assumption, but I believe the reason that you must remove a child through the parent is due to an issue with the way Firefox handled the reference.

If you call an object to commit hari-kari directly, then immediately after it dies, you are still holding that reference to it. This has the potential to create several nasty bugs... such as failing to remove it, removing it but keeping references to it that appear valid, or simply a memory leak.

I believe that when they realized the issue, the workaround was to remove an element through its parent because when the element is gone, you are now simply holding a reference to the parent. This would stop all that unpleasantness, and (if closing down a tree node by node, for example) would 'zip-up' rather nicely.

It should be an easily fixable bug, but as with many other things in web programming, the release was probably rushed, leading to this... and by the time the next version came around, enough people were using it that changing this would lead to breaking a bunch of code.

Again, all of this is simply my guesswork.

I do, however, look forward to the day when web programming finally gets a full spring cleaning, all these strange little idiosyncracies get cleaned up, and everyone starts playing by the same rules.

Probably the day after my robot servant sues me for back wages.

How can I clear the input text after clicking

To remove the default text, on clicking the element:

$('input:text').click(
    function(){
        $(this).val('');
    });

I would, though, suggest using focus() instead:

$('input:text').focus(
    function(){
        $(this).val('');
    });

Which responds to keyboard events too (the tab key, for example). Also, you could use the placeholder attribute in the element:

<input type="text" placeholder="default text" />

Which will clear on focus of the element, and reappear if the element remains empty/user doesn't input anything.

React - Preventing Form Submission

I think it's first worth noting that without javascript (plain html), the form element submits when clicking either the <input type="submit" value="submit form"> or <button>submits form too</button>. In javascript you can prevent that by using an event handler and calling e.preventDefault() on button click, or form submit. e is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit, and the other on the button via onClick.

Example: http://jsbin.com/vowuley/edit?html,js,console,output

Laravel 5 Eloquent where and or in Clauses

When we use multiple and (where) condition with last (where + or where) the where condition fails most of the time. for that we can use the nested where function with parameters passing in that.

$feedsql = DB::table('feeds as t1')
                   ->leftjoin('groups as t2', 't1.groups_id', '=', 't2.id')
                    ->where('t2.status', 1)
                    ->whereRaw("t1.published_on <= NOW()") 
                    >whereIn('t1.groupid', $group_ids)
                   ->where(function($q)use ($userid) {
                            $q->where('t2.contact_users_id', $userid)
                            ->orWhere('t1.users_id', $userid);
                     })
                  ->orderBy('t1.published_on', 'desc')->get();

The above query validate all where condition then finally checks where t2.status=1 and (where t2.contact_users_id='$userid' or where t1.users_id='$userid')

$watch an object

Call $watch with true as the third argument:

$scope.$watch('form', function(newVal, oldVal){
    console.log('changed');
}, true);

By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal.

Per the Angular documentation, the third parameter is for objectEquality:

When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

In April 2017 a patch was merged into Safari, so it aligned with the other browsers. This was released with Safari 11.

https://bugs.webkit.org/show_bug.cgi?id=157010

Does a finally block always get executed in Java?

Yes, finally block is always execute. Most of developer use this block the closing the database connection, resultset object, statement object and also uses into the java hibernate to rollback the transaction.

Storing data into list with class

Here's the extension method version:

public static class ListOfEmailDataExtension
{
    public static void Add(this List<EmailData> list, 
        string firstName, string lastName, string location)
    {
        if (null == list)
            throw new NullReferenceException();

        var emailData = new EmailData
                            {
                                FirstName = firstName, 
                                LastName = lastName, 
                                Location = location
                            };
        list.Add(emailData);
    }
}

Usage:

List<EmailData> myList = new List<EmailData>();
myList.Add("Ron", "Klein", "Israel");

Android Dialog: Removing title bar

This worked for me.

Dailog dialog = new Dialog(MyActivity.this, R.style.dialogstyle);

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="dialogstyle" parent="android:style/Theme.Dialog">
        <item name="android:windowBackground">@null</item>
        <item name="android:windowNoTitle">false</item>
    </style>
</resources>

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

I need to convert an int variable to double

I think you should casting variable or use Integer class by call out method doubleValue().

Collision resolution in Java HashMap

Your case is not talking about collision resolution, it is simply replacement of older value with a new value for the same key because Java's HashMap can't contain duplicates (i.e., multiple values) for the same key.

In your example, the value 17 will be simply replaced with 20 for the same key 10 inside the HashMap.

If you are trying to put a different/new value for the same key, it is not the concept of collision resolution, rather it is simply replacing the old value with a new value for the same key. It is how HashMap has been designed and you can have a look at the below API (emphasis is mine) taken from here.

public V put(K key, V value)

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.


On the other hand, collision resolution techniques comes into play only when multiple keys end up with the same hashcode (i.e., they fall in the same bucket location) where an entry is already stored. HashMap handles the collision resolution by using the concept of chaining i.e., it stores the values in a linked list (or a balanced tree since Java8, depends on the number of entries).

How to abort makefile if variable not set?

You can use an IF to test:

check:
        @[ "${var}" ] || ( echo ">> var is not set"; exit 1 )

Result:

$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1

Generating random integer from a range

The simplest (and hence best) C++ (using the 2011 standard) answer is

#include <random>

std::random_device rd;     // only used once to initialise (seed) engine
std::mt19937 rng(rd());    // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased

auto random_integer = uni(rng);

No need to re-invent the wheel. No need to worry about bias. No need to worry about using time as random seed.

Python list iterator behavior and next(iterator)

What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    next(a)
... 
0
1
2
3
4
5
6
7
8
9

So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.

If you assign the output of next() things work as expected:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    _ = next(a)
... 
0
2
4
6
8

or print extra information to differentiate the print() output from the interactive interpreter echo:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print('Printing: {}'.format(i))
...    next(a)
... 
Printing: 0
1
Printing: 2
3
Printing: 4
5
Printing: 6
7
Printing: 8
9

In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.

Using PHP variables inside HTML tags?

You can do it a number of ways, depending on the type of quotes you use:

  • echo "<a href='http://www.whatever.com/$param'>Click here</a>";
  • echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
  • echo '<a href="http://www.whatever.com/' . $param . '">Click here</a>';
  • echo "<a href=\"http://www.whatever.com/$param\">Click here</a>";

Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n will be expanded to mean the new line character, it will just be the characters \ and n in sequence.

You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.

On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.

How to set Internet options for Android emulator?

Add GSM Modem Support while creating AVD in your virtual devices from Android SDK and AVD Manager...

PHP include relative path

You could always include it using __DIR__:

include(dirname(__DIR__).'/config.php');

__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.

include(ROOT_PATH.'config.php');

Should then work to include the config file from where you want.

POSTing JSON to URL via WebClient in C#

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

var vm = new { k = "1", a = "2", c = "3", v=  "4" };
using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(vm);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}

Prerequisites: Json.NET library

What Language is Used To Develop Using Unity

i remember this from reading some articles about performance in unity from internet which awaring javascript users from using it in unity about really massive issues of using javascript in unity instead of C#, it says that C# is almost 4x faster than javascript!
i really appreciate that article b/c it saved my ass when i was about to start gaming, i dont mean that javascript it bad for unity developers , it is good but my advice could be that if you like using javascript, you should use it for simple small gamesNOT FOR BIG PROJECTS because it really can be a damn problem!

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

How can I get the error message for the mail() function?

If you are on Windows using SMTP, you can use error_get_last() when mail() returns false. Keep in mind this does not work with PHP's native mail() function.

$success = mail('[email protected]', 'My Subject', $message);
if (!$success) {
    $errorMessage = error_get_last()['message'];
}

With print_r(error_get_last()), you get something like this:

[type] => 2
[message] => mail(): Failed to connect to mailserver at "x.x.x.x" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
[file] => C:\www\X\X.php
[line] => 2

Difference between filter and filter_by in SQLAlchemy

We actually had these merged together originally, i.e. there was a "filter"-like method that accepted *args and **kwargs, where you could pass a SQL expression or keyword arguments (or both). I actually find that a lot more convenient, but people were always confused by it, since they're usually still getting over the difference between column == expression and keyword = expression. So we split them up.

JUnit Eclipse Plugin?

Eclipse has built in JUnit functionality. Open your Run Configuration manager to create a test to run. You can also create JUnit Test Cases/Suites from New->Other.

RegEx for matching "A-Z, a-z, 0-9, _" and "."

Working from what you've given I'll assume you want to check that someone has NOT entered any letters other than the ones you've listed. For that to work you want to search for any characters other than those listed:

[^A-Za-z0-9_.]

And use that in a match in your code, something like:

if ( /[^A-Za-z0-9_.]/.match( your_input_string ) ) {
   alert( "you have entered invalid data" );
}

Hows that?

SQL Server - How to lock a table until a stored procedure finishes

Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

Why is there an unexplainable gap between these inline-block div elements?

Using inline-block allows for white-space in your HTML, This usually equates to .25em (or 4px).

You can either comment out the white-space or, a more commons solution, is to set the parent's font-size to 0 and the reset it back to the required size on the inline-block elements.

javac error: Class names are only accepted if annotation processing is explicitly requested

How you can reproduce this cryptic error on the Ubuntu terminal:

Put this in a file called Main.java:

public Main{
    public static void main(String[] args){
        System.out.println("ok");
    }
}

Then compile it like this:

user@defiant /home/user $ javac Main
error: Class names, 'Main', are only accepted if 
annotation processing is explicitly requested
1 error

It's because you didn't specify .java at the end of Main.

Do it like this, and it works:

user@defiant /home/user $ javac Main.java
user@defiant /home/user $

Slap your forehead now and grumble that the error message is so cryptic.

ng-repeat finish event

Maybe a bit simpler approach with ngInit and Lodash's debounce method without the need of custom directive:

Controller:

$scope.items = [1, 2, 3, 4];

$scope.refresh = _.debounce(function() {
    // Debounce has timeout and prevents multiple calls, so this will be called 
    // once the iteration finishes
    console.log('we are done');
}, 0);

Template:

<ul>
    <li ng-repeat="item in items" ng-init="refresh()">{{item}}</li>
</ul>

Update

There is even simpler pure AngularJS solution using ternary operator:

Template:

<ul>
    <li ng-repeat="item in items" ng-init="$last ? doSomething() : null">{{item}}</li>
</ul>

Be aware that ngInit uses pre-link compilation phase - i.e. the expression is invoked before child directives are processed. This means that still an asynchronous processing might be required.

How to go back (ctrl+z) in vi/vim

The answer, u, (and many others) is in $ vimtutor.

What is the difference between pip and conda?

Here is a short rundown:

pip

  • Python packages only.
  • Compiles everything from source. EDIT: pip now installs binary wheels, if they are available.
  • Blessed by the core Python community (i.e., Python 3.4+ includes code that automatically bootstraps pip).

conda

  • Python agnostic. The main focus of existing packages are for Python, and indeed Conda itself is written in Python, but you can also have Conda packages for C libraries, or R packages, or really anything.
  • Installs binaries. There is a tool called conda build that builds packages from source, but conda install itself installs things from already built Conda packages.
  • External. Conda is the package manager of Anaconda, the Python distribution provided by Continuum Analytics, but it can be used outside of Anaconda too. You can use it with an existing Python installation by pip installing it (though this is not recommended unless you have a good reason to use an existing installation).

In both cases:

  • Written in Python
  • Open source (Conda is BSD and pip is MIT)

The first two bullet points of Conda are really what make it advantageous over pip for many packages. Since pip installs from source, it can be painful to install things with it if you are unable to compile the source code (this is especially true on Windows, but it can even be true on Linux if the packages have some difficult C or FORTRAN library dependencies). Conda installs from binary, meaning that someone (e.g., Continuum) has already done the hard work of compiling the package, and so the installation is easy.

There are also some differences if you are interested in building your own packages. For instance, pip is built on top of setuptools, whereas Conda uses its own format, which has some advantages (like being static, and again, Python agnostic).

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

Return rows in random order

To be efficient, and random, it might be best to have two different queries.

Something like...

SELECT table_id FROM table

Then, in your chosen language, pick a random id, then pull that row's data.

SELECT * FROM table WHERE table_id = $rand_id

But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.

Editor does not contain a main type

What you should do is, create a Java Project, but make sure you put this file in the package file of that project, otherwise you'll encounter same error.

enter image description here

Override body style for content in an iframe

Perhaps it's changed now, but I have used a separate stylesheet with this element:

.feedEkList iframe
{
max-width: 435px!important;
width: 435px!important;
height: 320px!important;
}

to successfully style embedded youtube iframes...see the blog posts on this page.

Volley JsonObjectRequest Post request not working

When you working with JsonObject request you need to pass the parameters right after you pass the link in the initialization , take a look on this code :

        HashMap<String, String> params = new HashMap<>();
        params.put("user", "something" );
        params.put("some_params", "something" );

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "request_URL", new JSONObject(params), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

           // Some code 

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //handle errors
        }
    });


}

Get Application Directory

PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;

If eclipse worries about an uncaught NameNotFoundException, you can use:

PackageManager m = getPackageManager();
String s = getPackageName();
try {
    PackageInfo p = m.getPackageInfo(s, 0);
    s = p.applicationInfo.dataDir;
} catch (PackageManager.NameNotFoundException e) {
    Log.w("yourtag", "Error Package name not found ", e);
}

Could not load NIB in bundle

In my case it was very weird (use a storyboard): For some reason it changed from "Main storyboard file base name" to "Main nib file base name" in the plist.

Changing back to "Main storyboard file base name" (UIMainStoryboardFile) solved the issue

Get device token for push notification

In a build setting set code signing Provision Profile if you have APN Enable certificate then you will definitely get the token id. and remove

Provision Profile : Automatic

and set to

Provision Profile : Your provision profile certificate.

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

Parse a URI String into Name-Value Collection

If you are using Spring Framework:

public static void main(String[] args) {
    String uri = "http://my.test.com/test?param1=ab&param2=cd&param2=ef";
    MultiValueMap<String, String> parameters =
            UriComponentsBuilder.fromUriString(uri).build().getQueryParams();
    List<String> param1 = parameters.get("param1");
    List<String> param2 = parameters.get("param2");
    System.out.println("param1: " + param1.get(0));
    System.out.println("param2: " + param2.get(0) + "," + param2.get(1));
}

You will get:

param1: ab
param2: cd,ef

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP If Statement with Multiple Conditions

you can use in_array function of php

$array=array('abc', 'def', 'hij', 'klm', 'nop');

if (in_array($val,$array))
{
  echo 'Value found';
}

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

How to use Fiddler to monitor WCF service

Fiddler listens to outbound requests rather than inbound requests so you're not going to be able to monitor all the requests coming in to your service by using Fiddler.

The best you're going to get with Fiddler is the ability to see all of the requests as they are generated by your Console App (assuming that the app generates web requests rather than using some other pipeline).

If you want a tool that is more powerful (but more difficult to use) that will allow you to monitor ALL incoming requests, you should check out WireShark.

Edit

I stand corrected. Thanks to Eric Law for posting the directions to configuring Fiddler to be a reverse proxy!

Docker CE on RHEL - Requires: container-selinux >= 2.9

You have already have container-selinux installed for version 3.7 check if the following docker-ce version works for you , it did for me.

sudo yum -y install docker-ce-cli.x86_64 1:19.03.5-3.el7

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

ASP MVC href to a controller/view

You can modify with the following

<li><a href="./Index" class="elements"><span>Clients</span></a></li>

The extra dot means you are in the same controller. If you want change the controller to a different controller then you can write this

<li><a href="../newController/Index" class="elements"><span>Clients</span></a></li>

ojdbc14.jar vs. ojdbc6.jar

Also, from ojdbc14 to ojdbc6, several types (e.g., OracleResultSet, OracleStatement) moved from package oracle.jdbc.driver to oracle.jdbc.

Difference of two date time in sql server

Please check below trick to find the date difference between two dates

 DATEDIFF(DAY,ordr.DocDate,RDR1.U_ProgDate) datedifff

where you can change according your requirement as you want difference of days or month or year or time.

How to export html table to excel using javascript

I try this with jquery; use this and have fun :D

    jQuery.printInExcel = function (DivID) 
{ 
var ExcelApp = new ActiveXObject("Excel.Application"); 
ExcelApp.Workbooks.Add; 
ExcelApp.visible = true; 
var str = ""; 
var tblcount = 0; 
var trcount = 0;
 $("#" + DivID + " table").each(function () 
{ $(this).find("tr").each(function () 
{ var tdcount = 0; $(this).find("td").each(function () 
{ str = str + $(this).text(); ExcelApp.Cells(trcount + 1, tdcount + 1).Value = str; 
str = ""; tdcount++ 
}); 
trcount++ 
}); tblcount++ 
}); 
};

use this in your class and call it with $.printInExcel(your var);

SpringApplication.run main method

Using:

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);  

        //do your ReconTool stuff
    }
}

will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.

Using maven just use mvn spring-boot:run

while in gradle it would be gradle bootRun

An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner. That would look like:

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
       //implement your business logic here
    }
}

Check out this guide from Spring's official guide repository.

The full Spring Boot documentation can be found here

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;
    }
}

How to increase size of DOSBox window?

For using DOSBox with SDL, you will need to set or change the following:

[sdl]
windowresolution=1280x960
output=opengl

Here is three options to put those settings:

  1. Edit user's default configuration, for example, using vi:

    $ dosbox -printconf
    /home/USERNAME/.dosbox/dosbox-0.74.conf
    $ vi "$(dosbox -printconf)"
    $ dosbox
    
  2. For temporary resize, create a new configuration with the three lines above, say newsize.conf:

    $ dosbox -conf newsize.conf
    

    You can use -conf to load multiple configuration and/or with -userconf for default configuration, for example:

    $ dosbox -userconf -conf newsize.conf 
    [snip]
    ---
    CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
    CONFIG:Loading additional settings from config file newsize.conf
    [snip]
    
  3. Create a dosbox.conf under current directory, DOSBox loads it as default.

DOSBox should start up and resize to 1280x960 in this case.

Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.

How do I export html table data as .csv file?

I was able to use the answer outlined here: Export to CSV using jQuery and html and added in a modification to make it work in IE and another modification mentioned in the comments to grab the thead from the table.

function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td),tr:has(th)'),

        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character

        // actual delimiter characters for CSV format
        colDelim = '","',
        rowDelim = '"\r\n"',

        // Grab text from table into CSV formatted string
        csv = '"' + $rows.map(function (i, row) {
            var $row = $(row), $cols = $row.find('td,th');

            return $cols.map(function (j, col) {
                var $col = $(col), text = $col.text();

                return text.replace(/"/g, '""'); // escape double quotes

            }).get().join(tmpColDelim);

        }).get().join(tmpRowDelim)
            .split(tmpRowDelim).join(rowDelim)
            .split(tmpColDelim).join(colDelim) + '"',



        // Data URI
        csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

        console.log(csv);

        if (window.navigator.msSaveBlob) { // IE 10+
            //alert('IE' + csv);
            window.navigator.msSaveOrOpenBlob(new Blob([csv], {type: "text/plain;charset=utf-8;"}), "csvname.csv")
        } 
        else {
            $(this).attr({ 'download': filename, 'href': csvData, 'target': '_blank' }); 
        }
}

// This must be a hyperlink
$("#xx").on('click', function (event) {

    exportTableToCSV.apply(this, [$('#projectSpreadsheet'), 'export.csv']);

    // IF CSV, don't do event.preventDefault() or return false
    // We actually need this to be a typical hyperlink
});

With my link looking like this...

<a href="#" id="xx" style="text-decoration:none;color:#000;background-color:#ddd;border:1px solid #ccc;padding:8px;">Export Table data into Excel</a>

JsFiddle: https://jsfiddle.net/mnsinger/65hqxygo/

How to disable <br> tags inside <div> by css?

<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic &amp; modern design.</span></p>

Remove <br> effect using CSS.

<style> p br{ display:none; } </style>

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

NumPy array initialization (fill with identical values)

You can use numpy.tile, e.g. :

v = 7
rows = 3
cols = 5
a = numpy.tile(v, (rows,cols))
a
Out[1]: 
array([[7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7]])

Although tile is meant to 'tile' an array (instead of a scalar, as in this case), it will do the job, creating pre-filled arrays of any size and dimension.

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

Toolbar navigation icon never set

work for me...

<android.support.v7.widget.Toolbar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/toolBar"
        android:background="@color/colorGreen"
        app:title="Title"
        app:titleTextColor="@color/colorBlack"
        app:navigationIcon="@drawable/ic_action_back"/>

Android studio takes too much memory

I have used all of Sam's recommendations above, but I found that the VM command line options are no longer supported as described. (I received an error when used)

As an alternative, I was able to reduce gradle dramatically by adding the following line to the "gradle.properties" file

org.gradle.jvmargs=-Xms512m -Xmx1024m

As of A.S. ver 1.3, the file is located in the same folder level as "gradle.build".

The above configuration is a "memory stack" of 512 meg, and "memory heap" of 1024 meg.

I tested this on a small project, using settings where both memory sizes were set to 256 meg. It limited the JVM sizes as expected. In all my tests, I restarted A.S. to force the JVM to restart.

Hopefully, this will save others dealing with this issue from getting those "Get yourself a better computer" responses. :-)

Dilber

how does Request.QueryString work?

The QueryString collection is used to retrieve the variable values in the HTTP query string.

The HTTP query string is specified by the values following the question mark (?), like this:

Link with a query string

The line above generates a variable named txt with the value "this is a query string test".

Query strings are also generated by form submission, or by a user typing a query into the address bar of the browser.

And see this sample : http://www.codeproject.com/Articles/5876/Passing-variables-between-pages-using-QueryString

refer this : http://www.dotnetperls.com/querystring

you can collect More details in google .

css overflow - only 1 line of text

I had the same issue and I solved it by using:

display: inline-block;

on the div in question.

How to sort a data frame by alphabetic order of a character variable in R?

Use order function:

set.seed(1)
DF <- data.frame(ID= sample(letters[1:26], 15, TRUE),
                 num = sample(1:100, 15, TRUE),
                 random = rnorm(15),
                 stringsAsFactors=FALSE)
DF[order(DF[,'ID']), ]
   ID num      random
10  b  27  0.61982575
12  e   2 -0.15579551
5   f  78  0.59390132
11  f  39 -0.05612874
1   g  50 -0.04493361
2   j  72 -0.01619026
14  j  87 -0.47815006
3   o 100  0.94383621
9   q  13 -1.98935170
8   r  66  0.07456498
13  r  39 -1.47075238
15  u  35  0.41794156
4   x  39  0.82122120
6   x  94  0.91897737
7   y  22  0.78213630

Another solution would be using orderByfunction from doBy package:

> library(doBy)
> orderBy(~ID, DF)

How to match letters only using java regex, matches method?

"[a-zA-Z]" matches only one character. To match multiple characters, use "[a-zA-Z]+".

Since a dot is a joker for any character, you have to mask it: "abc\." To make the dot optional, you need a question mark: "abc\.?"

If you write the Pattern as literal constant in your code, you have to mask the backslash:

System.out.println ("abc".matches ("abc\\.?"));
System.out.println ("abc.".matches ("abc\\.?"));
System.out.println ("abc..".matches ("abc\\.?"));

Combining both patterns:

System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));

Instead of a-zA-Z, \w is often more appropriate, since it captures foreign characters like äöüßø and so on:

System.out.println ("abc.".matches ("\\w+\\.?"));   

Why is IoC / DI not common in Python?

IoC/DI is a design concept, but unfortunately it's often taken as a concept that applies to certain languages (or typing systems). I'd love to see dependency injection containers become far more popular in Python. There's Spring, but that's a super-framework and seems to be a direct port of the Java concepts without much consideration for "The Python Way."

Given Annotations in Python 3, I decided to have a crack at a full featured, but simple, dependency injection container: https://github.com/zsims/dic . It's based on some concepts from a .NET dependency injection container (which IMO is fantastic if you're ever playing in that space), but mutated with Python concepts.

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

In order to resolve this issue make all your data flow tasks in one sequence. It means it should not execute parallel. One data flow task sequence should contain only one data flow task and for this another data flow task as sequence.

Ex:-

enter image description here

What does double question mark (??) operator mean in PHP

$myVar = $someVar ?? 42;

Is equivalent to :

$myVar = isset($someVar) ? $someVar : 42;

For constants, the behaviour is the same when using a constant that already exists :

define("FOO", "bar");
define("BAR", null);

$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";

echo $MyVar . PHP_EOL;  // bar
echo $MyVar2 . PHP_EOL; // 42

However, for constants that don't exist, this is different :

$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL;       // IDONTEXIST

Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)

Php will convert the non-existing constant to a string.

You can use constant("ConstantName") that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @ to ignore the warning message :

$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42

How to change style of a default EditText

I solved the same issue 10 minutes ago, so I will give you a short effective fix: Place this inside the application tag or your manifest:

 android:theme="@android:style/Theme.Holo"

Also set the Theme of your XML layout to Holo, in the layout's graphical view.

Libraries will be useful if you need to change more complicated theme stuff, but this little fix will work, so you can move on with your app.

Variable is accessed within inner class. Needs to be declared final

    public class ConfigureActivity extends Activity {

        EditText etOne;
        EditText etTwo;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_configure);

            Button btnConfigure = findViewById(R.id.btnConfigure1);   
            btnConfigure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            configure();
                        }
                    });
    }

    public  void configure(){
            String one = etOne.getText().toString();
            String two = etTwo.getText().toString();
    }
}

Conveniently map between enum and int / String

I'm not sure if it's the same in Java, but enum types in C are automatically mapped to integers as well so you can use either the type or integer to access it. Have you tried simply accessing it with integer yet?

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

You should only use &rsquo; if your intention is to make either a closed single quotation mark or an apostrophe. Both of these punctuation marks are curved in shape in most fonts. If your intent is to make a foot mark, go the other route. A foot mark is always a straight vertical mark.

It’s a matter of typography. One way is correct; the other is not.

Environment variables in Jenkins

What ultimately worked for me was the following steps:

  1. Configure the Environment Injector Plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
  2. Goto to the /job//configure screen
  3. In Build Environment section check "Inject environment variables to the build process"
  4. In "Properties Content" specified: TZ=America/New_York

PHP Warning: PHP Startup: ????????: Unable to initialize module

This happened to me when I tried to install a newer version of PHP. After finding that I also would need to reconfigure Apache for that I switched back to the old PHP version. Here the solution which worked for me:

change the httpd.conf to the correct versions:

 PHPIniDir ...
 LoadModule php5_module ...

Changed the

PATH - Environment Variable

When that does not take any effect

rename or delete the new PHP(-Version)-Folder

For some reason the last step did the trick for me. Even after a restart it did not have an effect before doing this.

How to get position of a certain element in strings vector, to use it as an index in ints vector?

I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }

I need to round a float to two decimal places in Java

You can make use of DecimalFormat to give you the style you wish.

DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number));  // prints 1.30E7

Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.

How to set data attributes in HTML elements

To keep jQuery and the DOM in sync, a simple option may be

$('#mydiv').data('myval',20).attr('data-myval',20);        

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Migrator cannot identify all the functions that need @objc Inferred Objective-C thunks marked as deprecated to help you find them
• Build warnings about deprecated methods
• Console messages when running deprecated thunks

enter image description here

How to use a client certificate to authenticate and authorize in a Web API

Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send

System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:

Here is what the trace log looked like on the machine where the client certificate failed.

System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.

Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL

Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)

After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.

How to create a timeline with LaTeX?

The tikz package seems to have what you want.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}

\begin{document}

  \begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm]
    % draw horizontal line   
    \draw (0,0) -- (2,0);
    \draw[snake] (2,0) -- (4,0);
    \draw (4,0) -- (5,0);
    \draw[snake] (5,0) -- (7,0);

    % draw vertical lines
    \foreach \x in {0,1,2,4,5,7}
      \draw (\x cm,3pt) -- (\x cm,-3pt);

    % draw nodes
    \draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$   $};
    \draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};
    \draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};
    \draw (3,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};
    \draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};
    \draw (6,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};
  \end{tikzpicture}

\end{document}

I'm not too expert with tikz, but this does give a good timeline, which looks like:

enter image description here

.jar error - could not find or load main class

Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from

"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*

to

"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*

(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.

I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).

Android emulator shows nothing except black screen and adb devices shows "device offline"

This is a known bug if you selected "Use host GPU" option while creating AVD. https://code.google.com/p/android/issues/detail?id=28614
Uncheck the option and it should work!

Concatenating variables and strings in React

You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id} - you need to indicate which are variables and which are string literals. Since anything inside {} is an inline JSX expression, you can do:

href={"#demo" + this.state.id}

This will use the string literal #demo and concatenate it to the value of this.state.id. This can then be applied to all strings. Consider this:

var text = "world";

And this:

{"Hello " + text + " Andrew"}

This will yield:

Hello world Andrew 

You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr} (interpolated expression), which is closer to what you seem to be trying to do:

href={`#demo${this.state.id}`}

This will basically substitute the value of this.state.id, concatenating it to #demo. It is equivalent to doing: "#demo" + this.state.id.

How to do a https request with bad certificate?

If you want to use the default settings from http package, so you don't need to create a new Transport and Client object, you can change to ignore the certificate verification like this:

tr := http.DefaultTransport.(*http.Transport)
tr.TLSClientConfig.InsecureSkipVerify = true

How to execute a java .class from the command line

My situation was a little complicated. I had to do three steps since I was using a .dll in the resources directory, for JNI code. My files were

S:\Accessibility\tools\src\main\resources\dlls\HelloWorld.dll
S:\Accessibility\tools\src\test\java\com\accessibility\HelloWorld.class

My code contained the following line

System.load(HelloWorld.class.getResource("/dlls/HelloWorld.dll").getPath());

First, I had to move to the classpath directory

cd /D "S:\Accessibility\tools\src\test\java"

Next, I had to change the classpath to point to the current directory so that my class would be loaded and I had to change the classpath to point to he resources directory so my dll would be loaded.

set classpath=%classpath%;.;..\..\..\src\main\resources; 

Then, I had to run java using the classname.

java com.accessibility.HelloWorld 

How do I center an anchor element in CSS?

style="margin:0 auto; width:auto;" Try that.

Why doesn't catching Exception catch RuntimeException?

The premise of the question is flawed, because catching Exception does catch RuntimeException. Demo code:

public class Test {
    public static void main(String[] args) {
        try {
            throw new RuntimeException("Bang");
        } catch (Exception e) {
            System.out.println("I caught: " + e);
        }
    }
}

Output:

I caught: java.lang.RuntimeException: Bang

Your loop will have problems if:

  • callbacks is null
  • anything modifies callbacks while the loop is executing (if it were a collection rather than an array)

Perhaps that's what you're seeing?

Handling null values in Freemarker

If you have a lot of variables to convert in optional, you can use SubimeText with this:

Find: \${([A-Za-z_0-9]*)}
Replace: \$\{${1}!\}

Be sure regex and case-sensitive options are enabled:

Sublime regex replace

Android Studio not showing modules in project structure

Update 19 March 2019

A new experience someone has just faced recently even though he/she did add a library module in app module, and include in Setting gradle as described below. One more thing worth trying is to make sure your app module and your library module have the same compileSdkVersion (which is in each its gradle)!

Please follow this link for more details.

Ref: Imported module in Android Studio can't find imported class

Original answer

Sometimes you use import module function, then the module does appear in Project mode but not in Android mode

enter image description here

enter image description here So the thing works for me is to go to Setting gradle, add my module manually, and sync a gradle again:

enter image description here

Eclipse error: 'Failed to create the Java Virtual Machine'

You can also solve this issue by removing the value "256m" under the line "-launcher.XXMaxPermSize”.

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

I have this version about datetimepicker https://tempusdominus.github.io/bootstrap-4/ and for any reason doesn`t work the change event with jquery but with JS vanilla it does

I figure out like this

document.getElementById('date').onchange = function(){ ...the jquery code...}

I hope work for you

CardView background color always white

Kotlin for XML

app:cardBackgroundColor="@android:color/red"

code

cardName.setCardBackgroundColor(ContextCompat.getColor(this, R.color.colorGray));

CSS word-wrapping in div

I found that word-wrap: anywhere worked (as opposed to word-wrap: break-word mentioned in another answer).

See also:

What does "anywhere" mean in "word-wrap" css property?

Correct way to convert size in bytes to KB, MB, GB in JavaScript

I just wanted to share my input. I had this problem so my solution is this. This will convert lower units to higher units and vice versa just supply the argument toUnit and fromUnit

export function fileSizeConverter(size: number, fromUnit: string, toUnit: string ): number | string {
  const units: string[] = ['B', 'KB', 'MB', 'GB', 'TB'];
  const from = units.indexOf(fromUnit.toUpperCase());
  const to = units.indexOf(toUnit.toUpperCase());
  const BASE_SIZE = 1024;
  let result: number | string = 0;

  if (from < 0 || to < 0 ) { return result = 'Error: Incorrect units'; }

  result = from < to ? size / (BASE_SIZE ** to) : size * (BASE_SIZE ** from);

  return result.toFixed(2);
}

I got the idea from here

A KeyValuePair in Java

I've published a NameValuePair class in GlobalMentor's core library, available in Maven. This is an ongoing project with a long history, so please submit any request for changes or improvements.

GDB: Listing all mapped memory regions for a crashed process

I have just seen the following:

set mem inaccessible-by-default [on|off]

here

It might allow you to search without regard if the memory is accessible.

How to provide password to a command that prompts for one in bash?

How to use autoexpect to pipe a password into a command:

These steps are illustrated with an Ubuntu 12.10 desktop. The exact commands for your distribution may be slightly different.

This is dangerous because you risk exposing whatever password you use to anyone who can read the autoexpect script file.

DO NOT expose your root password or power user passwords by piping them through expect like this. Root kits WILL find this in an instant and your box is owned.

EXPECT spawns a process, reads text that comes in then sends text predefined in the script file.

  1. Make sure you have expect and autoexpect installed:

    sudo apt-get install expect
    sudo apt-get install expect-dev
    
  2. Read up on it:

    man expect
    man autoexpect
    
  3. Go to your home directory:

    cd /home/el
    
  4. User el cannot chown a file to root and must enter a password:

    touch testfile.txt
    sudo chown root:root testfile.txt 
       [enter password to authorize the changing of the owner]
    
  5. This is the password entry we want to automate. Restart the terminal to ensure that sudo asks us for the password again. Go to /home/el again and do this:

    touch myfile.txt
    
    autoexpect -f my_test_expect.exp sudo chown root:root myfile.txt
    
        [enter password which authorizes the chown to root]
    
    autoexpect done, file is my_test_expect.exp
    
  6. You have created my_test_expect.exp file. Your super secret password is stored plaintext in this file. This should make you VERY uncomfortable. Mitigate some discomfort by restricting permissions and ownership as much as possible:

    sudo chown el my_test_expect.exp     //make el the owner.
    sudo chmod 700 my_test_expect.exp    //make file only readable by el.
    
  7. You see these sorts of commands at the bottom of my_test_expect.exp:

    set timeout -1
    spawn sudo chown root:root myfile.txt
    match_max 100000
    expect -exact "\[sudo\] password for el: "
    send -- "YourPasswordStoredInPlaintext\r"
    expect eof
    
  8. You will need to verify that the above expect commands are appropriate. If the autoexpect script is being overly sensitive or not sensitive enough then it will hang. In this case it's acceptable because the expect is waiting for text that will always arrive.

  9. Run the expect script as user el:

    expect my_test_expect.exp 
    spawn sudo chown root:root myfile.txt
    [sudo] password for el: 
    
  10. The password contained in my_test_expect.exp was piped into a chown to root by user el. To see if the password was accepted, look at myfile.txt:

    ls -l
    -rw-r--r--  1 root root          0 Dec  2 14:48 myfile.txt
    

It worked because it is root, and el never entered a password. If you expose your root, sudo, or power user password with this script, then acquiring root on your box will be easy. Such is the penalty for a security system that lets everybody in no questions asked.

Getting the current Fragment instance in the viewpager

This is more future-proof than the accepted answer:

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    /* ------------------------------------------------------------------------------------------ */
    // region Private attributes :

    private Context _context;
    private FragmentManager _fragmentManager;
    private Map<Integer, String> _fragmentsTags = new HashMap<>();

    // endregion
    /* ------------------------------------------------------------------------------------------ */



    /* ------------------------------------------------------------------------------------------ */
    // region Constructor :

    public MyFragmentPagerAdapter(Context context, FragmentManager fragmentManager) {

        super(fragmentManager);

        _context = context;
        _fragmentManager = fragmentManager;
    }

    // endregion
    /* ------------------------------------------------------------------------------------------ */



    /* ------------------------------------------------------------------------------------------ */
    // region FragmentPagerAdapter methods :

    @Override
    public int getCount() { return 2; }

    @Override
    public Fragment getItem(int position) {

        if(_fragmentsTags.containsKey(position)) {

            return _fragmentManager.findFragmentByTag(_fragmentsTags.get(position));
        }
        else {

            switch (position) {

                case 0 : { return Fragment.instantiate(_context, Tab1Fragment.class.getName()); }
                case 1 : { return Fragment.instantiate(_context, Tab2Fragment.class.getName()); }
            }
        }

        return null;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        // Instantiate the fragment and get its tag :
        Fragment result = (Fragment) super.instantiateItem(container, position);
        _fragmentsTags.put(position, result.getTag());

        return result;
    }

    // endregion
    /* ------------------------------------------------------------------------------------------ */
}

Spring Boot @autowired does not work, classes in different package

Spring Boot will handle those repositories automatically as long as they are included in the same package (or a sub-package) of your @SpringBootApplication class. For more control over the registration process, you can use the @EnableMongoRepositories annotation. spring.io guides

@SpringBootApplication
@EnableMongoRepositories(basePackages = {"RepositoryPackage"})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

how to open *.sdf files?

It can be opened using Visual Studio 2012.Follow the below path in VS after opening the project. View->Server Explorer->

enter image description here

When to use DataContract and DataMember attributes?

In terms of WCF, we can communicate with the server and client through messages. For transferring messages, and from a security prospective, we need to make a data/message in a serialized format.

For serializing data we use [datacontract] and [datamember] attributes. In your case if you are using datacontract WCF uses DataContractSerializer else WCF uses XmlSerializer which is the default serialization technique.

Let me explain in detail:

basically WCF supports 3 types of serialization:

  1. XmlSerializer
  2. DataContractSerializer
  3. NetDataContractSerializer

XmlSerializer :- Default order is Same as class

DataContractSerializer/NetDataContractSerializer :- Default order is Alphabetical

XmlSerializer :- XML Schema is Extensive

DataContractSerializer/NetDataContractSerializer :- XML Schema is Constrained

XmlSerializer :- Versioning support not possible

DataContractSerializer/NetDataContractSerializer :- Versioning support is possible

XmlSerializer :- Compatibility with ASMX

DataContractSerializer/NetDataContractSerializer :- Compatibility with .NET Remoting

XmlSerializer :- Attribute not required in XmlSerializer

DataContractSerializer/NetDataContractSerializer :- Attribute required in this serializing

so what you use depends on your requirements...

How to get selected value of a dropdown menu in ReactJS

import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
      />
    );
  }
}

And you can check it out on this site.

javax.naming.NoInitialContextException - Java

If working on EJB client library:

You need to mention the argument for getting the initial context.

InitialContext ctx = new InitialContext();

If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");

InitialContext ctx = new InitialContext(props);

URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.

The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.

Get input type="file" value when it has multiple files selected

You use input.files property. It's a collection of File objects and each file has a name property:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"

How to write to an existing excel file without overwriting data (using pandas)?

Solution by @MaxU worked very well. I have just one suggestion:

If truncate_sheet=True is specified than "startrow" should NOT be retained from existing sheet. I suggest:

        if startrow is None and sheet_name in writer.book.sheetnames:
            if not truncate_sheet: # truncate_sheet would use startrow if provided (or zero below)
                startrow = writer.book[sheet_name].max_row

How to get a pixel's x,y coordinate color from an image?

Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:

getPixel from HTML Canvas?

Some code that would serve you specifically as well:

var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

for (var i = 0, n = pix.length; i < n; i += 4) {
  console.log pix[i+3]
}

This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.

Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:

$('el').click(function(e){
   console.log(e.clientX, e.clientY)
}

Those should grab your x and y values.

XSLT equivalent for JSON

I wrote my own small library around this, recently, which tries to stay as close to

5.1 Processing Model (XSLT REC) https://www.w3.org/TR/xslt#section-Processing-Model

as is possible (as I could anyway), in a few lines of JavaScript code.

Here are a few not-completely-trivial examples of use...

1. JSON-to-some-markup:

Fiddle: https://jsfiddle.net/YSharpLanguage/kj9pk8oz/10

(inspired by D.1 Document Example (XSLT REC) https://www.w3.org/TR/xslt#section-Document-Example)

where this:

var D1document = {
    type: "document", title: [ "Document Title" ],
    "": [
      { type: "chapter", title: [ "Chapter Title" ],
        "": [
        { type: "section", title: [ "Section Title" ],
          "": [
            { type: "para", "": [ "This is a test." ] },
            { type: "note", "": [ "This is a note." ] }
        ] },
        { type: "section", title: [ "Another Section Title" ],
          "": [
            { type: "para", "": [ "This is ", { emph: "another" }, " test." ] },
            { type: "note", "": [ "This is another note." ] }
        ] }
      ] }
    ] };

var D1toHTML = { $: [
  [ [ function(node) { return node.type === "document"; } ],
    function(root) {
      return "<html>\r\n\
  <head>\r\n\
    <title>\r\n\
      {title}\r\n".of(root) + "\
    </title>\r\n\
  </head>\r\n\
  <body>\r\n\
{*}".of(root[""].through(this)) + "\
  </body>\r\n\
</html>";
    }
  ],
  [ [ function(node) { return node.type === "chapter"; } ],
    function(chapter) {
      return "    <h2>{title}</h2>\r\n".of(chapter) + "{*}".of(chapter[""].through(this));
    }
  ],
  [ [ function(node) { return node.type === "section"; } ],
    function(section) {
      return "    <h3>{title}</h3>\r\n".of(section) + "{*}".of(section[""].through(this));
    }
  ],
  [ [ function(node) { return node.type === "para"; } ],
    function(para) {
      return "    <p>{*}</p>\r\n".of(para[""].through(this));
    }
  ],
  [ [ function(node) { return node.type === "note"; } ],
    function(note) {
      return '    <p class="note"><b>NOTE: </b>{*}</p>\r\n'.of(note[""].through(this));
    }
  ],
  [ [ function(node) { return node.emph; } ],
    function(emph) {
      return "<em>{emph}</em>".of(emph);
    }
  ]
] };

console.log(D1document.through(D1toHTML));

... gives:

<html>
  <head>
    <title>
      Document Title
    </title>
  </head>
  <body>
    <h2>Chapter Title</h2>
    <h3>Section Title</h3>
    <p>This is a test.</p>
    <p class="note"><b>NOTE: </b>This is a note.</p>
    <h3>Another Section Title</h3>
    <p>This is <em>another</em> test.</p>
    <p class="note"><b>NOTE: </b>This is another note.</p>
  </body>
</html>

and

2. JSON-to-JSON:

Fiddle: https://jsfiddle.net/YSharpLanguage/ppfmmu15/10

where this:

// (A "Company" is just an object with a "Team")
function Company(obj) {
  return obj.team && Team(obj.team);
}

// (A "Team" is just a non-empty array that contains at least one "Member")
function Team(obj) {
  return ({ }.toString.call(obj) === "[object Array]") &&
         obj.length &&
         obj.find(function(item) { return Member(item); });
}

// (A "Member" must have first and last names, and a gender)
function Member(obj) {
  return obj.first && obj.last && obj.sex;
}

function Dude(obj) {
  return Member(obj) && (obj.sex === "Male");
}

function Girl(obj) {
  return Member(obj) && (obj.sex === "Female");
}

var data = { team: [
  { first: "John", last: "Smith", sex: "Male" },
  { first: "Vaio", last: "Sony" },
  { first: "Anna", last: "Smith", sex: "Female" },
  { first: "Peter", last: "Olsen", sex: "Male" }
] };

var TO_SOMETHING_ELSE = { $: [

  [ [ Company ],
    function(company) {
      return { some_virtual_dom: {
        the_dudes: { ul: company.team.select(Dude).through(this) },
        the_grrls: { ul: company.team.select(Girl).through(this) }
      } }
    } ],

  [ [ Member ],
    function(member) {
      return { li: "{first} {last} ({sex})".of(member) };
    } ]

] };

console.log(JSON.stringify(data.through(TO_SOMETHING_ELSE), null, 4));

... gives:

{
    "some_virtual_dom": {
        "the_dudes": {
            "ul": [
                {
                    "li": "John Smith (Male)"
                },
                {
                    "li": "Peter Olsen (Male)"
                }
            ]
        },
        "the_grrls": {
            "ul": [
                {
                    "li": "Anna Smith (Female)"
                }
            ]
        }
    }
}

3. XSLT vs. JavaScript:

A JavaScript equivalent of...

XSLT 3.0 REC Section 14.4 Example: Grouping Nodes based on Common Values

(at: http://jsfiddle.net/YSharpLanguage/8bqcd0ey/1)

Cf. https://www.w3.org/TR/xslt-30/#grouping-examples

where...

var cities = [
  { name: "Milano",  country: "Italia",      pop: 5 },
  { name: "Paris",   country: "France",      pop: 7 },
  { name: "München", country: "Deutschland", pop: 4 },
  { name: "Lyon",    country: "France",      pop: 2 },
  { name: "Venezia", country: "Italia",      pop: 1 }
];

/*
  Cf.
  XSLT 3.0 REC Section 14.4
  Example: Grouping Nodes based on Common Values

  https://www.w3.org/TR/xslt-30/#grouping-examples
*/
var output = "<table>\r\n\
  <tr>\r\n\
    <th>Position</th>\r\n\
    <th>Country</th>\r\n\
    <th>City List</th>\r\n\
    <th>Population</th>\r\n\
  </tr>{*}\r\n\
</table>".of
  (
    cities.select().groupBy("country")(function(byCountry, index) {
      var country = byCountry[0],
          cities = byCountry[1].select().orderBy("name");
      return "\r\n\
  <tr>\r\n\
    <td>{position}</td>\r\n\
    <td>{country}</td>\r\n\
    <td>{cities}</td>\r\n\
    <td>{population}</td>\r\n\
  </tr>".
        of({ position: index + 1, country: country,
             cities: cities.map(function(city) { return city.name; }).join(", "),
             population: cities.reduce(function(sum, city) { return sum += city.pop; }, 0)
           });
    })
  );

... gives:

<table>
  <tr>
    <th>Position</th>
    <th>Country</th>
    <th>City List</th>
    <th>Population</th>
  </tr>
  <tr>
    <td>1</td>
    <td>Italia</td>
    <td>Milano, Venezia</td>
    <td>6</td>
  </tr>
  <tr>
    <td>2</td>
    <td>France</td>
    <td>Lyon, Paris</td>
    <td>9</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Deutschland</td>
    <td>München</td>
    <td>4</td>
  </tr>
</table>

4. JSONiq vs. JavaScript:

A JavaScript equivalent of...

JSONiq Use Cases Section 1.1.2. Grouping Queries for JSON

(at: https://jsfiddle.net/YSharpLanguage/hvo24hmk/3)

Cf. http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping

where...

/*
  1.1.2. Grouping Queries for JSON
  http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping
*/
var sales = [
  { "product" : "broiler", "store number" : 1, "quantity" : 20  },
  { "product" : "toaster", "store number" : 2, "quantity" : 100 },
  { "product" : "toaster", "store number" : 2, "quantity" : 50 },
  { "product" : "toaster", "store number" : 3, "quantity" : 50 },
  { "product" : "blender", "store number" : 3, "quantity" : 100 },
  { "product" : "blender", "store number" : 3, "quantity" : 150 },
  { "product" : "socks", "store number" : 1, "quantity" : 500 },
  { "product" : "socks", "store number" : 2, "quantity" : 10 },
  { "product" : "shirt", "store number" : 3, "quantity" : 10 }
];

var products = [
  { "name" : "broiler", "category" : "kitchen", "price" : 100, "cost" : 70 },
  { "name" : "toaster", "category" : "kitchen", "price" : 30, "cost" : 10 },
  { "name" : "blender", "category" : "kitchen", "price" : 50, "cost" : 25 },
  {  "name" : "socks", "category" : "clothes", "price" : 5, "cost" : 2 },
  { "name" : "shirt", "category" : "clothes", "price" : 10, "cost" : 3 }
];

var stores = [
  { "store number" : 1, "state" : "CA" },
  { "store number" : 2, "state" : "CA" },
  { "store number" : 3, "state" : "MA" },
  { "store number" : 4, "state" : "MA" }
];

var nestedGroupingAndAggregate = stores.select().orderBy("state").groupBy("state")
( function(byState) {
    var state = byState[0],
        stateStores = byState[1];
    byState = { };
    return (
      (
        byState[state] =
        products.select().orderBy("category").groupBy("category")
        ( function(byCategory) {
            var category = byCategory[0],
                categoryProducts = byCategory[1],
                categorySales = sales.filter(function(sale) {
                  return stateStores.find(function(store) { return sale["store number"] === store["store number"]; }) &&
                         categoryProducts.find(function(product) { return sale.product === product.name; });
                });
            byCategory = { };
            return (
              (
                byCategory[category] =
                categorySales.select().orderBy("product").groupBy("product")
                ( function(byProduct) {
                    var soldProduct = byProduct[0],
                        soldQuantities = byProduct[1];
                    byProduct = { };
                    return (
                      (
                        byProduct[soldProduct] =
                        soldQuantities.reduce(function(sum, sale) { return sum += sale.quantity; }, 0)
                      ),
                      byProduct
                    );
                } ) // byProduct()
              ),
              byCategory
            );
        } ) // byCategory()
      ),
      byState
    );
} ); // byState()

... gives:

[
  {
    "CA": [
      {
        "clothes": [
          {
            "socks": 510
          }
        ]
      },
      {
        "kitchen": [
          {
            "broiler": 20
          },
          {
            "toaster": 150
          }
        ]
      }
    ]
  },
  {
    "MA": [
      {
        "clothes": [
          {
            "shirt": 10
          }
        ]
      },
      {
        "kitchen": [
          {
            "blender": 250
          },
          {
            "toaster": 50
          }
        ]
      }
    ]
  }
]

It is also useful to overcome the limitations of JSONPath wrt. querying against the ancestor axis, as raised by this SO question (and certainly others).

E.g., how to get the discount of a grocery item knowing its brand id, in

{
 "prods": [
    {
        "info": {
              "rate": 85
                },
        "grocery": [
                 {
                  "brand": "C",
                  "brand_id": "984"
                 },
                 {
                  "brand": "D",
                  "brand_id": "254"
                 }
                 ],
         "discount": "15"
    },
    {
        "info": {
              "rate": 100
                },
        "grocery": [
                 {
                  "brand": "A",
                  "brand_id": "983"
                 },
                 {
                  "brand": "B",
                  "brand_id": "253"
                 }
                 ],
         "discount": "20"
     }
 ]
}

?

A possible solution is:

var products = {
     "prods": [
        {
            "info": {
                  "rate": 85
                    },
            "grocery": [
                     {
                      "brand": "C",
                      "brand_id": "984"
                     },
                     {
                      "brand": "D",
                      "brand_id": "254"
                     }
                     ],
             "discount": "15"
        },
        {
            "info": {
                  "rate": 100
                    },
            "grocery": [
                     {
                      "brand": "A",
                      "brand_id": "983"
                     },
                     {
                      "brand": "B",
                      "brand_id": "253"
                     }
                     ],
             "discount": "20"
         }
     ]
};

function GroceryItem(obj) {
  return (typeof obj.brand === "string") && (typeof obj.brand_id === "string");
}

    // last parameter set to "true", to grab all the "GroceryItem" instances
    // at any depth:
var itemsAndDiscounts = [ products ].nodeset(GroceryItem, true).
    map(
      function(node) {
        var item = node.value, // node.value: the current "GroceryItem" (aka "$.prods[*].grocery[*]")

            discount = node.parent. // node.parent: the array of "GroceryItem" (aka "$.prods[*].grocery")
                       parent. // node.parent.parent: the product (aka "$.prods[*]")
                       discount; // node.parent.parent.discount: the product discount

        // finally, project into an easy-to-filter form:
        return { id: item.brand_id, discount: discount };
      }
    ),
    discountOfItem983;

discountOfItem983 = itemsAndDiscounts.
  filter
  (
    function(mapped) {
      return mapped.id === "983";
    }
  )
  [0].discount;

console.log("Discount of #983: " + discountOfItem983);

... which gives:

Discount of #983: 20

'HTH,

Jenkins fails when running "service start jenkins"

I had below error:

Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.

Solution was to revert the NAME to jenkins in the below file (Earlier I have changed it to 'NAME=ubuntu'):

sudo vi /etc/default/jenkins
    NAME=jenkins

Now restart passed:

sudo service jenkins restart
sudo systemctl restart jenkins.service

Hope that helps.

'console' is undefined error for Internet Explorer

Try

if (!window.console) console = ...

An undefined variable cannot be referred directly. However, all global variables are attributes of the same name of the global context (window in case of browsers), and accessing an undefined attribute is fine.

Or use if (typeof console === 'undefined') console = ... if you want to avoid the magic variable window, see @Tim Down's answer.

Numpy array dimensions

The shape method requires that a be a Numpy ndarray. But Numpy can also calculate the shape of iterables of pure python objects:

np.shape([[1,2],[1,2]])

Show data on mouseover of circle

There is an awesome library for doing that that I recently discovered. It's simple to use and the result is quite neat: d3-tip.

You can see an example here:

enter image description here

Basically, all you have to do is to download(index.js), include the script:

<script src="index.js"></script>

and then follow the instructions from here (same link as example)

But for your code, it would be something like:

define the method:

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Frequency:</strong> <span style='color:red'>" + d.frequency + "</span>";
  })

create your svg (as you already do)

var svg = ...

call the method:

svg.call(tip);

add tip to your object:

vis.selectAll("circle")
   .data(datafiltered).enter().append("svg:circle")
...
   .on('mouseover', tip.show)
   .on('mouseout', tip.hide)

Don't forget to add the CSS:

<style>
.d3-tip {
  line-height: 1;
  font-weight: bold;
  padding: 12px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  border-radius: 2px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  font-size: 10px;
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.8);
  content: "\25BC";
  position: absolute;
  text-align: center;
}

/* Style northward tooltips differently */
.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;
}
</style>

PHP Header redirect not working

Look at /Applications/MAMP/htdocs/testygubbins/OO/test/header.php line 15.

At that position, it makes some output. Fix it. :)

How to enable file sharing for my app?

Maybe it's obvious for you guys but I scratched my head for a while because the folder didn't show up in the files app. I actually needed to store something in the folder. you could achieve this by

  • saving some files into your document directory of the app
  • move something from iCloud Drive to your app (in the move dialog the folder will show up). As soon as there are no files in your folder anymore, it's gonna disappear from the "on my iPad tab".

Openssl : error "self signed certificate in certificate chain"

You have a certificate which is self-signed, so it's non-trusted by default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to a man-in-the-middle attack.

To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'll have to install that CA's certificate as well.

Have a look at this link about installing self-signed certificates.

Returning a stream from File.OpenRead()

Options:

  • Use data.Seek as suggested by ken2k
  • Use the somewhat simpler Position property:

    data.Position = 0;
    
  • Use the ToArray call in MemoryStream to make your life simpler to start with:

    byte[] buf = data.ToArray();
    

The third option would be my preferred approach.

Note that you should have a using statement to close the file stream automatically (and optionally for the MemoryStream), and I'd add a using directive for System.IO to make your code cleaner:

byte[] buf;
using (MemoryStream data = new MemoryStream())
{
    using (Stream file = TestStream())
    {
        file.CopyTo(data);
        buf = data.ToArray();
    }
}

// Use buf

You might also want to create an extension method on Stream to do this for you in one place, e.g.

public static byte[] CopyToArray(this Stream input)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        input.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }
}

Note that this doesn't close the input stream.

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

Are there any style options for the HTML5 Date picker?

I used a combination of the above solutions and some trial and error to come to this solution. Took me an annoying amount of time so I hope this can help someone else in the future. I also noticed that the date picker input is not at all supported by Safari...

I am using styled-components to render a transparent date picker input as shown in the image below:

image of date picker input

const StyledInput = styled.input`
  appearance: none;
  box-sizing: border-box;
  border: 1px solid black;
  background: transparent;
  font-size: 1.5rem;
  padding: 8px;
  ::-webkit-datetime-edit-text { padding: 0 2rem; }
  ::-webkit-datetime-edit-month-field { text-transform: uppercase; }
  ::-webkit-datetime-edit-day-field { text-transform: uppercase; }
  ::-webkit-datetime-edit-year-field { text-transform: uppercase; }
  ::-webkit-inner-spin-button { display: none; }
  ::-webkit-calendar-picker-indicator { background: transparent;}
`

Sort an array of objects in React and render them

this.state.data.sort((a, b) => a.item.timeM > b.item.timeM).map(
    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

How to pass multiple parameters to a get method in ASP.NET Core

Why not using just one controller action?

public string Get(int? id, string firstName, string lastName, string address)
{
   if (id.HasValue)
      GetById(id);
   else if (string.IsNullOrEmpty(address))
      GetByName(firstName, lastName);
   else
      GetByNameAddress(firstName, lastName, address);
}

Another option is to use attribute routing, but then you'd need to have a different URL format:

//api/person/byId?id=1
[HttpGet("byId")] 
public string Get(int id)
{
}

//api/person/byName?firstName=a&lastName=b
[HttpGet("byName")]
public string Get(string firstName, string lastName, string address)
{
}

How to set DataGrid's row Background, based on a property value using data bindings

In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.

<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
   <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="{Binding ColorSet}"/>
        </Style>
   </DataGrid.RowStyle>

And in my Employee Class

public class Employee {

    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public string ColorSet { get; set; }

    public Employee() { }

    public Employee(int id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
        if (Age > 50)
        {
            ColorSet = "Green";
        }
        else if (Age > 100)
        {
            ColorSet = "Red";
        }
        else
        {
            ColorSet = "White";
        }
    }
}

This way every Row of the DataGrid has the BackGround Color of the ColorSet Property of my Object.

How get total sum from input box values using Javascript?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
  //iterate through each textboxes and add keyup_x000D_
  //handler to trigger sum event_x000D_
  $(".txt").each(function() {_x000D_
_x000D_
   $(this).keyup(function(){_x000D_
    calculateSum();_x000D_
   });_x000D_
  });_x000D_
_x000D_
 });_x000D_
_x000D_
 function calculateSum() {_x000D_
_x000D_
  var sum = 0;_x000D_
  //iterate through each textboxes and add the values_x000D_
  $(".txt").each(function() {_x000D_
_x000D_
   //add only if the value is number_x000D_
   if(!isNaN(this.value) && this.value.length!=0) {_x000D_
    sum += parseFloat(this.value);_x000D_
   }_x000D_
_x000D_
  });_x000D_
  //.toFixed() method will roundoff the final sum to 2 decimal places_x000D_
  $("#sum").html(sum.toFixed(2));_x000D_
 }
_x000D_
body {_x000D_
    font-family: sans-serif;_x000D_
   }_x000D_
   #summation {_x000D_
    font-size: 18px;_x000D_
    font-weight: bold;_x000D_
    color:#174C68;_x000D_
   }_x000D_
   .txt {_x000D_
    background-color: #FEFFB0;_x000D_
    font-weight: bold;_x000D_
    text-align: right;_x000D_
   }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">_x000D_
 <tr>_x000D_
  <td width="40px">1</td>_x000D_
  <td>Butter</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>2</td>_x000D_
  <td>Cheese</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>3</td>_x000D_
  <td>Eggs</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>4</td>_x000D_
  <td>Milk</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>5</td>_x000D_
  <td>Bread</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>6</td>_x000D_
  <td>Soap</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr id="summation">_x000D_
  <td>&nbsp;</td>_x000D_
  <td align="right">Sum :</td>_x000D_
  <td align="center"><span id="sum">0</span></td>_x000D_
 </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I had same problem. After one day, I got it.

Problem was from adding two smtp tags in mailSettings under <system.net>.

How can I pad a String in Java?

All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.

public static char[] lpad(char[] pStringChar, int pTotalLength, char pPad) {
    if (pStringChar.length < pTotalLength) {
        char[] retChar = new char[pTotalLength];
        int padIdx = pTotalLength - pStringChar.length;
        Arrays.fill(retChar, 0, padIdx, pPad);
        System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
        return retChar;
    } else {
        return pStringChar;
    }
}
  • note it is called with String.toCharArray() and the result can be converted to String with new String((char[])result). The reason for this is, if you applying multiple operations you can do them all on char[] and not keep on converting between formats - behind the scenes, String is stored as char[]. If these operations were included in the String class itself, it would have been twice as efficient - speed and memory wise.

How to get the file path from URI?

Here is the answer to the question here

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

EDIT . Copying answer that worked for me

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

}

Convert Json string to Json object in Swift 4

I tried the solutions here, and as? [String:AnyObject] worked for me:

do{
    if let json = stringToParse.data(using: String.Encoding.utf8){
        if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
            let id = jsonData["id"] as! String
            ...
        }
    }
}catch {
    print(error.localizedDescription)

}