Programs & Examples On #System verilog

SystemVerilog is a unified hardware design, specification, and verification language based on extensions to Verilog.

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

Specified cast is not valid?

Try this:

public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();                
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }

Generate random numbers uniformly over an entire range

By their nature, a small sample of random numbers doesn't have to be uniformly distributed. They're random, after all. I agree that if a random number generator is generating numbers that consistently appear to be grouped, then there is probably something wrong with it.

But keep in mind that randomness isn't necessarily uniform.

Edit: I added "small sample" to clarify.

Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

Quick explanation:

  • The function withColumn is called to add (or replace, if the name exists) a column to the data frame.
  • The function regexp_replace will generate a new column by replacing all substrings that match the pattern.

S3 - Access-Control-Allow-Origin Header

This configuration solved the issue for me:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <ExposeHeader>ETag</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Convert nested Python dict to object?

You can leverage the json module of the standard library with a custom object hook:

import json

class obj(object):
    def __init__(self, dict_):
        self.__dict__.update(dict_)

def dict2obj(d):
    return json.loads(json.dumps(d), object_hook=obj)

Example usage:

>>> d = {'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]}
>>> o = dict2obj(d)
>>> o.a
1
>>> o.b.c
2
>>> o.d[0]
u'hi'
>>> o.d[1].foo
u'bar'

And it is not strictly read-only as it is with namedtuple, i.e. you can change values – not structure:

>>> o.b.c = 3
>>> o.b.c
3

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

git cherry-pick says "...38c74d is a merge but no -m option was given"

Simplification of @Daira Hopwood method good for picking one single commit. Need no temporary branches.

In the case of the author:

  • Z is wanted commit (fd9f578)
  • Y is commit before it
  • X current working branch

then do:

git checkout Z   # move HEAD to wanted commit
git reset Y      # have Z as changes in working tree
git stash        # save Z in stash
git checkout X   # return to working branch
git stash pop    # apply Z to current branch
git commit -a    # do commit

Procedure expects parameter which was not supplied

First - why is that an EXEC? Shouldn't that just be

AS
SELECT Column_Name, ...
FROM ...
WHERE TABLE_NAME = @template

The current SP doesn't make sense? In particular, that would look for a column matching @template, not the varchar value of @template. i.e. if @template is 'Column_Name', it would search WHERE TABLE_NAME = Column_Name, which is very rare (to have table and column named the same).

Also, if you do have to use dynamic SQL, you should use EXEC sp_ExecuteSQL (keeping the values as parameters) to prevent from injection attacks (rather than concatenation of input). But it isn't necessary in this case.

Re the actual problem - it looks OK from a glance; are you sure you don't have a different copy of the SP hanging around? This is a common error...

Format certain floating dataframe columns into percentage in pandas

Just another way of doing it should you require to do it over a larger range of columns

using applymap

df[['var1','var2']] = df[['var1','var2']].applymap("{0:.2f}".format)
df['var3'] = df['var3'].applymap(lambda x: "{0:.2f}%".format(x*100))

applymap is useful if you need to apply the function over multiple columns; it's essentially an abbreviation of the below for this specific example:

df[['var1','var2']].apply(lambda x: map(lambda x:'{:.2f}%'.format(x),x),axis=1)

Great explanation below of apply, map applymap:

Difference between map, applymap and apply methods in Pandas

how to change text in Android TextView

setting the text to sam textview twice is overwritting the first written text. So the second time when we use settext we just append the new string like

textview.append("Step Two: fry egg");

What is the way of declaring an array in JavaScript?

There are a number of ways to create arrays.

The traditional way of declaring and initializing an array looks like this:

var a = new Array(5); // declare an array "a", of size 5
a = [0, 0, 0, 0, 0];  // initialize each of the array's elements to 0

Or...

// declare and initialize an array in a single statement
var a = new Array(0, 0, 0, 0, 0); 

How to convert a GUID to a string in C#?

String guid = System.Guid.NewGuid().ToString();

Otherwise it's a delegate.

Find MongoDB records where array field is not empty

This also works:

db.getCollection('collectionName').find({'arrayName': {$elemMatch:{}}})

Exception : AAPT2 error: check logs for details

I faced similar problem. Akilesh awasthi's answer helped me fix it. My problem was a little different. I was using places_ic_search icon from com.google.android.gms:play-services-location The latest version com.google.android.gms:play-services-location:15.0.0 does not provide the icon places_ic_search. Because of this there was a problem in the layout.xml files.That led to build failure AAPT2 error: check logs for details as the message. Android studio should be showing cannot find drawable places_ic_search as the message instead.

I ended up using a lower version of com.google.android.gms:play-services-location temporarily. Hope this helps someone in future.

How to get line count of a large file cheaply in Python?

If one wants to get the line count cheaply in Python in Linux, I recommend this method:

import os
print os.popen("wc -l file_path").readline().split()[0]

file_path can be both abstract file path or relative path. Hope this may help.

Python error message io.UnsupportedOperation: not readable

Use a+ to open a file for reading, writing as well as create it if it doesn't exist.

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. -Python file modes

with open('"File.txt', 'a+') as file:
    print(file.readlines())
    file.write("test")

Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

Remove pandas rows with duplicate indices

This adds the index as a dataframe column, drops duplicates on that, then removes the new column:

df = df.reset_index().drop_duplicates(subset='index', keep='last').set_index('index').sort_index()

Note that the use of .sort_index() above at the end is as needed and is optional.

Mailto on submit button

Just include "a" tag in "button" tag.

<button><a href="mailto:..."></a></button>

HTML form submit to PHP script

Try this:

<form method="post" action="check.php">
    <select name="website_string">
        <option value="" selected="selected"></option>
        <option VALUE="abc"> ABC</option>
        <option VALUE="def"> def</option>
        <option VALUE="hij"> hij</option>
    </select>
    <input TYPE="submit" name="submit" />
</form>

Both your select control and your submit button had the same name attribute, so the last one used was the submit button when you clicked it. All other syntax errors aside.

check.php

<?php
    echo $_POST['website_string'];
?>

Obligatory disclaimer about using raw $_POST data. Sanitize anything you'll actually be using in application logic.

Understanding __get__ and __set__ and Python descriptors

I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).

The code:

#!/usr/bin/env python
class Celsius:
    def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5.0
    def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9.0

class Temperature:
    def __init__(self, initial_f): self.fahrenheit = initial_f
    celsius = Celsius()

if __name__ == "__main__":

    t = Temperature(212)
    print(t.celsius)
    t.celsius = 0
    print(t.fahrenheit)

The result:

C:\Users\gkuhn\Desktop>python test2.py
<__main__.Celsius instance at 0x02E95A80>
212

With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the get magic does not work for old style classes.

Sql Server string to date conversion

why not try

select convert(date,'10/15/2011 00:00:00',104) as [MM/dd/YYYY]

date formats can be found at SQL Server Helper > SQL Server Date Formats

Show/hide div if checkbox selected

change the input boxes like

<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox

and js code as

function showMe (box) {

    var chboxs = document.getElementsByName("c1");
    var vis = "none";
    for(var i=0;i<chboxs.length;i++) { 
        if(chboxs[i].checked){
         vis = "block";
            break;
        }
    }
    document.getElementById(box).style.display = vis;


}

here is a demo fiddle

How can I get the value of a registry key from within a batch script?

To get a particular answer to the registry value you may use the following query:

REG QUERY "Key_Name" /v "Value_Name" /s

eg: REG QUERY "HKEY_CURRENT_USER\Software\Microsoft\Command Processor" /v "EnableExtensions" /s

here /v : Queries for a specific registry key values.

/s : Queries all subkeys and values recursively (like dir /s)

invalid use of non-static member function

You must make Foo::comparator static or wrap it in a std::mem_fun class object. This is because lower_bounds() expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind too.

Examples:

// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });

TimePicker Dialog from clicking EditText

You have not put the last argument in the TimePickerDialog.

{
public TimePickerDialog(Context context, OnTimeSetListener listener, int hourOfDay, int minute,
            boolean is24HourView) {
        this(context, 0, listener, hourOfDay, minute, is24HourView);
    }
}

this is the code of the TimePickerclass. it requires a boolean argument is24HourView

submit the form using ajax

Nobody has actually given a pure javascript answer (as requested by OP), so here it is:

function postAsync(url2get, sendstr)    {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    if (req != undefined) {
        // req.overrideMimeType("application/json"); // if request result is JSON
        try {
            req.open("POST", url2get, false); // 3rd param is whether "async"
            }
        catch(err) {
            alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
            return false;
            }
        req.send(sendstr); // param string only used for POST

        if (req.readyState == 4) { // only if req is "loaded"
            if (req.status == 200)  // only if "OK"
                { return req.responseText ; }
            else    { return "XHR error: " + req.status +" "+req.statusText; }
            }
        }
    alert("req for getAsync is undefined");
}

var var_str = "var1=" + var1  + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
    // hint: encodeURIComponent()

if (ret.match(/^XHR error/)) {
    console.log(ret);
    return;
    }

In your case:

var var_str = "video_time=" + document.getElementById('video_time').value 
     + "&video_id=" + document.getElementById('video_id').value;

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

CSS3 transition events

W3C CSS Transitions Draft

The completion of a CSS Transition generates a corresponding DOM Event. An event is fired for each property that undergoes a transition. This allows a content developer to perform actions that synchronize with the completion of a transition.


Webkit

To determine when a transition completes, set a JavaScript event listener function for the DOM event that is sent at the end of a transition. The event is an instance of WebKitTransitionEvent, and its type is webkitTransitionEnd.

box.addEventListener( 'webkitTransitionEnd', 
    function( event ) { alert( "Finished transition!" ); }, false );

Mozilla

There is a single event that is fired when transitions complete. In Firefox, the event is transitionend, in Opera, oTransitionEnd, and in WebKit it is webkitTransitionEnd.

Opera

There is one type of transition event available. The oTransitionEnd event occurs at the completion of the transition.

Internet Explorer

The transitionend event occurs at the completion of the transition. If the transition is removed before completion, the event will not fire.


Stack Overflow: How do I normalize CSS3 Transition functions across browsers?

Difference between nVidia Quadro and Geforce cards?

It's called market segmentation or something like that. nVidia produces one very configurable chip and then sells it in different configurations that essentially have the same elements and hence the same bill of materials to different market segments, although one would usually expect to find elements of higher quality on the more expensive Quadro boards.

What differentiates Quadro from GeForce is that GeForce usually has its dual precision floating point performance severely limited, e.g. to 1/4 or 1/8 of that of the Quadro/Tesla GPUs. This limitation is purely artificial and imposed on solely to differentiate the gamer/enthusiast segment from the professional segment. Lower DP performance makes GeForce boards bad candidates for stuff like scientific or engineering computing and those are markets where money streams from. Also Quadros (arguably) have more display channels and faster RAMDACs which allows them to drive more and higher resolution screens, a sort of setup perceived as professional for CAD/CAM work.

As Jason Morgan has pointed out, there are tricks that can unlock some of the disabled features in GeForce to bring them in par with Quadro. Those usually involves soldering and voids the warranty on the card. Since HPC puts lots of stress on the hardware and malfunctions occur more frequently that one would like them to, I would advise against using cheap tricks.

AngularJS - How to use $routeParams in generating the templateUrl?

This very helpful feature is now available starting at version 1.1.2 of AngularJS. It's considered unstable but I have used it (1.1.3) and it works fine.

Basically you can use a function to generate a templateUrl string. The function is passed the route parameters that you can use to build and return the templateUrl string.

var app = angular.module('app',[]);

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id; }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

Many thanks to https://github.com/lrlopez for the pull request.

https://github.com/angular/angular.js/pull/1524

How to empty a list?

If you're running Python 3.3 or better, you can use the clear() method of list, which is parallel to clear() of dict, set, deque and other mutable container types:

alist.clear()  # removes all items from alist (equivalent to del alist[:])

As per the linked documentation page, the same can also be achieved with alist *= 0.

To sum up, there are four equivalent ways to clear a list in-place (quite contrary to the Zen of Python!):

  1. alist.clear() # Python 3.3+
  2. del alist[:]
  3. alist[:] = []
  4. alist *= 0

How to add text inside the doughnut chart using Chart.js?

@rap-2-h and @Ztuons Ch's answer doesn't allow for the showTooltips option to be active, but what you can do is create and layer a second canvas object behind the one rendering the chart.

The important part is the styling required in the divs and for the canvas object itself so that they render on top of each other.

_x000D_
_x000D_
var data = [_x000D_
    {value : 100, color : 'rgba(226,151,093,1)', highlight : 'rgba(226,151,093,0.75)', label : "Sector 1"},_x000D_
    {value : 100, color : 'rgba(214,113,088,1)', highlight : 'rgba(214,113,088,0.75)', label : "Sector 2"},_x000D_
    {value : 100, color : 'rgba(202,097,096,1)', highlight : 'rgba(202,097,096,0.75)', label : "Sector 3"}_x000D_
]_x000D_
_x000D_
var options = { showTooltips : true };_x000D_
     _x000D_
var total = 0;_x000D_
for (i = 0; i < data.length; i++) {_x000D_
     total = total + data[i].value;_x000D_
}_x000D_
_x000D_
var chartCtx = $("#canvas").get(0).getContext("2d");_x000D_
var chart = new Chart(chartCtx).Doughnut(data, options);_x000D_
_x000D_
var textCtx = $("#text").get(0).getContext("2d");_x000D_
textCtx.textAlign = "center";_x000D_
textCtx.textBaseline = "middle";_x000D_
textCtx.font = "30px sans-serif";_x000D_
textCtx.fillText(total, 150, 150);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<div style="position: relative; width:300px; height:300px;">_x000D_
    <canvas id="text" _x000D_
            style="z-index: 1; _x000D_
                   position: absolute;_x000D_
                   left: 0px; _x000D_
                   top: 0px;" _x000D_
            height="300" _x000D_
            width="300"></canvas>_x000D_
    <canvas id="canvas" _x000D_
            style="z-index: 2; _x000D_
                   position: absolute;_x000D_
                   left: 0px; _x000D_
                   top: 0px;" _x000D_
            height="300" _x000D_
            width="300"></canvas>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Here's the jsfiddle: https://jsfiddle.net/68vxqyak/1/

PL/SQL, how to escape single quote in a string?

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

How to slice an array in Bash

There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.

version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}"    # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}"    # 7 1

Checking if an object is null in C#

Your dataList is null as it has not been instantiated, judging by the code you have posted.

Try:

public List<Object> dataList = new List<Object>();
public  bool AddData(ref Object data)
bool success = false;
try
{
    if (!data.Equals(null))   // I've also used if(data != null) which hasn't worked either
    {
       dataList.Add(data);                      //NullReferenceException occurs here
       success = doOtherStuff(data);
    }
}
catch (Exception e)
{
    throw new Exception(e.ToString());
}
return success;

}

Using msbuild to execute a File System Publish Profile

First check the Visual studio version of the developer PC which can publish the solution(project). as shown is for VS 2013

 /p:VisualStudioVersion=12.0

add the above command line to specify what kind of a visual studio version should build the project. As previous answers, this might happen when we are trying to publish only one project, not the whole solution.

So the complete code would be something like this

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" "C:\Program Files (x86)\Jenkins\workspace\Jenkinssecondsample\MVCSampleJenkins\MVCSampleJenkins.csproj" /T:Build;Package /p:Configuration=DEBUG /p:OutputPath="obj\DEBUG" /p:DeployIisAppPath="Default Web Site/jenkinsdemoapp" /p:VisualStudioVersion=12.0

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now

"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "

How do I list all cron jobs for all users?

you can write for all user list :

sudo crontab -u userName -l

,

You can also go to

cd /etc/cron.daily/
ls -l
cat filename

this file will list the schedules

cd /etc/cron.d/
ls -l
cat filename

startsWith() and endsWith() functions in PHP

I would do it like this

     function startWith($haystack,$needle){
              if(substr($haystack,0, strlen($needle))===$needle)
              return true;
        }

  function endWith($haystack,$needle){
              if(substr($haystack, -strlen($needle))===$needle)
              return true;
        }

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

How to set a ripple effect on textview or imageview on Android?

Ref : http://developer.android.com/training/material/animations.html,

http://wiki.workassis.com/category/android/android-xml/

<TextView
.
.
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
/>

<ImageView
.
.
.
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
/>

Best way to concatenate List of String objects?

ArrayList inherits its toString()-method from AbstractCollection, ie:

public String toString() {
    Iterator<E> i = iterator();
    if (! i.hasNext())
        return "[]";

    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (;;) {
        E e = i.next();
        sb.append(e == this ? "(this Collection)" : e);
        if (! i.hasNext())
            return sb.append(']').toString();
        sb.append(", ");
    }
}

Building the string yourself will be far more efficient.


If you really want to aggregate the strings beforehand in some sort of List, you should provide your own method to efficiently join them, e.g. like this:

static String join(Collection<?> items, String sep) {
    if(items.size() == 0)
        return "";

    String[] strings = new String[items.size()];
    int length = sep.length() * (items.size() - 1);

    int idx = 0;
    for(Object item : items) {
        String str = item.toString();
        strings[idx++] = str;
        length += str.length();
    }

    char[] chars = new char[length];
    int pos = 0;

    for(String str : strings) {
        str.getChars(0, str.length(), chars, pos);
        pos += str.length();

        if(pos < length) {
            sep.getChars(0, sep.length(), chars, pos);
            pos += sep.length();
        }
    }

    return new String(chars);
}

Add text to Existing PDF using Python

I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share:

  1. read your PDF using PdfFileReader(), we'll call this input
  2. create a new pdf containing your text to add using ReportLab, save this as a string object
  3. read the string object using PdfFileReader(), we'll call this text
  4. create a new PDF object using PdfFileWriter(), we'll call this output
  5. iterate through input and apply .mergePage(*text*.getPage(0)) for each page you want the text added to, then use output.addPage() to add the modified pages to a new document

This works well for simple text additions. See PyPDF's sample for watermarking a document.

Here is some code to answer the question below:

packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
<do something with canvas>
can.save()
packet.seek(0)
input = PdfFileReader(packet)

From here you can merge the pages of the input file with another document.

socket programming multiple client to one server

This is the echo server handling multiple clients... Runs fine and good using Threads

// echo server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class Server_X_Client {
public static void main(String args[]){


    Socket s=null;
    ServerSocket ss2=null;
    System.out.println("Server Listening......");
    try{
        ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined

    }
    catch(IOException e){
    e.printStackTrace();
    System.out.println("Server error");

    }

    while(true){
        try{
            s= ss2.accept();
            System.out.println("connection Established");
            ServerThread st=new ServerThread(s);
            st.start();

        }

    catch(Exception e){
        e.printStackTrace();
        System.out.println("Connection Error");

    }
    }

}

}

class ServerThread extends Thread{  

    String line=null;
    BufferedReader  is = null;
    PrintWriter os=null;
    Socket s=null;

    public ServerThread(Socket s){
        this.s=s;
    }

    public void run() {
    try{
        is= new BufferedReader(new InputStreamReader(s.getInputStream()));
        os=new PrintWriter(s.getOutputStream());

    }catch(IOException e){
        System.out.println("IO error in server thread");
    }

    try {
        line=is.readLine();
        while(line.compareTo("QUIT")!=0){

            os.println(line);
            os.flush();
            System.out.println("Response to Client  :  "+line);
            line=is.readLine();
        }   
    } catch (IOException e) {

        line=this.getName(); //reused String line for getting thread name
        System.out.println("IO Error/ Client "+line+" terminated abruptly");
    }
    catch(NullPointerException e){
        line=this.getName(); //reused String line for getting thread name
        System.out.println("Client "+line+" Closed");
    }

    finally{    
    try{
        System.out.println("Connection Closing..");
        if (is!=null){
            is.close(); 
            System.out.println(" Socket Input Stream Closed");
        }

        if(os!=null){
            os.close();
            System.out.println("Socket Out Closed");
        }
        if (s!=null){
        s.close();
        System.out.println("Socket Closed");
        }

        }
    catch(IOException ie){
        System.out.println("Socket Close Error");
    }
    }//end finally
    }
}

Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..

// A simple Client Server Protocol .. Client for Echo Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class NetworkClient {

public static void main(String args[]) throws IOException{


    InetAddress address=InetAddress.getLocalHost();
    Socket s1=null;
    String line=null;
    BufferedReader br=null;
    BufferedReader is=null;
    PrintWriter os=null;

    try {
        s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
        br= new BufferedReader(new InputStreamReader(System.in));
        is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
        os= new PrintWriter(s1.getOutputStream());
    }
    catch (IOException e){
        e.printStackTrace();
        System.err.print("IO Exception");
    }

    System.out.println("Client Address : "+address);
    System.out.println("Enter Data to echo Server ( Enter QUIT to end):");

    String response=null;
    try{
        line=br.readLine(); 
        while(line.compareTo("QUIT")!=0){
                os.println(line);
                os.flush();
                response=is.readLine();
                System.out.println("Server Response : "+response);
                line=br.readLine();

            }



    }
    catch(IOException e){
        e.printStackTrace();
    System.out.println("Socket read Error");
    }
    finally{

        is.close();os.close();br.close();s1.close();
                System.out.println("Connection Closed");

    }

}
}

Reference excel worksheet by name?

To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below. screenshot of predictive text in VBE

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.

Can I specify multiple users for myself in .gitconfig?

One command github accounts switch

This solution takes the form of a single git alias. Once executed, the current project user will be attached to another account

Generate ssh keys

ssh-keygen -t rsa -C "[email protected]" -f '/Users/arnaudrinquin/.ssh/id_rsa'

[...]

ssh-keygen -t rsa -C "[email protected]" -f '/Users/arnaudrinquin/.ssh/id_rsa_pro'

Link them to your GitHub / Bitbucket accounts

  1. copy default public key pbcopy < ~/.ssh/id_rsa.pub
  2. login to your GitHub acount
  3. paste the key in the add SSH key github page
  4. copy other public key pbcopy < ~/.ssh/id_rsa_pro.pub
  5. repeat and adapt steps 2 to 4 for every other account

Step 1. Automatic ssh key switching.

We can configure ssh to send a use a specific encryption key depending on the host. The nice thing is that you can have several aliases for the same hostname.

See this example ~/.ssh/config file:

# Default GitHub
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa

# Professional github alias
Host github_pro
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_pro

git remote configuration

You can now use these aliases in the git remotes by changing [email protected] by git@github_pro.

You can either change your existing projects remotes (using something like git remote set-url origin git@github_pro:foo/bar.git) or adapt them directly when cloning them.

git clone [email protected]:ArnaudRinquin/atom-zentabs.git

using alias, it become:

git clone git@github_pro:ArnaudRinquin/atom-zentabs.git

Step 2. Changing git user.email

Git config settings can be global or per project. In our case, we want a per project settings. It is very easy to change it:

git config user.email '[email protected]'

While this is easy, it takes way to long for the developers we are. We can write a very simple git alias for that.

We are going to add it to the ~/.gitconfig file.

[user]
    name = Arnaud Rinquin
    email = [email protected]

...

[alias]
    setpromail = "config user.email '[email protected]'"

Then, all we have to do is git setpromail to have our email changed for this project only.

Step 3. One command switch please?!

Wouldn’t it be nice to switch from default account to a specified one with a single parameter-less command? This is definitely possible. This command will have two steps:

  • change current project remotes to the chosen aliases
  • change current project user.email config

We already have a one command solution for the second step, but the first one is way harder. One command remote host change

Here comes the solution in the form of another git alias command to add to your ~/.gitconfig:

[alias]
  changeremotehost = !sh -c \"git remote -v | grep '$1.*fetch' | sed s/..fetch.// | sed s/$1/$2/ | xargs git remote set-url\"

This allows changing all remotes from one host to another (the alias). See the example:

$ > git remote -v
origin  [email protected]:ArnaudRinquin/arnaudrinquin.github.io.git (fetch)
origin  [email protected]:ArnaudRinquin/arnaudrinquin.github.io.git (push)

$ > git changeremotehost github.com github_pro

$ > git remote -v
origin  git@github_pro:ArnaudRinquin/arnaudrinquin.github.io.git (fetch)
origin  git@github_pro:ArnaudRinquin/arnaudrinquin.github.io.git (push)

Combine them all

We now just have to combine the two commands into one, this is quite easy. See how I also integrate bitbucket host switching.

[alias]
  changeremotehost = !sh -c \"git remote -v | grep '$1.*fetch' | sed s/..fetch.// | sed s/$1/$2/ | xargs git remote set-url\"
  setpromail = "config user.email '[email protected]'"
  gopro = !sh -c \"git changeremotehost github.com github_pro && git changeremotehost bitbucket.com bitbucket_pro && git setpromail\"

Source Link -Github

Source Link -Tutorial

Best way to track onchange as-you-type in input type="text"?

Use oninput instead of onchange.

index.html

<html>
  <head>
    <title>title here</title>
    <script src="index.js"></script>
  </head>
  <body>
    <input oninput="onclickhandler(this)"></input>
  </body>
</html>

script.js

function onclickhandler(e) {
  console.log(e.value);
}

How to pass credentials to the Send-MailMessage command for sending emails

I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:

$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Test" 
$Body = "Test Body" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\CDF.pdf"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password"); 
$SMTPClient.Send($SMTPMessage)

Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
        [String]$Subject,
        [Parameter(`
            Mandatory=$true)]
        [String]$Body,
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailFrom="[email protected]",  #This gives a default value to the $EmailFrom command
        [Parameter(`
            mandatory=$false)]
        [String]$attachment,
        [Parameter(`
            mandatory=$true)]
        [String]$Password
    )

        $SMTPServer = "smtp.gmail.com" 
        $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
        if ($attachment -ne $null) {
            $SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
            $SMTPMessage.Attachments.Add($SMTPattachment)
        }
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
        $SMTPClient.EnableSsl = $true 
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password); 
        $SMTPClient.Send($SMTPMessage)
        Remove-Variable -Name SMTPClient
        Remove-Variable -Name Password

} #End Function Send-EMail

To call it, just use this command:

Send-EMail -EmailTo "[email protected]" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"

I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!

Edit: Added $EmailFrom based on JuanPablo's comment

Edit: SMTP was spelled STMP in the attachments.

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

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

@HostBinding and @HostListener: what do they do and what are they for?

Here is a basic hover example.

Component's template property:

Template

<!-- attention, we have the c_highlight class -->
<!-- c_highlight is the selector property value of the directive -->

<p class="c_highlight">
    Some text.
</p>

And our directive

import {Component,HostListener,Directive,HostBinding} from '@angular/core';

@Directive({
    // this directive will work only if the DOM el has the c_highlight class
    selector: '.c_highlight'
 })
export class HostDirective {

  // we could pass lots of thing to the HostBinding function. 
  // like class.valid or attr.required etc.

  @HostBinding('style.backgroundColor') c_colorrr = "red"; 

  @HostListener('mouseenter') c_onEnterrr() {
   this.c_colorrr= "blue" ;
  }

  @HostListener('mouseleave') c_onLeaveee() {
   this.c_colorrr = "yellow" ;
  } 
}

Html.RenderPartial() syntax with Razor

Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

Void methods require a semicolon at the end of the calling code.

In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

like so

<% Html.RenderPartial("Path/to/my/partial/view"); %>

when you are using the Razor view engine the equivalent is

@{Html.RenderPartial("Path/to/my/partial/view");}

Throwing multiple exceptions in a method of an interface in java

You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read

public class MyClass implements MyInterface {
  public void find(int x) throws A_Exception, B_Exception{
    ----
    ----
    ---
  }
}

Then an interface would look like this

public interface MyInterface {
  void find(int x) throws A_Exception, B_Exception;
}

What does %w(array) mean?

Though it's an old post, the question keep coming up and the answers don't always seem clear to me, so, here's my thoughts:

%w and %W are examples of General Delimited Input types, that relate to Arrays. There are other types that include %q, %Q, %r, %x and %i.

The difference between the upper and lower case version is that it gives us access to the features of single and double quotes. With single quotes and (lowercase) %w, we have no code interpolation (#{someCode}) and a limited range of escape characters that work (\\, \n). With double quotes and (uppercase) %W we do have access to these features.

The delimiter used can be any character, not just the open parenthesis. Play with the examples above to see that in effect.

For a full write up with examples of %w and the full list, escape characters and delimiters, have a look at "Ruby - %w vs %W – secrets revealed!"

Get the current URL with JavaScript?

Getting the current URL with JavaScript :

  • window.location.toString();

  • window.location.href

Oracle SqlPlus - saving output in a file but don't show on screen

Right from the SQL*Plus manual
http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch8.htm#sthref1597

SET TERMOUT

SET TERMOUT OFF suppresses the display so that you can spool output from a script without seeing it on the screen.

If both spooling to file and writing to terminal are not required, use SET TERMOUT OFF in >SQL scripts to disable terminal output.

SET TERMOUT is not supported in iSQL*Plus

PHP code to convert a MySQL query to CSV

Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.

SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM test_table;

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

Git repository friendly method

git-tab-to-space() (
  d="$(mktemp -d)"
  git grep --cached -Il '' | grep -E "${1:-.}" | \
    xargs -I'{}' bash -c '\
    f="${1}/f" \
    && expand -t 4 "$0" > "$f" && \
    chmod --reference="$0" "$f" && \
    mv "$f" "$0"' \
    '{}' "$d" \
  ;
  rmdir "$d"
)

Act on all files under the current directory:

git-tab-to-space

Act only on C or C++ files:

git-tab-to-space '\.(c|h)(|pp)$'

You likely want this notably because of those annoying Makefiles which require tabs.

The command git grep --cached -Il '':

  • lists only the tracked files, so nothing inside .git
  • excludes directories, binary files (would be corrupted), and symlinks (would be converted to regular files)

as explained at: How to list all text (non-binary) files in a git repository?

chmod --reference keeps the file permissions unchanged: https://unix.stackexchange.com/questions/20645/clone-ownership-and-permissions-from-another-file Unfortunately I can't find a succinct POSIX alternative.

If your codebase had the crazy idea to allow functional raw tabs in strings, use:

expand -i

and then have fun going over all non start of line tabs one by one, which you can list with: Is it possible to git grep for tabs?

Tested on Ubuntu 18.04.

Force GUI update from UI Thread

Call label.Invalidate and then label.Update() - usually the update only happens after you exit the current function but calling Update forces it to update at that specific place in code. From MSDN:

The Invalidate method governs what gets painted or repainted. The Update method governs when the painting or repainting occurs. If you use the Invalidate and Update methods together rather than calling Refresh, what gets repainted depends on which overload of Invalidate you use. The Update method just forces the control to be painted immediately, but the Invalidate method governs what gets painted when you call the Update method.

Extracting an attribute value with beautifulsoup

For me:

<input id="color" value="Blue"/>

This can be fetched by below snippet.

page = requests.get("https://www.abcd.com")
soup = BeautifulSoup(page.content, 'html.parser')
colorName = soup.find(id='color')
print(color['value'])

Android - styling seek bar

All those answers are deprecated.

In 2019 it's easier to style your seekbar to your preferred color by changing your ProgressBar to this

<SeekBar
            android:id="@+id/seekBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progressTint="#36970f"
            android:thumbTint="#36970f"
            />

Styling your seekbar color programmatically try the following code

        seekBar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
        seekBar.getThumb().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);

How do I resolve "Cannot find module" error using Node.js?

Check if the enviroment variable NODE_PATH is set correctly and pointing to the node_modules path. nodejs uses this variable to search for the libraries

Easiest way to mask characters in HTML(5) text input

A little late, but a useful plugin that will actually use a mask to give a bit more restriction on user input.

<div class="col-sm-3 col-md-6 col-lg-4">
  <div class="form-group">
     <label for="addPhone">Phone Number *</label>
      <input id="addPhone" name="addPhone" type="text" class="form-control 
       required" data-mask="(999) 999-9999"placeholder>
    <span class="help-block">(999) 999-9999</span>
  </div>
</div>

 <!-- Input Mask -->
 <script src="js/plugins/jasny/jasny-bootstrap.min.js"></script>

enter image description here

More info on the plugin https://www.jasny.net/bootstrap/2.3.1/javascript.html#inputmask

Python and pip, list all versions of a package that's available?

I came up with dead-simple bash script. Thanks to jq's author.

#!/bin/bash
set -e

PACKAGE_JSON_URL="https://pypi.org/pypi/${1}/json"

curl -L -s "$PACKAGE_JSON_URL" | jq  -r '.releases | keys | .[]' | sort -V

Update:

  • Add sorting by version number.
  • Add -L to follow redirects.

Basic http file downloading and saving to disk in python?

Another clean way to save the file is this:

import csv
import urllib

urllib.retrieve("your url goes here" , "output.csv")

error: Libtool library used but 'LIBTOOL' is undefined

For people using Tiny Core Linux, you also need to install libtool-dev as it has the *.m4 files needed for libtoolize.

How to read a file line-by-line into a list?

In case that there are also empty lines in the document I like to read in the content and pass it through filter to prevent empty string elements

with open(myFile, "r") as f:
    excludeFileContent = list(filter(None, f.read().splitlines()))

How to get name of calling function/method in PHP?

I needed something to just list the calling classes/methods (working on a Magento project).

While debug_backtrace provides tons of useful information, the amount of information it spewed out for the Magento installation was overwhelming (over 82,000 lines!) Since I was only concerned with the calling function and class, I worked this little solution up:

$callers = debug_backtrace();
foreach( $callers as $call ) {
    echo "<br>" . $call['class'] . '->' . $call['function'];
}

The executable gets signed with invalid entitlements in Xcode

If the other good answers listed here aren't working for you, try opening Keychain Access and removing all 'iPhone Developer...' certificates other than the primary one you're using for code signing. I found that I had several revoked certificates, and certificates from my other teammates that needed to be deleted.

how to get javaScript event source element?

You should change the generated HTML to not use inline javascript, and use addEventListener instead.

If you can not in any way change the HTML, you could get the onclick attributes, the functions and arguments used, and "convert" it to unobtrusive javascript instead by removing the onclick handlers, and using event listeners.

We'd start by getting the values from the attributes

_x000D_
_x000D_
$('button').each(function(i, el) {_x000D_
    var funcs = [];_x000D_
_x000D_
 $(el).attr('onclick').split(';').map(function(item) {_x000D_
     var fn     = item.split('(').shift(),_x000D_
         params = item.match(/\(([^)]+)\)/), _x000D_
            args;_x000D_
            _x000D_
        if (params && params.length) {_x000D_
         args = params[1].split(',');_x000D_
            if (args && args.length) {_x000D_
                args = args.map(function(par) {_x000D_
              return par.trim().replace(/('")/g,"");_x000D_
             });_x000D_
            }_x000D_
        }_x000D_
        funcs.push([fn, args||[]]);_x000D_
    });_x000D_
  _x000D_
    $(el).data('args', funcs); // store in jQuery's $.data_x000D_
  _x000D_
    console.log( $(el).data('args') );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button onclick="doSomething('param')" id="id_button1">action1</button>_x000D_
<button onclick="doAnotherSomething('param1', 'param2')" id="id_button1">action2</button>._x000D_
<button onclick="doDifferentThing()" id="id_button3">action3</button>
_x000D_
_x000D_
_x000D_

That gives us an array of all and any global methods called by the onclick attribute, and the arguments passed, so we can replicate it.

Then we'd just remove all the inline javascript handlers

$('button').removeAttr('onclick')

and attach our own handlers

$('button').on('click', function() {...}

Inside those handlers we'd get the stored original function calls and their arguments, and call them.
As we know any function called by inline javascript are global, we can call them with window[functionName].apply(this-value, argumentsArray), so

$('button').on('click', function() {
    var element = this;
    $.each(($(this).data('args') || []), function(_,fn) {
        if (fn[0] in window) window[fn[0]].apply(element, fn[1]);
    });
});

And inside that click handler we can add anything we want before or after the original functions are called.

A working example

_x000D_
_x000D_
$('button').each(function(i, el) {_x000D_
    var funcs = [];_x000D_
_x000D_
 $(el).attr('onclick').split(';').map(function(item) {_x000D_
     var fn     = item.split('(').shift(),_x000D_
         params = item.match(/\(([^)]+)\)/), _x000D_
            args;_x000D_
            _x000D_
        if (params && params.length) {_x000D_
         args = params[1].split(',');_x000D_
            if (args && args.length) {_x000D_
                args = args.map(function(par) {_x000D_
              return par.trim().replace(/('")/g,"");_x000D_
             });_x000D_
            }_x000D_
        }_x000D_
        funcs.push([fn, args||[]]);_x000D_
    });_x000D_
    $(el).data('args', funcs);_x000D_
}).removeAttr('onclick').on('click', function() {_x000D_
 console.log('click handler for : ' + this.id);_x000D_
  _x000D_
 var element = this;_x000D_
 $.each(($(this).data('args') || []), function(_,fn) {_x000D_
     if (fn[0] in window) window[fn[0]].apply(element, fn[1]);_x000D_
    });_x000D_
  _x000D_
    console.log('after function call --------');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button onclick="doSomething('param');" id="id_button1">action1</button>_x000D_
<button onclick="doAnotherSomething('param1', 'param2')" id="id_button2">action2</button>._x000D_
<button onclick="doDifferentThing()" id="id_button3">action3</button>_x000D_
_x000D_
<script>_x000D_
 function doSomething(arg) { console.log('doSomething', arg) }_x000D_
    function doAnotherSomething(arg1, arg2) { console.log('doAnotherSomething', arg1, arg2) }_x000D_
    function doDifferentThing() { console.log('doDifferentThing','no arguments') }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Creating a JSON Array in node js

Build up a JavaScript data structure with the required information, then turn it into the json string at the end.

Based on what I think you're doing, try something like this:

var result = [];
for (var name in goals) {
  if (goals.hasOwnProperty(name)) {
    result.push({name: name, goals: goals[name]});
  }
}

res.contentType('application/json');
res.send(JSON.stringify(result));

or something along those lines.

How do I read image data from a URL in Python?

I use the requests library. It seems to be more robust.

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

Java get String CompareTo as a comparator object

If you do find yourslef needing a Comparator, and you already use Guava, you can use Ordering.natural().

Resize an Array while keeping current elements in Java?

It is not possible to change the Array Size. But you can copy the element of one array into another array by creating an Array of bigger size.

It is recommended to create Array of double size if Array is full and Reduce Array to halve if Array is one-half full

public class ResizingArrayStack1 {
    private String[] s;
    private int size = 0;
    private int index = 0;

    public void ResizingArrayStack1(int size) {
        this.size = size;
        s = new String[size];
    }


    public void push(String element) {
        if (index == s.length) {
            resize(2 * s.length);
        }
        s[index] = element;
        index++;
    }

    private void resize(int capacity) {
        String[] copy = new String[capacity];
        for (int i = 0; i < s.length; i++) {
            copy[i] = s[i];
            s = copy;
        }
    }

    public static void main(String[] args) {
        ResizingArrayStack1 rs = new ResizingArrayStack1();
        rs.push("a");
        rs.push("b");
        rs.push("c");
        rs.push("d");
    }
}

SHA1 vs md5 vs SHA256: which to use for a PHP login?

Everyone is talking about this like they can be hacked over the internet. As already stated, limiting attempts makes it impossible to crack a password over the Internet and has nothing to do with the hash.

The salt is a must, but the complexity or multiple salts doesn't even matter. Any salt alone stops the attacker from using a premade rainbow table. A unique salt per user stops the attacker from creating a new rainbow table to use against your entire user base.

The security really comes into play when the entire database is compromised and a hacker can then perform 100 million password attempts per second against the md5 hash. SHA512 is about 10,000 times slower. A complex password with today's power could still take 100 years to bruteforce with md5 and would take 10,000 times as long with SHA512. The salts don't stop a bruteforce at all as they always have to be known, which if the attacker downloaded your database, he probably was in your system anyway.

Convert Month Number to Month Name Function in SQL

SELECT DATENAME(MONTH,dateadd(month, -3,getdate()))

Object of class stdClass could not be converted to string

Most likely, the userdata() function is returning an object, not a string. Look into the documentation (or var_dump the return value) to find out which value you need to use.

Can I inject a service into a directive in AngularJS?

You can do injection on Directives, and it looks just like it does everywhere else.

app.directive('changeIt', ['myData', function(myData){
    return {
        restrict: 'C',
        link: function (scope, element, attrs) {
            scope.name = myData.name;
        }
    }
 }]);

How can I loop through all rows of a table? (MySQL)

    Use this:

    $stmt = $user->runQuery("SELECT * FROM tbl WHERE ID=:id");
    $stmt->bindparam(":id",$id);
    $stmt->execute();

        $stmt->bindColumn("a_b",$xx);
        $stmt->bindColumn("c_d",$yy);


    while($rows = $stmt->fetch(PDO::FETCH_BOUND))
    {
        //---insert into new tble
    }   

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting the same error today:

Error:Execution failed for task ':app:preDebugAndroidTestBuild'.> Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

What I did:

  • I simply updated all my dependencies to 27.1.1 instead of 26.1.0
  • Also, updated my compileSdkVersion 27 and targetSdkVersion 27 which were 26 earlier

And com.android.support:support-annotations error was gone!

For Ref:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

str.split() without any arguments splits on runs of whitespace characters:

>>> s = 'I am having a very nice day.'
>>> 
>>> len(s.split())
7

From the linked documentation:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

Just make sure build with correct web.xml configuration.I have update web.xml with tomcat configuration and it worked for me. Sample :-

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"_x000D_
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"_x000D_
 id="WebApp_ID" version="2.5">_x000D_
 <display-name>simulator</display-name>_x000D_
 <description>simulator app</description>_x000D_
_x000D_
_x000D_
    <!-- File upload  -->_x000D_
    <welcome-file-list>_x000D_
        <welcome-file>index.html</welcome-file>_x000D_
    </welcome-file-list>_x000D_
 <!-- excel simulation -->_x000D_
    <display-name>simulator</display-name>_x000D_
    <description>simulator app</description>_x000D_
    <!-- File upload  -->_x000D_
    <welcome-file-list>_x000D_
        <welcome-file>InsertPage.html</welcome-file>_x000D_
    </welcome-file-list>_x000D_
    <servlet>_x000D_
        <servlet-name>FileUploadServlet</servlet-name>_x000D_
        <servlet-class>clari5.excel.FileUploadServlet</servlet-class>_x000D_
        <load-on-startup>1</load-on-startup>_x000D_
    </servlet>_x000D_
    <servlet-mapping>_x000D_
        <servlet-name>FileUploadServlet</servlet-name>_x000D_
        <url-pattern>/excelSimulator/FileUploadServlet</url-pattern>_x000D_
    </servlet-mapping>_x000D_
_x000D_
_x000D_
_x000D_
</web-app>
_x000D_
_x000D_
_x000D_

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

Convert HTML + CSS to PDF

Important: Please note that this answer was written in 2009 and it might not be the most cost-effective solution today in 2019. Online alternatives are better today at this than they were back then.

Here are some online services that you can use:


Have a look at PrinceXML.

It's definitely the best HTML/CSS to PDF converter out there, although it's not free (But hey, your programming might not be free either, so if it saves you 10 hours of work, you're home free (since you also need to take into account that the alternative solutions will require you to setup a dedicated server with the right software)

Oh yeah, did I mention that this is the first (and probably only) HTML2PDF solution that does full ACID2 ?

PrinceXML Samples

How to get the last character of a string in a shell?

Every answer so far implies the word "shell" in the question equates to Bash.

This is how one could do that in a standard Bourne shell:

printf $str | tail -c 1

When to use the !important property in CSS

!important is somewhat like eval. It isn't a good solution to any problem, and there are very few problems that can't be solved without it.

How to convert a char array back to a string?

Try this:

CharSequence[] charArray = {"a","b","c"};

for (int i = 0; i < charArray.length; i++){
    String str = charArray.toString().join("", charArray[i]);
    System.out.print(str);
}

How can I clear previous output in Terminal in Mac OS X?

Command + K will clear previous output.

To clear entered text, first jump left with Command + A and then clear the text to the right of the pointer with Control + K.

Visual examples:

Enter image description here

call javascript function on hyperlink click

I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.

attachEvent / addEventListening allow multiple event handlers to be created.

Instant run in Android Studio 2.0 (how to turn off)

UPDATE

In Android Studio Version 3.5 and Above

Now Instant Run is removed, It has "Apply Changes". See official blog for more about the change.

we removed Instant Run and re-architectured and implemented from the ground-up a more practical approach in Android Studio 3.5 called Apply Changes.Apply Changes uses platform-specific APIs from Android Oreo and higher to ensure reliable and consistent behavior; unlike Instant Run, Apply Changes does not modify your APK. To support the changes, we re-architected the entire deployment pipeline to improve deployment speed, and also tweaked the run and deployment toolbar buttons for a more streamlined experience.

Now, As per stable available version 3.0 of Android studio,

If you need to turn off Instant Run, go to

File ? Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run.

enter image description here

How to change default format at created_at and updated_at value laravel

Use Carbon\Carbon;

$targetDate =  "2014-06-26 04:07:31";
Carbon::parse($targetDate)->format('Y-m-d');

Failed to load AppCompat ActionBar with unknown error in android studio

Faced the same problem in Android Studio 3.1.3

Just go to style.xml file

and replace Theme name

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

with

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

Then clean and rebuild the project.This will solve the error.

How to convert a huge list-of-vector to a matrix more efficiently?

This should be equivalent to your current code, only a lot faster:

output <- matrix(unlist(z), ncol = 10, byrow = TRUE)

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

How do you find the sum of all the numbers in an array in Java?

A bit surprised to see None of the above answers considers it can be multiple times faster using a thread pool. Here, parallel uses a fork-join thread pool and automatically break the stream in multiple parts and run them parallel and then merge. If you just remember the following line of code you can use it many places.

So the award for the fastest short and sweet code goes to -

int[] nums = {1,2,3};
int sum =  Arrays.stream(nums).parallel().reduce(0, (a,b)-> a+b);

Lets say you want to do sum of squares , then Arrays.stream(nums).parallel().map(x->x*x).reduce(0, (a,b)-> a+b). Idea is you can still perform reduce , without map .

What is the maximum possible length of a query string?

Different web stacks do support different lengths of http-requests. I know from experience that the early stacks of Safari only supported 4000 characters and thus had difficulty handling ASP.net pages because of the USER-STATE. This is even for POST, so you would have to check the browser and see what the stack limit is. I think that you may reach a limit even on newer browsers. I cannot remember but one of them (IE6, I think) had a limit of 16-bit limit, 32,768 or something.

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

Taskkill /f doesn't kill a process

I could solve my issue rearding this problem by killing explorer.exe which in turn was addicted to the process I wanted to kill. I guess this may also happen if processes open interfaces via hook which may be locked.

Clearing state es6 React

This is how I handle it:

class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this._initState = {
        a: 1,
        b: 2
      }
    this.state = this._initState;
  }

  _resetState(){
     this.setState(this._initState);
   }
}

Update: Actually this is wrong. For future readers please refer to @RaptoX answer. Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.

Laravel blank white screen

Try this, in the public/index.php page

error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set("display_errors", 1);

How to calculate Date difference in Hive

If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs. 

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Java: how do I get a class literal from a generic type?

Due to the exposed fact that Class literals doesn't have generic type information, I think you should assume that it will be impossible to get rid of all the warnings. In a way, using Class<Something> is the same as using a collection without specifying the generic type. The best I could come out with was:

private <C extends A<C>> List<C> getList(Class<C> cls) {
    List<C> res = new ArrayList<C>();
    // "snip"... some stuff happening in here, using cls
    return res;
}

public <C extends A<C>> List<A<C>> getList() {
    return getList(A.class);
}

What is the purpose of the single underscore "_" variable in Python?

As far as the Python languages is concerned, _ has no special meaning. It is a valid identifier just like _foo, foo_ or _f_o_o_.

Any special meaning of _ is purely by convention. Several cases are common:

  • A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.

    # iteration disregarding content
    sum(1 for _ in some_iterable)
    # unpacking disregarding specific elements
    head, *_ = values
    # function disregarding its argument
    def callback(_): return True
    
  • Many REPLs/shells store the result of the last top-level expression to builtins._.

    The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module. When not in interactive mode, _ has no special meaning and is not defined. [source]

    Due to the way names are looked up, unless shadowed by a global or local _ definition the bare _ refers to builtins._ .

    >>> 42
    42
    >>> f'the last answer is {_}'
    'the last answer is 42'
    >>> _
    'the last answer is 42'
    >>> _ = 4  # shadow ``builtins._`` with global ``_``
    >>> 23
    23
    >>> _
    4
    

    Note: Some shells such as ipython do not assign to builtins._ but special-case _.

  • In the context internationalization and localization, _ is used as an alias for the primary translation function.

    gettext.gettext(message)

    Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).

Get the last day of the month in SQL

From SQL Server 2012 you can use the EOMONTH function.

Returns the last day of the month that contains the specified date, with an optional offset.

Syntax

EOMONTH ( start_date [, month_to_add ] ) 

How ... I can find the last day of the month for any given date?

SELECT EOMONTH(@SomeGivenDate)

Get element type with jQuery

also you can use:

$("#elementId").get(0).tagName

Find the files that have been changed in last 24 hours

You can do that with

find . -mtime 0

From man find:

[The] time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago.

jQuery or Javascript - how to disable window scroll without overflow:hidden;

tfe answered this question in another post on StackOverflow: Answered

Another method would be to use:

$(document).bind("touchmove",function(event){
  event.preventDefault();
});

But it may prevent some of the jquery mobile functionality from working properly.

How to grep a text file which contains some binary data?

You could run the data file through cat -v, e.g

$ cat -v tmp/test.log | grep re
line1 re ^@^M
line3 re^M

which could be then further post-processed to remove the junk; this is most analogous to your query about using tr for the task.

-v simply tells cat to display non-printing characters.

java.lang.UnsupportedClassVersionError

This class was compiled with a JDK more recent than the one used for execution.

The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.

Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).

Shared folder between MacOSX and Windows on Virtual Box

I had the exact same issue, after rightly have configured in Mac OSX host a SharedFolder with Auto-Mount enabled. On the Guest OS, it is also required to install VirtualBox Guest Additions. For the case of Windows, it is:

VBoxWindowsAdditions.exe

Right after this installation, i could perfectly view the shared folder content under This PC and Network ("\VBOXSVR\Installers").

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

If the answers must be constrained to Google Sheets, this answer works but it has limitations and is clumsy enough UX that it may be hard to get others to adopt. In trying to solve this problem I've found that, for many applications, Airtable solves this by allowing for multi-select columns and the UX is worlds better.

Powershell script to check if service is started, if not then start it

[Array] $servers = "Server1","server2";
$service='YOUR SERVICE'

foreach($server in $servers)

{
    $srvc = Get-WmiObject -query "SELECT * FROM win32_service  WHERE   name LIKE '$service' " -computername $server  ;
    $res=Write-Output $srvc | Format-Table -AutoSize $server, $fmtMode, $fmtState, $fmtStatus ;  
   $srvc.startservice() 
   $res
}

How to embed fonts in HTML?

I asked this a while back. The answer is basically that it doesn't work. :(

How to Apply global font to whole HTML document

Use the following css:

* {
    font: Verdana, Arial, 'sans-serif' !important;/* <-- fonts */
}

The *-selector means any/all elements, but will obviously be on the bottom of the food chain when it comes to overriding more specific selectors.

Note that the !important-flag will render the font-style for * to be absolute, even if other selectors have been used to set the text (for example, the body or maybe a p).

Parsing JSON Object in Java

public class JsonParsing {

public static Properties properties = null;

public static JSONObject jsonObject = null;

static {
    properties = new Properties();
}

public static void main(String[] args) {

    try {

        JSONParser jsonParser = new JSONParser();

        File file = new File("src/main/java/read.json");

        Object object = jsonParser.parse(new FileReader(file));

        jsonObject = (JSONObject) object;

        parseJson(jsonObject);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public static void getArray(Object object2) throws ParseException {

    JSONArray jsonArr = (JSONArray) object2;

    for (int k = 0; k < jsonArr.size(); k++) {

        if (jsonArr.get(k) instanceof JSONObject) {
            parseJson((JSONObject) jsonArr.get(k));
        } else {
            System.out.println(jsonArr.get(k));
        }

    }
}

public static void parseJson(JSONObject jsonObject) throws ParseException {

    Set<Object> set = jsonObject.keySet();
    Iterator<Object> iterator = set.iterator();
    while (iterator.hasNext()) {
        Object obj = iterator.next();
        if (jsonObject.get(obj) instanceof JSONArray) {
            System.out.println(obj.toString());
            getArray(jsonObject.get(obj));
        } else {
            if (jsonObject.get(obj) instanceof JSONObject) {
                parseJson((JSONObject) jsonObject.get(obj));
            } else {
                System.out.println(obj.toString() + "\t"
                        + jsonObject.get(obj));
            }
        }
    }
}}

How to hide a div element depending on Model value? MVC

The below code should apply different CSS classes based on your Model's CanEdit Property value .

<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>

But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.

@if(Model.CanEdit)
{
  <div>Edit/Delete link goes here</div>
}

Task<> does not contain a definition for 'GetAwaiter'

I had this issue in one of my projects, where I found that I had set my project's .Net Framework version to 4.0 and async tasks are only supported in .Net Framework 4.5 onwards.

I simply changed my project settings to use .Net Framework 4.5 or above and it worked.

Change hover color on a button with Bootstrap customization

I had to add !important to get it to work. I also made my own class button-primary-override.

.button-primary-override:hover, 
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
    background-color: #42A5F5 !important;
    border-color: #42A5F5 !important;
    background-image: none !important;
    border: 0 !important;
}

Save file to specific folder with curl command

I don't think you can give a path to curl, but you can CD to the location, download and CD back.

cd target/path && { curl -O URL ; cd -; }

Or using subshell.

(cd target/path && curl -O URL)

Both ways will only download if path exists. -O keeps remote file name. After download it will return to original location.

If you need to set filename explicitly, you can use small -o option:

curl -o target/path/filename URL

Is it better to return null or empty collection?

From the perspective of managing complexity, a primary software engineering objective, we want to avoid propagating unnecessary cyclomatic complexity to the clients of an API. Returning a null to the client is like returning them the cyclomatic complexity cost of another code branch.

(This corresponds to a unit testing burden. You would need to write a test for the null return case, in addition to the empty collection return case.)

How do I commit only some files?

If you have already staged files, simply unstage them:

git reset HEAD [file-name-A.ext] [file-name-B.ext]

Then add them bit by bit back in.

JavaScript Extending Class

If you don't like the prototype approach, because it doesn't really behave in a nice OOP-way, you could try this:

var BaseClass = function() 
{
    this.some_var = "foobar";

    /**
     * @return string
     */
    this.someMethod = function() {
        return this.some_var;
    }
};

var MyClass = new Class({ extends: BaseClass }, function()
{
    /**
     * @param string value
     */
    this.__construct = function(value)
    {
        this.some_var = value;
    }
})

Using lightweight library (2k minified): https://github.com/haroldiedema/joii

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

clear() will be much more efficient. It will simply remove each and every item. Using removeAll(arraylist) will take a lot more work because it will check every item in arraylist to see if it exists in arraylist before removing it.

How to do a newline in output

Use "\n" instead of '\n'

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

How to compare variables to undefined, if I don’t know whether they exist?

The best way is to check the type, because undefined/null/false are a tricky thing in JS. So:

if(typeof obj !== "undefined") {
    // obj is a valid variable, do something here.
}

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

How do I convert a String to an int in Java?

An alternate solution is to use Apache Commons' NumberUtils:

int num = NumberUtils.toInt("1234");

The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.

Apache NumberUtils API Version 3.4

How to remove specific session in asp.net?

There are many ways to nullify session in ASP.NET. Session in essence is a cookie, set on client's browser and in ASP.NET, its name is usually ASP.NET_SessionId. So, theoretically if you delete that cookie (which in terms of browser means that you set its expiration date to some date in past, because cookies can't be deleted by developers), then you loose the session in server. Another way as you said is to use Session.Clear() method. But the best way is to set another irrelevant object (usually null value) in the session in correspondance to a key. For example, to nullify Session["FirstName"], simply set it to Session["FirstName"] = null.

Program to find prime numbers

U can use the normal prime number concept must only two factors (one and itself). So do like this,easy way

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PrimeNUmber
{
    class Program
    {
        static void FindPrimeNumber(long num)
        {
            for (long i = 1; i <= num; i++)
            {
                int totalFactors = 0;
                for (int j = 1; j <= i; j++)
                {
                    if (i % j == 0)
                    {
                        totalFactors = totalFactors + 1;
                    }
                }
                if (totalFactors == 2)
                {
                    Console.WriteLine(i);
                }
            }
        }

        static void Main(string[] args)
        {
            long num;
            Console.WriteLine("Enter any value");
            num = Convert.ToInt64(Console.ReadLine());
            FindPrimeNumber(num);
            Console.ReadLine();
        }
    }
}

How to remove all listeners in an element?

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);

If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

A process crashed in windows .. Crash dump location

I have observed on Windows 2008 the Windows Error Reporting crash dumps get staged in the folder:

C:\Users\All Users\Microsoft\Windows\WER\ReportQueue

Which, starting with Windows Vista, is an alias for:

C:\ProgramData\Microsoft\Windows\WER\ReportQueue

Get source jar files attached to Eclipse for Maven-managed dependencies

Right click on project -> maven -> download sources

How to change the server port from 3000?

You can change it in the webpack.dev.js file in config folder.

How to find files modified in last x minutes (find -mmin does not work as expected)

I can reproduce your problem if there are no files in the directory that were modified in the last hour. In that case, find . -mmin -60 returns nothing. The command find . -mmin -60 |xargs ls -l, however, returns every file in the directory which is consistent with what happens when ls -l is run without an argument.

To make sure that ls -l is only run when a file is found, try:

find . -mmin -60 -type f -exec ls -l {} +

How to copy data from one table to another new table in MySQL?

You can easily get data from another table. You have to add fields only you want.

The mysql query is:

INSERT INTO table_name1(fields you want)
  SELECT fields you want FROM table_name2


where, the values are copied from table2 to table1

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Was able to fix the issue by updating NVIDIA device drivers to the latest (v446.14). NVIDIA drivers download link here.

Install python 2.6 in CentOS

When you install your python version (in this case it is python2.6) then issue this command to create your virtualenv:

virtualenv -p /usr/bin/python2.6 /your/virtualenv/path/here/

How to create strings containing double quotes in Excel formulas?

I use a function for this (if the workbook already has VBA).

Function Quote(inputText As String) As String
  Quote = Chr(34) & inputText & Chr(34)
End Function

This is from Sue Mosher's book "Microsoft Outlook Programming". Then your formula would be:

="Maurice "&Quote("Rocket")&" Richard"

This is similar to what Dave DuPlantis posted.

How do I make a C++ macro behave like a function?

Here is an answer coming right from the libc6! Taking a look at /usr/include/x86_64-linux-gnu/bits/byteswap.h, I found the trick you were looking for.

A few critics of previous solutions:

  • Kip's solution does not permit evaluating to an expression, which is in the end often needed.
  • coppro's solution does not permit assigning a variable as the expressions are separate, but can evaluate to an expression.
  • Steve Jessop's solution uses the C++11 auto keyword, that's fine, but feel free to use the known/expected type instead.

The trick is to use both the (expr,expr) construct and a {} scope:

#define MACRO(X,Y) \
  ( \
    { \
      register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \
      std::cout << "1st arg is:" << __x << std::endl; \
      std::cout << "2nd arg is:" << __y << std::endl; \
      std::cout << "Sum is:" << (__x + __y) << std::endl; \
      __x + __y; \
    } \
  )

Note the use of the register keyword, it's only a hint to the compiler. The X and Y macro parameters are (already) surrounded in parenthesis and casted to an expected type. This solution works properly with pre- and post-increment as parameters are evaluated only once.

For the example purpose, even though not requested, I added the __x + __y; statement, which is the way to make the whole bloc to be evaluated as that precise expression.

It's safer to use void(); if you want to make sure the macro won't evaluate to an expression, thus being illegal where an rvalue is expected.

However, the solution is not ISO C++ compliant as will complain g++ -pedantic:

warning: ISO C++ forbids braced-groups within expressions [-pedantic]

In order to give some rest to g++, use (__extension__ OLD_WHOLE_MACRO_CONTENT_HERE) so that the new definition reads:

#define MACRO(X,Y) \
  (__extension__ ( \
    { \
      register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \
      std::cout << "1st arg is:" << __x << std::endl; \
      std::cout << "2nd arg is:" << __y << std::endl; \
      std::cout << "Sum is:" << (__x + __y) << std::endl; \
      __x + __y; \
    } \
  ))

In order to improve my solution even a bit more, let's use the __typeof__ keyword, as seen in MIN and MAX in C:

#define MACRO(X,Y) \
  (__extension__ ( \
    { \
      __typeof__(X) __x = (X); \
      __typeof__(Y) __y = (Y); \
      std::cout << "1st arg is:" << __x << std::endl; \
      std::cout << "2nd arg is:" << __y << std::endl; \
      std::cout << "Sum is:" << (__x + __y) << std::endl; \
      __x + __y; \
    } \
  ))

Now the compiler will determine the appropriate type. This too is a gcc extension.

Note the removal of the register keyword, as it would the following warning when used with a class type:

warning: address requested for ‘__x’, which is declared ‘register’ [-Wextra]

JavaScript: undefined !== undefined?

From - JQuery_Core_Style_Guidelines

  • Global Variables:
    typeof variable === "undefined"

  • Local Variables:
    variable === undefined

  • Properties:
    object.prop === undefined

Getting HTML elements by their attribute names

I think you want to take a look at jQuery since that Javascript library provides a lot of functionality you might want to use in this kind of cases. In your case you could write (or find one on the internet) a hasAttribute method, like so (not tested):

$.fn.hasAttribute = function(tagName, attrName){
  var result = [];
  $.each($(tagName), function(index, value) { 
     var attr = $(this).attr(attrName); 
     if (typeof attr !== 'undefined' && attr !== false)
        result.push($(this));
  });
  return result;
}

How do I resolve a TesseractNotFoundError?

You are probably missing tesseract-ocr from your machine. Check the installation instructions here: https://github.com/tesseract-ocr/tesseract/wiki

On a Mac, you can just install using homebrew:

brew install tesseract

It should run fine after that

How to install psycopg2 with "pip" on Python?

Besides installing the required packages, I also needed to manually add PostgreSQL bin directory to PATH.
$vi ~/.bash_profile
Add PATH=/usr/pgsql-9.2/bin:$PATH before export PATH.
$source ~/.bash_profile
$pip install psycopg2

php variable in html no other way than: <?php echo $var; ?>

There's the short tag version of your code, which is now completely acceptable to use despite antiquated recommendations otherwise:

<input type="hidden" name="type" value="<?= $var ?>" >

which (prior to PHP 5.4) requires short tags be enabled in your php configuration. It functions exactly as the code you typed; these lines are literally identical in their internal implementation:

<?= $var1, $var2 ?>
<?php echo $var1, $var2 ?>

That's about it for built-in solutions. There are plenty of 3rd party template libraries that make it easier to embed data in your output, smarty is a good place to start.

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

AndroidStudio Menu:

Build/Clean Project

Update old dependencies

Parse DateTime string in JavaScript

I'v been used following code in IE. (IE8 compatible)

var dString = "2013.2.4";
var myDate = new Date( dString.replace(/(\d+)\.(\d+)\.(\d+)/,"$2/$3/$1") );
alert( "my date:"+ myDate );

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

In clean Ubuntu 16.04 LTS, MariaDB root login for localhost changed from password style to sudo login style...

so, just do

sudo mysql -u root

since we want to login with password, create another user 'user'

in MariaDB console... (you get in MariaDB console with 'sudo mysql -u root')

use mysql
CREATE USER 'user'@'localhost' IDENTIFIED BY 'yourpassword';
\q

then in bash shell prompt,

mysql-workbench

and you can login with 'user' with 'yourpassword' on localhost

How to: "Separate table rows with a line"

You have to use CSS.

In my opinion when you have a table often it is good with a separate line each side of the line.

Try this code:

HTML:

<table>
    <tr class="row"><td>row 1</td></tr>
    <tr class="row"><td>row 2</td></tr>
</table>

CSS:

.row {
    border:1px solid black; 
}

Bye

Andrea

jQuery append() vs appendChild()

appendChild is a DOM vanilla-js function.

append is a jQuery function.

They each have their own quirks.

Console output in a Qt GUI app?

So many answers to this topic. 0.0

So I tried it with Qt5.x from Win7 to Win10. It took me some hours to have a good working solution which doesn't produce any problems somewhere in the chain:

#include "mainwindow.h"

#include <QApplication>

#include <windows.h>
#include <stdio.h>
#include <iostream>

//
// Add to project file:
// CONFIG += console
//

int main( int argc, char *argv[] )
{
    if( argc < 2 )
    {
    #if defined( Q_OS_WIN )
        ::ShowWindow( ::GetConsoleWindow(), SW_HIDE ); //hide console window
    #endif
        QApplication a( argc, argv );
        MainWindow *w = new MainWindow;
        w->show();
        int e = a.exec();
        delete w; //needed to execute deconstructor
        exit( e ); //needed to exit the hidden console
        return e;
    }
    else
    {
        QCoreApplication a( argc, argv );
        std::string g;
        std::cout << "Enter name: ";
        std::cin >> g;
        std::cout << "Name is: " << g << std::endl;
        exit( 0 );
        return a.exec();
    }
}


I tried it also without the "CONFIG += console", but then you need to redirect the streams and create the console on your own:

#ifdef _WIN32
if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()){
    freopen("CONOUT$", "w", stdout);
    freopen("CONOUT$", "w", stderr);
    freopen("CONIN$", "r", stdin);
}
#endif

BUT this only works if you start it through a debugger, otherwise all inputs are directed towards the system too. Means, if you type a name via std::cin the system tries to execute the name as a command. (very strange)

Two other warnings to this attempt would be, that you can't use ::FreeConsole() it won't close it and if you start it through a console the app won't close.



Last there is a Qt help section in QApplication to this topic. I tried the example there with an application and it doesn't work for the GUI, it stucked somewhere in an endless loop and the GUI won't be rendered or it simply crashes:

QCoreApplication* createApplication(int &argc, char *argv[])
{
    for (int i = 1; i < argc; ++i)
        if (!qstrcmp(argv[i], "-no-gui"))
            return new QCoreApplication(argc, argv);
    return new QApplication(argc, argv);
}

int main(int argc, char* argv[])
{
    QScopedPointer<QCoreApplication> app(createApplication(argc, argv));

    if (qobject_cast<QApplication *>(app.data())) {
       // start GUI version...
    } else {
       // start non-GUI version...
    }

    return app->exec();
}


So if you are using Windows and Qt simply use the console option, hide the console if you need the GUI and close it via exit.

How do you round a floating point number in Perl?

If you are only concerned with getting an integer value out of a whole floating point number (i.e. 12347.9999 or 54321.0001), this approach (borrowed and modified from above) will do the trick:

my $rounded = floor($float + 0.1); 

Append TimeStamp to a File Name

Perhaps appending DateTime.Now.Ticks instead, is a tiny bit faster since you won't be creating 3 strings and the ticks value will always be unique also.

Best tool for inspecting PDF files?

I've used PDFBox with good success. Here's a sample of what the code looks like (back from version 0.7.2), that likely came from one of the provided examples:

// load the document
System.out.println("Reading document: " + filename);
PDDocument doc = null;                                                                                                                                                                                                          
doc = PDDocument.load(filename);

// look at all the document information
PDDocumentInformation info = doc.getDocumentInformation();
COSDictionary dict = info.getDictionary();
List l = dict.keyList();
for (Object o : l) {
    //System.out.println(o.toString() + " " + dict.getString(o));
    System.out.println(o.toString());
}

// look at the document catalog
PDDocumentCatalog cat = doc.getDocumentCatalog();
System.out.println("Catalog:" + cat);

List<PDPage> lp = cat.getAllPages();
System.out.println("# Pages: " + lp.size());
PDPage page = lp.get(4);
System.out.println("Page: " + page);
System.out.println("\tCropBox: " + page.getCropBox());
System.out.println("\tMediaBox: " + page.getMediaBox());
System.out.println("\tResources: " + page.getResources());
System.out.println("\tRotation: " + page.getRotation());
System.out.println("\tArtBox: " + page.getArtBox());
System.out.println("\tBleedBox: " + page.getBleedBox());
System.out.println("\tContents: " + page.getContents());
System.out.println("\tTrimBox: " + page.getTrimBox());
List<PDAnnotation> la = page.getAnnotations();
System.out.println("\t# Annotations: " + la.size());

Parsing XML with namespace in Python via 'ElementTree'

My solution is based on @Martijn Pieters' comment:

register_namespace only influences serialisation, not search.

So the trick here is to use different dictionaries for serialization and for searching.

namespaces = {
    '': 'http://www.example.com/default-schema',
    'spec': 'http://www.example.com/specialized-schema',
}

Now, register all namespaces for parsing and writing:

for name, value in namespaces.iteritems():
    ET.register_namespace(name, value)

For searching (find(), findall(), iterfind()) we need a non-empty prefix. Pass these functions a modified dictionary (here I modify the original dictionary, but this must be made only after the namespaces are registered).

self.namespaces['default'] = self.namespaces['']

Now, the functions from the find() family can be used with the default prefix:

print root.find('default:myelem', namespaces)

but

tree.write(destination)

does not use any prefixes for elements in the default namespace.

How to send HTTP request in java?

I know others will recommend Apache's http-client, but it adds complexity (i.e., more things that can go wrong) that is rarely warranted. For a simple task, java.net.URL will do.

URL url = new URL("http://www.y.com/url");
InputStream is = url.openStream();
try {
  /* Now read the retrieved document from the stream. */
  ...
} finally {
  is.close();
}

How to use router.navigateByUrl and router.navigate in Angular

navigateByUrl

routerLink directive as used like this:

<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>

is just a wrapper around imperative navigation using router and its navigateByUrl method:

router.navigateByUrl('/inbox/33/messages/44')

as can be seen from the sources:

export class RouterLink {
  ...

  @HostListener('click')
  onClick(): boolean {
    ...
    this.router.navigateByUrl(this.urlTree, extras);
    return true;
  }

So wherever you need to navigate a user to another route, just inject the router and use navigateByUrl method:

class MyComponent {
   constructor(router: Router) {
      this.router.navigateByUrl(...);
   }
}

navigate

There's another method on the router that you can use - navigate:

router.navigate(['/inbox/33/messages/44'])

difference between the two

Using router.navigateByUrl is similar to changing the location bar directly–we are providing the “whole” new URL. Whereas router.navigate creates a new URL by applying an array of passed-in commands, a patch, to the current URL.

To see the difference clearly, imagine that the current URL is '/inbox/11/messages/22(popup:compose)'.

With this URL, calling router.navigateByUrl('/inbox/33/messages/44') will result in '/inbox/33/messages/44'. But calling it with router.navigate(['/inbox/33/messages/44']) will result in '/inbox/33/messages/44(popup:compose)'.

Read more in the official docs.

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080'   
                                         ^^^^^

The https:// is wrong, it should be http://. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.

Transparent color of Bootstrap-3 Navbar

.navbar {
   background-color: transparent;
   background: transparent;
   border-color: transparent;
}

.navbar li { color: #000 } 

http://bootply.com/106969

How do I find ' % ' with the LIKE operator in SQL Server?

I would use

WHERE columnName LIKE '%[%]%'

SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.

The response to this Connect Item states

We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.

An example

CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)

CREATE NONCLUSTERED INDEX IX ON T(X)

INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT  TOP (100000)  'blah'
FROM master..spt_values v1,  master..spt_values v2


SET STATISTICS IO ON;
SELECT *
FROM T 
WHERE X LIKE '%[%]%'

SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'

Shows 457 logical reads for the first query and 33,335 for the second.

How can I use jQuery to move a div across the screen

Just a quick little function I drummed up that moves DIVs from their current spot to a target spot, one pixel step at a time. I tried to comment as best as I could, but the part you're interested in, is in example 1 and example 2, right after [$(function() { // jquery document.ready]. Put your bounds checking code there, and then exit the interval if conditions are met. Requires jQuery.

First the Demo: http://jsfiddle.net/pnYWY/

First the DIVs...

<style>
  .moveDiv {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }

  .moveDivB {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }
</style>


<div class="moveDiv"></div>
<div class="moveDivB"></div>

example 1) Start

// first animation (fire right away)
var myVar = setInterval(function(){
    $(function() { // jquery document.ready

        // returns true if it just took a step
        // returns false if the div has arrived
        if( !move_div_step(55,25,'.moveDiv') )
        {
            // arrived...
            console.log('arrived'); 
            clearInterval(myVar);
        }

    });
},50); // set speed here in ms for your delay

example 2) Delayed Start

// pause and then fire an animation..
setTimeout(function(){
    var myVarB = setInterval(function(){
        $(function() { // jquery document.ready
            // returns true if it just took a step
            // returns false if the div has arrived
            if( !move_div_step(25,55,'.moveDivB') )
            {
                // arrived...
                console.log('arrived'); 
                clearInterval(myVarB);
            }
        });
    },50); // set speed here in ms for your delay
},5000);// set speed here for delay before firing

Now the Function:

function move_div_step(xx,yy,target) // takes one pixel step toward target
{
    // using a line algorithm to move a div one step toward a given coordinate.
    var div_target = $(target);

    // get current x and current y
    var x = div_target.position().left; // offset is relative to document; position() is relative to parent;
    var y = div_target.position().top;

    // if x and y are = to xx and yy (destination), then div has arrived at it's destination.
    if(x == xx && y == yy)
        return false;

    // find the distances travelled
    var dx = xx - x;
    var dy = yy - y;

    // preventing time travel
    if(dx < 0)          dx *= -1;
    if(dy < 0)          dy *= -1;

    // determine speed of pixel travel...
    var sx=1, sy=1;

    if(dx > dy)         sy = dy/dx;
    else if(dy > dx)    sx = dx/dy;

    // find our one...
    if(sx == sy) // both are one..
    {
        if(x <= xx) // are we going forwards?
        {
            x++; y++;
        }
        else  // .. we are going backwards.
        {
            x--; y--;
        }       
    }
    else if(sx > sy) // x is the 1
    {
        if(x <= xx) // are we going forwards..?
            x++;
        else  // or backwards?
            x--;

        y += sy;
    }
    else if(sy > sx) // y is the 1 (eg: for every 1 pixel step in the y dir, we take 0.xxx step in the x
    {
        if(y <= yy) // going forwards?
            y++;
        else  // .. or backwards?
            y--;

        x += sx;
    }

    // move the div
    div_target.css("left", x);
    div_target.css("top",  y);

    return true;
}  // END :: function move_div_step(xx,yy,target)

PHP shell_exec() vs exec()

shell_exec returns all of the output stream as a string. exec returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.

See

C - gettimeofday for computing time?

The answer offered by @Daniel Kamil Kozar is the correct answer - gettimeofday actually should not be used to measure the elapsed time. Use clock_gettime(CLOCK_MONOTONIC) instead.


Man Pages say - The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2).

The Opengroup says - Applications should use the clock_gettime() function instead of the obsolescent gettimeofday() function.

Everyone seems to love gettimeofday until they run into a case where it does not work or is not there (VxWorks) ... clock_gettime is fantastically awesome and portable.

<<

Attributes / member variables in interfaces?

Java 8 introduced default methods for interfaces using which you can body to the methods. According to OOPs interfaces should act as contract between two systems/parties.

But still i found a way to achieve storing properties in the interface. I admit it is kinda ugly implementation.

   import java.util.Map;
   import java.util.WeakHashMap;

interface Rectangle
{

class Storage
{
    private static final Map<Rectangle, Integer> heightMap = new WeakHashMap<>();
    private static final Map<Rectangle, Integer> widthMap = new WeakHashMap<>();
}

default public int getHeight()
{
    return Storage.heightMap.get(this);
}

default public int getWidth()
{
    return Storage.widthMap.get(this);
}

default public void setHeight(int height)
{
    Storage.heightMap.put(this, height);
}

default public void setWidth(int width)
{
    Storage.widthMap.put(this, width);
}
}

This interface is ugly. For storing simple property it needed two hashmaps and each hashmap by default creates 16 entries by default. Additionally when real object is dereferenced JVM additionally need to remove this weak reference.

Xpath for href element

Best way to locate anchor elements is to use link=Re-Call:

selenium.click("link=Re-Call");

It will work..

find the array index of an object with a specific key value in underscore

Keepin' it simple:

// Find the index of the first element in array
// meeting specified condition.
//
var findIndex = function(arr, cond) {
  var i, x;
  for (i in arr) {
    x = arr[i];
    if (cond(x)) return parseInt(i);
  }
};

var idIsTwo = function(x) { return x.id == 2 }
var tv = [ {id: 1}, {id: 2} ]
var i = findIndex(tv, idIsTwo) // 1

Or, for non-haters, the CoffeeScript variant:

findIndex = (arr, cond) ->
  for i, x of arr
    return parseInt(i) if cond(x)

What strategies and tools are useful for finding memory leaks in .NET?

Just for the forgetting-to-dispose problem, try the solution described in this blog post. Here's the essence:

    public void Dispose ()
    {
        // Dispose logic here ...

        // It's a bad error if someone forgets to call Dispose,
        // so in Debug builds, we put a finalizer in to detect
        // the error. If Dispose is called, we suppress the
        // finalizer.
#if DEBUG
        GC.SuppressFinalize(this);
#endif
    }

#if DEBUG
    ~TimedLock()
    {
        // If this finalizer runs, someone somewhere failed to
        // call Dispose, which means we've failed to leave
        // a monitor!
        System.Diagnostics.Debug.Fail("Undisposed lock");
    }
#endif

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

docker : invalid reference format

For others come to here:
If you happen to put your docker command in a file, say run.sh, check your line separator. In Linux, it should be LR, otherwise you would get the same error.

What is sharding and why is it important?

If you have queries to a DBMS for which the locality is quite restricted (say, a user only fires selects with a 'where username = $my_username') it makes sense to put all the usernames starting with A-M on one server and all from N-Z on the other. By this you get near linear scaling for some queries.

Long story short: Sharding is basically the process of distributing tables onto different servers in order to balance the load onto both equally.

Of course, it's so much more complicated in reality. :)

WorksheetFunction.CountA - not working post upgrade to Office 2010

It seems there is a change in how Application.COUNTA works in VB7 vs VB6. I tried the following in both versions of VB.

   ReDim allData(0 To 1, 0 To 15)
   Debug.Print Application.WorksheetFunction.CountA(allData)

In VB6 this returns 0.

Inn VB7 it returns 32

Looks like VB7 doesn't consider COUNTA to be COUNTA anymore.

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

to_string is not a member of std, says g++ (mingw)

This happened to me as well, I just wrote up a quick function rather than worrying about updating my compiler.

string to_string(int number){
    string number_string = "";
    char ones_char;
    int ones = 0;
    while(true){
        ones = number % 10;
        switch(ones){
            case 0: ones_char = '0'; break;
            case 1: ones_char = '1'; break;
            case 2: ones_char = '2'; break;
            case 3: ones_char = '3'; break;
            case 4: ones_char = '4'; break;
            case 5: ones_char = '5'; break;
            case 6: ones_char = '6'; break;
            case 7: ones_char = '7'; break;
            case 8: ones_char = '8'; break;
            case 9: ones_char = '9'; break;
            default : ErrorHandling("Trouble converting number to string.");
        }
        number -= ones;
        number_string = ones_char + number_string;
        if(number == 0){
            break;
        }
        number = number/10;
    }
    return number_string;
}

C++ Convert string (or char*) to wstring (or wchar_t*)

This variant of it is my favourite in real life. It converts the input, if it is valid UTF-8, to the respective wstring. If the input is corrupted, the wstring is constructed out of the single bytes. This is extremely helpful if you cannot really be sure about the quality of your input data.

std::wstring convert(const std::string& input)
{
    try
    {
        std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
        return converter.from_bytes(input);
    }
    catch(std::range_error& e)
    {
        size_t length = input.length();
        std::wstring result;
        result.reserve(length);
        for(size_t i = 0; i < length; i++)
        {
            result.push_back(input[i] & 0xFF);
        }
        return result;
    }
}

Fully custom validation error message with Rails

A unique approach I haven't seen anyone mention!

The only way I was able to get all the customisation I wanted was to use an after_validation callback to allow me to manipulate the error message.

  1. Allow the validation message to be created as normal, you don't need to try and change it in the validation helper.

  2. create an after_validation callback that will replace that validation message in the back-end before it gets to the view.

  3. In the after_validation method you can do anything you want with the validation message, just like a normal string! You can even use dynamic values and insert them into the validation message.


#this could be any validation
validates_presence_of :song_rep_xyz, :message => "whatever you want - who cares - we will replace you later"

after_validation :replace_validation_message

def replace_validation_message
    custom_value = #any value you would like
    errors.messages[:name_of_the_attribute] = ["^This is the replacement message where 
    you can now add your own dynamic values!!! #{custom_value}"]
end

The after_validation method will have far greater scope than the built in rails validation helper, so you will be able to access the object you are validating like you are trying to do with object.file_name. Which does not work in the validation helper where you are trying to call it.

Note: we use the ^ to get rid of the attribute name at the beginning of the validation as @Rystraum pointed out referencing this gem

How to decide when to use Node.js?

My one more reason to choose Node.js for a new project is:

Be able to do pure cloud based development

I have used Cloud9 IDE for a while and now I can't imagine without it, it covers all the development lifecycles. All you need is a browser and you can code anytime anywhere on any devices. You don't need to check in code in one Computer(like at home), then checkout in another computer(like at work place).

Of course, there maybe cloud based IDE for other languages or platforms (Cloud 9 IDE is adding supports for other languages as well), but using Cloud 9 to do Node.js developement is really a great experience for me.

saving a file (from stream) to disk using c#

For the filestream:

//Check if the directory exists
if (!System.IO.Directory.Exists(@"C:\yourDirectory"))
{
    System.IO.Directory.CreateDirectory(@"C:\yourDirectory");
}

//Write the file
using (System.IO.StreamWriter outfile = new System.IO.StreamWriter(@"C:\yourDirectory\yourFile.txt"))
{
    outfile.Write(yourFileAsString);
}

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());

This works for me.

How to embed YouTube videos in PHP?

luvboy,

If i understand clearly, user provides the URL/code of the Youtube video and then that video is displayed on the page.

For that, just write a simple page, with layout etc.. Copy video embed code from youtube and paste it in your page. Replace embed code with some field, say VideoID. Set this VideoId to code provided by your user.

edit: see answer by Alec Smart.

JQuery addclass to selected div, remove class if another div is selected

In this mode you can find all element which has class active and remove it

try this

$(document).ready(function() {
        $(this.attr('id')).click(function () {
           $(document).find('.active').removeClass('active');
           var DivId = $(this).attr('id');
           alert(DivId);
           $(this).addClass('active');
        });
  });

Is there an opposite of include? for Ruby Arrays?

I was looking up on this for myself, found this, and then a solution. People are using confusing methods and some methods that don't work in certain situations or not at all.

I know it's too late now, considering this was posted 6 years ago, but hopefully future visitors find this (and hopefully, it can clean up their, and your, code.)

Simple solution:

if not @players.include?(p.name) do
  ....
end

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

Check div is hidden using jquery

Try checking for the :visible property instead.

if($('#car2').not(':visible'))
{
    alert('car 2 is hidden');       
}

Is there a JavaScript function that can pad a string to get to a determined length?

Based on the best answers of this question I have made a prototype for String called padLeft (exactly like we have in C#):

String.prototype.padLeft = function (paddingChar, totalWidth) {
    if (this.toString().length >= totalWidth)
        return this.toString();

    var array = new Array(totalWidth); 

    for (i = 0; i < array.length; i++)
        array[i] = paddingChar;

    return (array.join("") + this.toString()).slice(-array.length);
}

Usage:

var str = "12345";
console.log(str.padLeft("0", 10)); //Result is: "0000012345"

JsFiddle

How to remove non-alphanumeric characters?

You can split the string into characters and filter it.

<?php 

function filter_alphanum($string) {
    $characters = str_split($string);
    $alphaNumeric = array_filter($characters,"ctype_alnum");
    return join($alphaNumeric);
}

$res = filter_alphanum("a!bc!#123");
print_r($res); // abc123

?>

SSL Error: CERT_UNTRUSTED while using npm command

Since i stumbled on the post via google:

Try using npm ci it will be much than an npm install.

From the manual:

In short, the main differences between using npm install and npm ci are:

  • The project must have an existing package-lock.json or npm-shrinkwrap.json.
  • If dependencies in the package lock do not match those in package.json, npm ci will exit with an error, instead of updating the package lock.
  • npm ci can only install entire projects at a time: individual dependencies cannot be added with this command.
  • If a node_modules is already present, it will be automatically removed before npm ci begins its install.
  • It will never write to package.json or any of the package-locks: installs are essentially frozen.

"inappropriate ioctl for device"

Ran into this error today while trying to use code to delete a folder/files that are living on a Windoze 7 box that's mounted as a share on a Centos server. Got the inappropriate icotl for device error and tried everything that came to mind. Read just about every post on the net related to this.

Obviously the problem was isolated to the mounted Windoze share on the Linux server. Looked at the file permissions on the Windoze box and noted the files had their permissions set to read only.

Changed those, went back to the Linux server and all worked as expected. This may not be the solution for most but hopefully it saves someone some time.

How to correctly use the ASP.NET FileUpload control

My solution in code behind was:

System.Web.UI.WebControls.FileUpload fileUpload;

I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.

How do I convert the date from one format to another date object in another format without using any deprecated classes?

  private String formatDate(String date, String inputFormat, String outputFormat) {

    String newDate;
    DateFormat inputDateFormat = new SimpleDateFormat(inputFormat);
    inputDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateFormat outputDateFormat = new SimpleDateFormat(outputFormat);
    try {
        newDate = outputDateFormat.format((inputDateFormat.parse(date)));
    } catch (Exception e) {
        newDate = "";
    }
    return newDate;

}

Colon (:) in Python list index

a[len(a):] - This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)] it will get you the beginning to whatever is len(a).

Convert object to JSON string in C#

Use .net inbuilt class JavaScriptSerializer

  JavaScriptSerializer js = new JavaScriptSerializer();
  string json = js.Serialize(obj);

What is an .axd file?

from Google

An .axd file is a HTTP Handler file. There are two types of .axd files.

  1. ScriptResource.axd
  2. WebResource.axd

These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.

Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere

And ofcourse it is necessary

How can I get the max (or min) value in a vector?

Let,

 #include <vector>

 vector<int> v {1, 2, 3, -1, -2, -3};

If the vector is sorted in ascending or descending order then you can find it with complexity O(1).

For a vector of ascending order the first element is the smallest element, you can get it by v[0] (0 based indexing) and last element is the largest element, you can get it by v[sizeOfVector-1].

If the vector is sorted in descending order then the last element is the smallest element,you can get it by v[sizeOfVector-1] and first element is the largest element, you can get it by v[0].

If the vector is not sorted then you have to iterate over the vector to get the smallest/largest element.In this case time complexity is O(n), here n is the size of vector.

int smallest_element = v[0]; //let, first element is the smallest one
int largest_element = v[0]; //also let, first element is the biggest one
for(int i = 1; i < v.size(); i++)  //start iterating from the second element
{
    if(v[i] < smallest_element)
    {
       smallest_element = v[i];
    }
    if(v[i] > largest_element)
    {
       largest_element = v[i];
    }
}

You can use iterator,

for (vector<int>:: iterator it = v.begin(); it != v.end(); it++)
{
    if(*it < smallest_element) //used *it (with asterisk), because it's an iterator
    {
      smallest_element = *it;
    }
    if(*it > largest_element)
    {
      largest_element = *it;
    }
}

You can calculate it in input section (when you have to find smallest or largest element from a given vector)

int smallest_element, largest_element, value;
vector <int> v;
int n;//n is the number of elements to enter
cin >> n;
for(int i = 0;i<n;i++)
{
    cin>>value;
    if(i==0)
    {
        smallest_element= value; //smallest_element=v[0];
        largest_element= value; //also, largest_element = v[0]
    }

    if(value<smallest_element and i>0)
    {
        smallest_element = value;
    }

    if(value>largest_element and i>0)
    {
        largest_element = value;
    }
    v.push_back(value);
}

Also you can get smallest/largest element by built in functions

#include<algorithm>

int smallest_element = *min_element(v.begin(),v.end());

int largest_element  = *max_element(v.begin(),v.end());

You can get smallest/largest element of any range by using this functions. such as,

vector<int> v {1,2,3,-1,-2,-3};

cout << *min_element(v.begin(), v.begin() + 3); //this will print 1,smallest element of first three elements

cout << *max_element(v.begin(), v.begin() + 3); //largest element of first three elements

cout << *min_element(v.begin() + 2, v.begin() + 5); // -2, smallest element between third and fifth element (inclusive)

cout << *max_element(v.begin() + 2, v.begin()+5); //largest element between third and first element (inclusive)

I have used asterisk (*), before min_element()/max_element() functions. Because both of them return iterator. All codes are in c++.

Trying Gradle build - "Task 'build' not found in root project"

You didn't do what you're being asked to do.

What is asked:

I have to execute ../gradlew build

What you do

cd ..
gradlew build

That's not the same thing.

The first one will use the gradlew command found in the .. directory (mdeinum...), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore.

The second one will execute the gradlew command found in the current directory (mdeinum...), and look for the build file to execute in the current directory, which is mdeinum....

So the build file executed is not the same.

How to disable margin-collapsing?

Every webkit based browser should support the properties -webkit-margin-collapse. There are also subproperties to only set it for the top or bottom margin. You can give it the values collapse (default), discard (sets margin to 0 if there is a neighboring margin), and separate (prevents margin collapse).

I've tested that this works on 2014 versions of Chrome and Safari. Unfortunately, I don't think this would be supported in IE because it's not based on webkit.

Read Apple's Safari CSS Reference for a full explanation.

If you check Mozilla's CSS webkit extensions page, they list these properties as proprietary and recommend not to use them. This is because they're likely not going to go into standard CSS anytime soon and only webkit based browsers will support them.

Regex number between 1 and 100

I use for this angular 6

try this.

^([0-9]\.[0-9]{1}|[0-9]\.[0-9]{2}|\.[0-9]{2}|[1-9][0-9]\.[0-9]{1}|[1-9][0-9]\.[0-9]{2}|[0-9][0-9]|[1-9][0-9]\.[0-9]{2})$|^([0-9]|[0-9][0-9]|[0-99])$|^100$

it's validate 0.00 - 100. with two decimal places.

hope this will help

<input matInput [(ngModel)]="commission" type="number" max="100" min="0" name="rateInput" pattern="^(\.[0-9]{2}|[0-9]\.[0-9]{2}|[0-9][0-9]|[1-9][0-9]\.[0-9]{2})$|^([0-9]|[0-9][0-9]|[0-99])$|^100$" required #rateInput2="ngModel"><span>%</span><br>

Number should be between 0 and 100

Javascript loop through object array?

The suggested for loop is quite fine but you have to check the properties with hasOwnProperty. I'd rather suggest using Object.keys() that only returns 'own properties' of the object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)

_x000D_
_x000D_
var data = {_x000D_
    "messages": [{_x000D_
        "msgFrom": "13223821242",_x000D_
        "msgBody": "Hi there"_x000D_
    }, {_x000D_
        "msgFrom": "Bill",_x000D_
        "msgBody": "Hello!"_x000D_
    }]_x000D_
};_x000D_
_x000D_
data.messages.forEach(function(message, index) {_x000D_
    console.log('message index '+ index);_x000D_
    Object.keys(message).forEach(function(prop) {    _x000D_
        console.log(prop + " = " + message[prop]);_x000D_
    });_x000D_
});
_x000D_
_x000D_
_x000D_

Python - Passing a function into another function

Just pass it in like any other parameter:

def a(x):
    return "a(%s)" % (x,)

def b(f,x):
    return f(x)

print b(a,10)

Exit a while loop in VBS/VBA

Incredibly old question, but bearing in mind that the OP said he does not want to use Do While and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop:

This never runs anything if the status is already at "Fail"...

While (i < 20 And Not bShouldStop)
    If (Status = "Fail") Then
        bShouldStop = True
    Else
        i = i + 1
        '
        ' Do Something
        '
    End If  
Wend

Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.

While (i < 20 And Not bShouldStop)
    i = i + 1
    '
    ' Do Something
    '

    If (Status = "Fail") Then
        bShouldStop = True
    End If  
Wend

Ultimately, if the variable Status is being modified inside the While (and assuming you don't need i outside the while, it makes no difference really, but just wanted to present multiple options...