Programs & Examples On #Squid

Squid is an open-source HTTP caching proxy server.

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

Set the maximum character length of a UITextField

I created this UITextFieldLimit subclass:

  • Multiple textfields supported
  • Set the text length limit
  • Paste prevention
  • Displays a label of left characters inside the textfield, get hidden when you stop editing.
  • Shake animation when no characters left.

Grab the UITextFieldLimit.h and UITextFieldLimit.m from this GitHub repository:

https://github.com/JonathanGurebo/UITextFieldLimit

and begin to test!

Mark your storyboard-created UITextField and link it to my subclass using the Identity Inspector:

Identity Inspector

Then you can link it to an IBOutlet and set the limit(default is 10).


Your ViewController.h file should contain: (if you wan't to modify the setting, like the limit)

#import "UITextFieldLimit.h"

/.../

@property (weak, nonatomic) IBOutlet UITextFieldLimit *textFieldLimit; // <--Your IBOutlet

Your ViewController.m file should @synthesize textFieldLimit.


Set the text length limit in your ViewController.m file:

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    [textFieldLimit setLimit:25];// <-- and you won't be able to put more than 25 characters in the TextField.
}

Hope the class helps you. Good luck!

How to get the selected item from ListView?

You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.

What you should change, in your above example, is to

public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    MyClass item = (MyClass) adapter.getItem(position);
}

File Explorer in Android Studio

Device Explorer path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/...

Logs File path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/storage/emulated/0/Android/data/com.app.domain/files/LogFiles/

Shared Preferences File path for Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/data/data/com.app.domain/shared_prefs/

RSpec: how to test if a method was called?

The below should work

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

Disabled href tag

There is no disabled attribute for hyperlinks. If you don't want something to be linked then you'll need to remove the <a> tag altogether.

Alternatively you can remove its href attribute - though this has other UX and Accessibility issues as noted in the comments below so is not recommended.

Convert UTC to local time in Rails 3

It is easy to configure it using your system local zone, Just in your application.rb add this

config.time_zone = Time.now.zone

Then, rails should show you timestamps in your localtime or you can use something like this instruction to get the localtime

Post.created_at.localtime

How to check if a line has one of the strings in a list?

This still loops through the cartesian product of the two lists, but it does it one line:

>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False

This also have the advantage that any short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings in linesX. If you want to find multiple occurrences you could do something like this:

>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]

If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.

How to dump a table to console?

Format as JSON (you can "beautify" in IDE later):

local function format_any_value(obj, buffer)
    local _type = type(obj)
    if _type == "table" then
        buffer[#buffer + 1] = '{"'
        for key, value in next, obj, nil do
            buffer[#buffer + 1] = tostring(key) .. '":'
            format_any_value(value, buffer)
            buffer[#buffer + 1] = ',"'
        end
        buffer[#buffer] = '}' -- note the overwrite
    elseif _type == "string" then
        buffer[#buffer + 1] = '"' .. obj .. '"'
    elseif _type == "boolean" or _type == "number" then
        buffer[#buffer + 1] = tostring(obj)
    else
        buffer[#buffer + 1] = '"???' .. _type .. '???"'
    end
end

Usage:

local function format_as_json(obj)
    if obj == nil then return "null" else
        local buffer = {}
        format_any_value(obj, buffer)
        return table.concat(buffer)
    end
end

local function print_as_json(obj)
    print(_format_as_json(obj))
end

print_as_json {1, 2, 3}
print_as_json(nil)
print_as_json("string")
print_as_json {[1] = 1, [2] = 2, three = { { true } }, four = "four"}

BTW, I also wrote several other solutions: a very fast one, and one with special characters escaping: https://github.com/vn971/fast_json_encode

Difference between "read commited" and "repeatable read"

Read committed is an isolation level that guarantees that any data read was committed at the moment is read. It simply restricts the reader from seeing any intermediate, uncommitted, 'dirty' read. It makes no promise whatsoever that if the transaction re-issues the read, will find the Same data, data is free to change after it was read.

Repeatable read is a higher isolation level, that in addition to the guarantees of the read committed level, it also guarantees that any data read cannot change, if the transaction reads the same data again, it will find the previously read data in place, unchanged, and available to read.

The next isolation level, serializable, makes an even stronger guarantee: in addition to everything repeatable read guarantees, it also guarantees that no new data can be seen by a subsequent read.

Say you have a table T with a column C with one row in it, say it has the value '1'. And consider you have a simple task like the following:

BEGIN TRANSACTION;
SELECT * FROM T;
WAITFOR DELAY '00:01:00'
SELECT * FROM T;
COMMIT;

That is a simple task that issue two reads from table T, with a delay of 1 minute between them.

  • under READ COMMITTED, the second SELECT may return any data. A concurrent transaction may update the record, delete it, insert new records. The second select will always see the new data.
  • under REPEATABLE READ the second SELECT is guaranteed to display at least the rows that were returned from the first SELECT unchanged. New rows may be added by a concurrent transaction in that one minute, but the existing rows cannot be deleted nor changed.
  • under SERIALIZABLE reads the second select is guaranteed to see exactly the same rows as the first. No row can change, nor deleted, nor new rows could be inserted by a concurrent transaction.

If you follow the logic above you can quickly realize that SERIALIZABLE transactions, while they may make life easy for you, are always completely blocking every possible concurrent operation, since they require that nobody can modify, delete nor insert any row. The default transaction isolation level of the .Net System.Transactions scope is serializable, and this usually explains the abysmal performance that results.

And finally, there is also the SNAPSHOT isolation level. SNAPSHOT isolation level makes the same guarantees as serializable, but not by requiring that no concurrent transaction can modify the data. Instead, it forces every reader to see its own version of the world (it's own 'snapshot'). This makes it very easy to program against as well as very scalable as it does not block concurrent updates. However, that benefit comes with a price: extra server resource consumption.

Supplemental reads:

getResourceAsStream() is always returning null

I don't know if this applies to JAX-WS, but for JAX-RS I was able to access a file by injecting a ServletContext and then calling getResourceAsStream() on it:

@Context ServletContext servletContext;
...
InputStream is = servletContext.getResourceAsStream("/WEB-INF/test_model.js");

Note that, at least in GlassFish 3.1, the path had to be absolute, i.e., start with slash. More here: How do I use a properties file with jax-rs?

Using GregorianCalendar with SimpleDateFormat

  1. You are putting there a two-digits year. The first century. And the Gregorian calendar started in the 16th century. I think you should add 2000 to the year.

  2. Month in the function new GregorianCalendar(year, month, days) is 0-based. Subtract 1 from the month there.

  3. Change the body of the second function as follows:

        String dateFormatted = null;
        SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
        try {
            dateFormatted = fmt.format(date);
        }
        catch ( IllegalArgumentException e){
            System.out.println(e.getMessage());
        }
        return dateFormatted;
    

After debugging, you'll see that simply GregorianCalendar can't be an argument of the fmt.format();.

Really, nobody needs GregorianCalendar as output, even you are told to return "a string".

Change the header of your format function to

public static String format(final Date date) 

and make the appropriate changes. fmt.format() will take the Date object gladly.

  1. Always after an unexpected exception arises, catch it yourself, don't allow the Java machine to do it. This way, you'll understand the problem.

'Class' does not contain a definition for 'Method'

There are three possibilities:

1) If you are referring old DLL then it cant be used. So you have refer new DLL

2) If you are using it in different namespace and trying to use the other namespace's dll then it wont refer this method.

3) You may need to rebuild the project

I think third option might be the cause for you. Please post more information in order to understand exact problem of yours.

Javascript - get array of dates between 2 dates

d3js provides a lot of handy functions and includes d3.time for easy date manipulations

https://github.com/d3/d3-time

For your specific request:

Utc

var range = d3.utcDay.range(new Date(), d3.utcDay.offset(new Date(), 7));

or local time

var range = d3.timeDay.range(new Date(), d3.timeDay.offset(new Date(), 7));

range will be an array of date objects that fall on the first possible value for each day

you can change timeDay to timeHour, timeMonth etc for the same results on different intervals

Python, creating objects

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:

class Student(object):
    name = ""
    age = 0
    major = ""

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    # Note: I didn't need to create a variable in the class definition before doing this.
    student.gpa = float(4.0)
    return student

I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.

C: How to free nodes in the linked list?

One function can do the job,

void free_list(node *pHead)
{
    node *pNode = pHead, *pNext;

    while (NULL != pNode)
    {
        pNext = pNode->next;
        free(pNode);
        pNode = pNext;
    }

}

How do I get the value of a registry key and ONLY the value using powershell

Harry Martyrossian mentions in a comment on his own answer that the
Get-ItemPropertyValue cmdlet was introduced in Powershell v5, which solves the problem:

PS> Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' 'ProgramFilesDir'
C:\Program Files

Alternatives for PowerShell v4-:

Here's an attempt to retain the efficiency while eliminating the need for repetition of the value name, which, however, is still a little cumbersome:

& { (Get-ItemProperty `
      -LiteralPath HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion `
      -Name $args `
    ).$args } 'ProgramFilesDir'

By using a script block, the value name can be passed in once as a parameter, and the parameter variable ($args) can then simply be used twice inside the block.

Alternatively, a simple helper function can ease the pain:

function Get-RegValue([String] $KeyPath, [String] $ValueName) {
  (Get-ItemProperty -LiteralPath $KeyPath -Name $ValueName).$ValueName
}

Note: All solutions above bypass the problem described in Ian Kemp's's answer - the need to use explicit quoting for certain value names when used as property names; e.g., .'15.0' - because the value names are passed as parameters and property access happens via a variable; e.g., .$ValueName


As for the other answers:

  • Andy Arismendi's helpful answer explains the annoyance with having to repeat the value name in order to get the value data efficiently.
  • M Jeremy Carter's helpful answer is more convenient, but can be a performance pitfall for keys with a large number of values, because an object with a large number of properties must be constructed.

How to declare a global variable in React?

The best way I have found so far is to use React Context but to isolate it inside a high order provider component.

How to use onResume()?

Most of the previous answers do a good job explaining how, why, and when to use onResume() but I would like to add something about re-creating your Activity.

I want to know if I want to restart the activity at the end of exectuion of an other what method is executed onCreate() or onResume()

The answer is onCreate() However, when deciding to actually re-create it, you should ask yourself how much of the Activity needs to be re-created. If it is data in an adapter, say for a list, then you can call notifyDataChanged() on the adapter to repopulate the adapter and not have to redraw everything.

Also, if you just need to update certain views but not all then it may be more efficient to call invalidate() on the view(s) that need updated. This will only redraw those views and possibly allow your application to run more smoothly. I hope this can help you.

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

Text Editor which shows \r\n?

The best for replace \n \t and more: Programmer's File Editor http://www.lancs.ac.uk/staff/steveb/cpaap/pfe/pfefiles.htm

How to uninstall Jenkins?

There is no uninstaller. Therefore, you need to:

  • Delete the directory containing Jenkins (or, if you're deploying the war -- remove the war from your container).

  • Remove ~/.jenkins.

  • Remove you startup scripts.

adding child nodes in treeview

I needed to do something similar and came across the same issues. I used the AfterSelect event to make sure I wasn't getting the previously selected node.

It's actually really easy to reference the correct node to receive the new child node.

private void TreeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
   //show dialogbox to let user name the new node
   frmDialogInput f = new frmDialogInput();
   f.ShowDialog();

    //find the node that was selected
    TreeNode myNode = TreeView1.SelectedNode;
    //create the new node to add
    TreeNode newNode = new TreeNode(f.EnteredText);
    //add the new child to the selected node
    myNode.Nodes.Add(newNode);
}

VB.net Need Text Box to Only Accept Numbers

Try this:

Private Sub txtCaseID_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtCaseID.KeyPress
    If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then e.KeyChar = ""
End Sub

Can I pass parameters in computed properties in Vue.Js

You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

Note that getters accessed via methods will run each time you call them, and the result is not cached.

That is called Method-Style Access and it is documented on the Vue.js docs.

Is there a "theirs" version of "git merge -s ours"?

Why doesn't it exist?

While I mention in "git command for making one branch like another" how to simulate git merge -s theirs, note that Git 2.15 (Q4 2017) is now clearer:

The documentation for '-X<option>' for merges was misleadingly written to suggest that "-s theirs" exists, which is not the case.

See commit c25d98b (25 Sep 2017) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 4da3e23, 28 Sep 2017)

merge-strategies: avoid implying that "-s theirs" exists

The description of -Xours merge option has a parenthetical note that tells the readers that it is very different from -s ours, which is correct, but the description of -Xtheirs that follows it carelessly says "this is the opposite of ours", giving a false impression that the readers also need to be warned that it is very different from -s theirs, which in reality does not even exist.

-Xtheirs is a strategy option applied to recursive strategy. This means that recursive strategy will still merge anything it can, and will only fall back to "theirs" logic in case of conflicts.

That debate for the pertinence or not of a theirs merge strategy was brought back recently in this Sept. 2017 thread.
It acknowledges older (2008) threads

In short, the previous discussion can be summarized to "we don't want '-s theirs' as it encourages the wrong workflow".

It mentions the alias:

mtheirs = !sh -c 'git merge -s ours --no-commit $1 && git read-tree -m -u $1' -

Yaroslav Halchenko tries to advocate once more for that strategy, but Junio C. Hamano adds:

The reason why ours and theirs are not symmetric is because you are you and not them---the control and ownership of our history and their history is not symmetric.

Once you decide that their history is the mainline, you'd rather want to treat your line of development as a side branch and make a merge in that direction, i.e. the first parent of the resulting merge is a commit on their history and the second parent is the last bad one of your history. So you would end up using "checkout their-history && merge -s ours your-history" to keep the first-parenthood sensible.

And at that point, use of "-s ours" is no longer a workaround for lack of "-s theirs".
It is a proper part of the desired semantics, i.e. from the point of view of the surviving canonical history line, you want to preserve what it did, nullifying what the other line of history did.

Junio adds, as commented by Mike Beaton:

git merge -s ours <their-ref> effectively says 'mark commits made up to <their-ref> on their branch as commits to be permanently ignored';
and this matters because, if you subsequently merge from later states of their branch, their later changes will be brought in without the ignored changes ever being brought in.

Create Word Document using PHP in Linux

By far the easiest way to create DOC files on Linux, using PHP is with the Zend Framework component phpLiveDocx.

From the project web site:

"phpLiveDocx allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge."

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

Insert/Update Many to Many Entity Framework . How do I do it?

Try this one for Updating:

[HttpPost]
public ActionResult Edit(Models.MathClass mathClassModel)
{
    //get current entry from db (db is context)
    var item = db.Entry<Models.MathClass>(mathClassModel);

    //change item state to modified
    item.State = System.Data.Entity.EntityState.Modified;

    //load existing items for ManyToMany collection
    item.Collection(i => i.Students).Load();

    //clear Student items          
    mathClassModel.Students.Clear();

    //add Toner items
    foreach (var studentId in mathClassModel.SelectedStudents)
    {
        var student = db.Student.Find(int.Parse(studentId));
        mathClassModel.Students.Add(student);
    }                

    if (ModelState.IsValid)
    {
       db.SaveChanges();
       return RedirectToAction("Index");
    }

    return View(mathClassModel);
}

How to get the concrete class name as a string?

 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'

Downloading all maven dependencies to a directory NOT in repository?

I found the next command

mvn dependency:copy-dependencies -Dclassifier=sources

here maven.apache.org

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

Change SQLite database mode to read-write

There can be several reasons for this error message:

  • Several processes have the database open at the same time (see the FAQ).

  • There is a plugin to compress and encrypt the database. It doesn't allow to modify the DB.

  • Lastly, another FAQ says: "Make sure that the directory containing the database file is also writable to the user executing the CGI script." I think this is because the engine needs to create more files in the directory.

  • The whole filesystem might be read only, for example after a crash.

  • On Unix systems, another process can replace the whole file.

java: use StringBuilder to insert at the beginning

How about:

StringBuilder builder = new StringBuilder();
for(int i=99;i>=0;i--){
    builder.append(Integer.toString(i));
}
builder.toString();

OR

StringBuilder builder = new StringBuilder();
for(int i=0;i<100;i++){
  builder.insert(0, Integer.toString(i));
}
builder.toString();

But with this, you are making the operation O(N^2) instead of O(N).

Snippet from java docs:

Inserts the string representation of the Object argument into this character sequence. The overall effect is exactly as if the second argument were converted to a string by the method String.valueOf(Object), and the characters of that string were then inserted into this character sequence at the indicated offset.

How to get the list of all database users

SELECT name FROM sys.database_principals WHERE
type_desc = 'SQL_USER' AND default_schema_name = 'dbo'

This selects all the users in the SQL server that the administrator created!

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

If you would like to use the values, say as part of csvfile csv.writer, the numbers can be formatted before creating a list:

df['label'].apply(lambda x: '%.17f' % x).values.tolist()

How to store directory files listing into an array?

This might work for you:

OIFS=$IFS; IFS=$'\n'; array=($(ls -ls)); IFS=$OIFS; echo "${array[1]}"

How to determine the content size of a UIWebView?

AFAIK you can use [webView sizeThatFits:CGSizeZero] to figure out it's content size.

What is a difference between unsigned int and signed int in C?

Assuming int is a 16 bit integer (which depends on the C implementation, most are 32 bit nowadays) the bit representation differs like the following:

 5 = 0000000000000101
-5 = 1111111111111011

if binary 1111111111111011 would be set to an unsigned int, it would be decimal 65531.

Statistics: combinations in Python

Using only standard library distributed with Python:

import itertools

def nCk(n, k):
    return len(list(itertools.combinations(range(n), k)))

C compile error: Id returned 1 exit status

Using code::blocks , I have solved this error by doing :

workspace properties > build target > build target files

and checking every project file.

jQuery animated number counter from zero to value

This is work for me !

<script type="text/javascript">
$(document).ready(function(){
        countnumber(0,40,"stat1",50);
        function countnumber(start,end,idtarget,duration){
            cc=setInterval(function(){
                if(start==end)
                {
                    $("#"+idtarget).html(start);
                    clearInterval(cc);
                }
                else
                {
                   $("#"+idtarget).html(start);
                   start++;
                }
            },duration);
        }
    });
</script>
<span id="span1"></span>

How to read barcodes with the camera on Android?

Here is sample code using camera api

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;

public class MainActivity extends AppCompatActivity {

TextView barcodeInfo;
SurfaceView cameraView;
CameraSource cameraSource;

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

    cameraView = (SurfaceView) findViewById(R.id.camera_view);
      barcodeInfo = (TextView) findViewById(R.id.txtContent);


    BarcodeDetector barcodeDetector =
            new BarcodeDetector.Builder(this)
                    .setBarcodeFormats(Barcode.CODE_128)//QR_CODE)
                    .build();

    cameraSource = new CameraSource
            .Builder(this, barcodeDetector)
            .setRequestedPreviewSize(640, 480)
            .build();

    cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {

            try {
                cameraSource.start(cameraView.getHolder());
            } catch (IOException ie) {
                Log.e("CAMERA SOURCE", ie.getMessage());
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            cameraSource.stop();
        }
    });


    barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {
        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {

            final SparseArray<Barcode> barcodes = detections.getDetectedItems();

            if (barcodes.size() != 0) {
                barcodeInfo.post(new Runnable() {    // Use the post method of the TextView
                    public void run() {
                        barcodeInfo.setText(    // Update the TextView
                                barcodes.valueAt(0).displayValue
                        );
                    }
                });
            }
        }
    });
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.gateway.cameraapibarcode.MainActivity">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <SurfaceView
        android:layout_width="640px"
        android:layout_height="480px"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:id="@+id/camera_view"/>

    <TextView
        android:text=" code reader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtContent"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Process"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imgview"/>
</LinearLayout>
</RelativeLayout>

build.gradle(Module:app)

add compile 'com.google.android.gms:play-services:7.8.+' in dependencies

Convert seconds to HH-MM-SS with JavaScript?

Here is a function to convert seconds to hh-mm-ss format based on powtac's answer here

jsfiddle

/** 
 * Convert seconds to hh-mm-ss format.
 * @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
  var hours   = Math.floor(totalSeconds / 3600);
  var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
  var seconds = totalSeconds - (hours * 3600) - (minutes * 60);

  // round seconds
  seconds = Math.round(seconds * 100) / 100

  var result = (hours < 10 ? "0" + hours : hours);
      result += "-" + (minutes < 10 ? "0" + minutes : minutes);
      result += "-" + (seconds  < 10 ? "0" + seconds : seconds);
  return result;
}

Example use

var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

HTML forms support GET and POST. (HTML5 at one point added PUT/DELETE, but those were dropped.)

XMLHttpRequest supports every method, including CHICKEN, though some method names are matched against case-insensitively (methods are case-sensitive per HTTP) and some method names are not supported at all for security reasons (e.g. CONNECT).

Browsers are slowly converging on the rules specified by XMLHttpRequest, but as the other comment pointed out there are still some differences.

How do I find out my MySQL URL, host, port and username?

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

sqlite database default time value 'now'

This is a full example based on the other answers and comments to the question. In the example the timestamp (created_at-column) is saved as unix epoch UTC timezone and converted to local timezone only when necessary.

Using unix epoch saves storage space - 4 bytes integer vs. 24 bytes string when stored as ISO8601 string, see datatypes. If 4 bytes is not enough that can be increased to 6 or 8 bytes.

Saving timestamp on UTC timezone makes it convenient to show a reasonable value on multiple timezones.

SQLite version is 3.8.6 that ships with Ubuntu LTS 14.04.

$ sqlite3 so.db
SQLite version 3.8.6 2014-08-15 11:46:33
Enter ".help" for usage hints.
sqlite> .headers on

create table if not exists example (
   id integer primary key autoincrement
  ,data text not null unique
  ,created_at integer(4) not null default (strftime('%s','now'))
);

insert into example(data) values
 ('foo')
,('bar')
;

select
 id
,data
,created_at as epoch
,datetime(created_at, 'unixepoch') as utc
,datetime(created_at, 'unixepoch', 'localtime') as localtime
from example
order by id
;

id|data|epoch     |utc                |localtime
1 |foo |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
2 |bar |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02

Localtime is correct as I'm located at UTC+2 DST at the moment of the query.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

Why is __dirname not defined in node REPL?

I was running a script from batch file as SYSTEM user and all variables like process.cwd() , path.resolve() and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.

Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.

// this should be the name of currently executed file
const currentFilename = 'index.js';

function veryHackyGetFolder() {
  try {
    throw new Error();
  } catch(e) {
    const fullMsg = e.stack.toString();
    const beginning = fullMsg.indexOf('file:///') + 8;
    const end = fullMsg.indexOf('\/' + currentFilename);
    const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\\');
    return dir;
  }
}

Usage

const dir = veryHackyGetFolder();

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

Check element CSS display with JavaScript

This answer is not exactly what you want, but it might be useful in some cases. If you know the element has some dimensions when displayed, you can also use this:

var hasDisplayNone = (element.offsetHeight === 0 && element.offsetWidth === 0);

EDIT: Why this might be better than direct check of CSS display property? Because you do not need to check all parent elements. If some parent element has display: none, its children are hidden too but still has element.style.display !== 'none'.

Web colors in an Android color xml resource file

Edit Answer of @rolnad :-Remove White space from name

<color name="Black">#000000</color>
<color name="Gunmetal">#2C3539</color>
<color name="Midnight">#2B1B17</color>
<color name="Charcoal">#34282C</color>
<color name="DarkSlateGrey">#25383C</color>
<color name="Oil">#3B3131</color>
<color name="BlackCat">#413839</color>
<color name="BlackEel">#463E3F</color>
<color name="BlackCow">#4C4646</color>
<color name="GrayWolf">#504A4B</color>
<color name="VampireGray">#565051</color>
<color name="GrayDolphin">#5C5858</color>
<color name="CarbonGray">#625D5D</color>
<color name="AshGray">#666362</color>
<color name="CloudyGray">#6D6968</color>
<color name="SmokeyGray">#726E6D</color>
<color name="Gray">#736F6E</color>
<color name="Granite">#837E7C</color>
<color name="BattleshipGray">#848482</color>
<color name="GrayCloud">#B6B6B4</color>
<color name="GrayGoose">#D1D0CE</color>
<color name="Platinum">#E5E4E2</color>
<color name="MetallicSilver">#BCC6CC</color>
<color name="BlueGray">#98AFC7</color>
<color name="LightSlateGray">#6D7B8D</color>
<color name="SlateGray">#657383</color>
<color name="JetGray">#616D7E</color>
<color name="MistBlue">#646D7E</color>
<color name="MarbleBlue">#566D7E</color>
<color name="SteelBlue">#4863A0</color>
<color name="BlueJay">#2B547E</color>
<color name="DarkSlateBlue">#2B3856</color>
<color name="MidnightBlue">#151B54</color>
<color name="NavyBlue">#000080</color>
<color name="BlueWhale">#342D7E</color>
<color name="LapisBlue">#15317E</color>
<color name="EarthBlue">#0000A0</color>
<color name="CobaltBlue">#0020C2</color>
<color name="BlueberryBlue">#0041C2</color>
<color name="SapphireBlue">#2554C7</color>
<color name="BlueEyes">#1569C7</color>
<color name="RoyalBlue">#2B60DE</color>
<color name="BlueOrchid">#1F45FC</color>
<color name="BlueLotus">#6960EC</color>
<color name="LightSlateBlue">#736AFF</color>
<color name="Slate_Blue">#357EC7</color>
<color name="SilkBlue">#488AC7</color>
<color name="BlueIvy">#3090C7</color>
<color name="BlueKoi">#659EC7</color>
<color name="ColumbiaBlue">#87AFC7</color>
<color name="BabyBlue">#95B9C7</color>
<color name="LightSteelBlue">#728FCE</color>
<color name="OceanBlue">#2B65EC</color>
<color name="BlueRibbon">#306EFF</color>
<color name="BlueDress">#157DEC</color>
<color name="DodgerBlue">#1589FF</color>
<color name="Cornflower_Blue">#6495ED</color>
<color name="ButterflyBlue">#38ACEC</color>
<color name="Iceberg">#56A5EC</color>
<color name="CrystalBlue">#5CB3FF</color>
<color name="DeepSkyBlue">#3BB9FF</color>
<color name="DenimBlue">#79BAEC</color>
<color name="LightSkyBlue">#82CAFA</color>
<color name="SkyBlue">#82CAFF</color>
<color name="JeansBlue">#A0CFEC</color>
<color name="BlueAngel">#B7CEEC</color>
<color name="PastelBlue">#B4CFEC</color>
<color name="SeaBlue">#C2DFFF</color>
<color name="PowderBlue">#C6DEFF</color>
<color name="CoralBlue">#AFDCEC</color>
<color name="LightBlue">#ADDFFF</color>
<color name="RobinEggBlue">#BDEDFF</color>
<color name="PaleBlueLily">#CFECEC</color>
<color name="LightCyan">#E0FFFF</color>
<color name="Water">#EBF4FA</color>
<color name="AliceBlue">#F0F8FF</color>
<color name="Azure">#F0FFFF</color>
<color name="LightSlate">#CCFFFF</color>
<color name="LightAquamarine">#93FFE8</color>
<color name="ElectricBlue">#9AFEFF</color>
<color name="Aquamarine">#7FFFD4</color>
<color name="CyanorAqua">#00FFFF</color>
<color name="TronBlue">#7DFDFE</color>
<color name="BlueZircon">#57FEFF</color>
<color name="BlueLagoon">#8EEBEC</color>
<color name="Celeste">#50EBEC</color>
<color name="BlueDiamond">#4EE2EC</color>
<color name="TiffanyBlue">#81D8D0</color>
<color name="CyanOpaque">#92C7C7</color>
<color name="BlueHosta">#77BFC7</color>
<color name="NorthernLightsBlue">#78C7C7</color>
<color name="MediumTurquoise">#48CCCD</color>
<color name="Turquoise">#43C6DB</color>
<color name="Jellyfish">#46C7C7</color>
<color name="MascawBlueGreen">#43BFC7</color>
<color name="LightSeaGreen">#3EA99F</color>
<color name="DarkTurquoise">#3B9C9C</color>
<color name="SeaTurtleGreen">#438D80</color>
<color name="MediumAquamarine">#348781</color>
<color name="GreenishBlue">#307D7E</color>
<color name="GrayishTurquoise">#5E7D7E</color>
<color name="BeetleGreen">#4C787E</color>
<color name="Teal">#008080</color>
<color name="SeaGreen">#4E8975</color>
<color name="CamouflageGreen">#78866B</color>
<color name="HazelGreen">#617C58</color>
<color name="VenomGreen">#728C00</color>
<color name="FernGreen">#667C26</color>
<color name="DarkForrestGreen">#254117</color>
<color name="MediumSeaGreen">#306754</color>
<color name="MediumForestGreen">#347235</color>
<color name="SeaweedGreen">#437C17</color>
<color name="PineGreen">#387C44</color>
<color name="JungleGreen">#347C2C</color>
<color name="ShamrockGreen">#347C17</color>
<color name="MediumSpringGreen">#348017</color>
<color name="ForestGreen">#4E9258</color>
<color name="GreenOnion">#6AA121</color>
<color name="SpringGreen">#4AA02C</color>
<color name="LimeGreen">#41A317</color>
<color name="CloverGreen">#3EA055</color>
<color name="GreenSnake">#6CBB3C</color>
<color name="AlienGreen">#6CC417</color>
<color name="GreenApple">#4CC417</color>
<color name="YellowGreen">#52D017</color>
<color name="KellyGreen">#4CC552</color>
<color name="ZombieGreen">#54C571</color>
<color name="FrogGreen">#99C68E</color>
<color name="GreenPeas">#89C35C</color>
<color name="DollarBillGreen">#85BB65</color>
<color name="DarkSeaGreen">#8BB381</color>
<color name="IguanaGreen">#9CB071</color>
<color name="AvocadoGreen">#B2C248</color>
<color name="PistachioGreen">#9DC209</color>
<color name="SaladGreen">#A1C935</color>
<color name="HummingbirdGreen">#7FE817</color>
<color name="NebulaGreen">#59E817</color>
<color name="StoplightGoGreen">#57E964</color>
<color name="AlgaeGreen">#64E986</color>
<color name="JadeGreen">#5EFB6E</color>
<color name="Green">#00FF00</color>
<color name="EmeraldGreen">#5FFB17</color>
<color name="LawnGreen">#87F717</color>
<color name="Chartreuse">#8AFB17</color>
<color name="DragonGreen">#6AFB92</color>
<color name="Mintgreen">#98FF98</color>
<color name="GreenThumb">#B5EAAA</color>
<color name="LightJade">#C3FDB8</color>
<color name="TeaGreen">#CCFB5D</color>
<color name="GreenYellow">#B1FB17</color>
<color name="SlimeGreen">#BCE954</color>
<color name="Goldenrod">#EDDA74</color>
<color name="HarvestGold">#EDE275</color>
<color name="SunYellow">#FFE87C</color>
<color name="Yellow">#FFFF00</color>
<color name="CornYellow">#FFF380</color>
<color name="Parchment">#FFFFC2</color>
<color name="Cream">#FFFFCC</color>
<color name="LemonChiffon">#FFF8C6</color>
<color name="Cornsilk">#FFF8DC</color>
<color name="Beige">#F5F5DC</color>
<color name="AntiqueWhite">#FAEBD7</color>
<color name="BlanchedAlmond">#FFEBCD</color>
<color name="Vanilla">#F3E5AB</color>
<color name="TanBrown">#ECE5B6</color>
<color name="Peach">#FFE5B4</color>
<color name="Mustard">#FFDB58</color>
<color name="RubberDuckyYellow">#FFD801</color>
<color name="BrightGold">#FDD017</color>
<color name="Goldenbrown">#EAC117</color>
<color name="MacaroniandCheese">#F2BB66</color>
<color name="Saffron">#FBB917</color>
<color name="Beer">#FBB117</color>
<color name="Cantaloupe">#FFA62F</color>
<color name="BeeYellow">#E9AB17</color>
<color name="BrownSugar">#E2A76F</color>
<color name="BurlyWood">#DEB887</color>
<color name="DeepPeach">#FFCBA4</color>
<color name="GingerBrown">#C9BE62</color>
<color name="SchoolBusYellow">#E8A317</color>
<color name="SandyBrown">#EE9A4D</color>
<color name="FallLeafBrown">#C8B560</color>
<color name="Gold">#D4A017</color>
<color name="Sand">#C2B280</color>
<color name="CookieBrown">#C7A317</color>
<color name="Caramel">#C68E17</color>
<color name="Brass">#B5A642</color>
<color name="Khaki">#ADA96E</color>
<color name="Camelbrown">#C19A6B</color>
<color name="Bronze">#CD7F32</color>
<color name="TigerOrange">#C88141</color>
<color name="Cinnamon">#C58917</color>
<color name="DarkGoldenrod">#AF7817</color>
<color name="Copper">#B87333</color>
<color name="Wood">#966F33</color>
<color name="OakBrown">#806517</color>
<color name="Moccasin">#827839</color>
<color name="ArmyBrown">#827B60</color>
<color name="Sandstone">#786D5F</color>
<color name="Mocha">#493D26</color>
<color name="Taupe">#483C32</color>
<color name="Coffee">#6F4E37</color>
<color name="BrownBear">#835C3B</color>
<color name="RedDirt">#7F5217</color>
<color name="Sepia">#7F462C</color>
<color name="OrangeSalmon">#C47451</color>
<color name="Rust">#C36241</color>
<color name="RedFox">#C35817</color>
<color name="Chocolate">#C85A17</color>
<color name="Sedona">#CC6600</color>
<color name="PapayaOrange">#E56717</color>
<color name="HalloweenOrange">#E66C2C</color>
<color name="PumpkinOrange">#F87217</color>
<color name="ConstructionConeOrange">#F87431</color>
<color name="SunriseOrange">#E67451</color>
<color name="MangoOrange">#FF8040</color>
<color name="DarkOrange">#F88017</color>
<color name="Coral">#FF7F50</color>
<color name="BasketBallOrange">#F88158</color>
<color name="LightSalmon">#F9966B</color>
<color name="Tangerine">#E78A61</color>
<color name="DarkSalmon">#E18B6B</color>
<color name="LightCoral">#E77471</color>
<color name="BeanRed">#F75D59</color>
<color name="ValentineRed">#E55451</color>
<color name="ShockingOrange">#E55B3C</color>
<color name="Red">#FF0000</color>
<color name="Scarlet">#FF2400</color>
<color name="RubyRed">#F62217</color>
<color name="FerrariRed">#F70D1A</color>
<color name="FireEngineRed">#F62817</color>
<color name="LavaRed">#E42217</color>
<color name="LoveRed">#E41B17</color>
<color name="Grapefruit">#DC381F</color>
<color name="ChestnutRed">#C34A2C</color>
<color name="CherryRed">#C24641</color>
<color name="Mahogany">#C04000</color>
<color name="ChilliPepper">#C11B17</color>
<color name="Cranberry">#9F000F</color>
<color name="RedWine">#990012</color>
<color name="Burgundy">#8C001A</color>
<color name="BloodRed">#7E3517</color>
<color name="Sienna">#8A4117</color>
<color name="Sangria">#7E3817</color>
<color name="Firebrick">#800517</color>
<color name="Maroon">#810541</color>
<color name="PlumPie">#7D0541</color>
<color name="VelvetMaroon">#7E354D</color>
<color name="PlumVelvet">#7D0552</color>
<color name="RosyFinch">#7F4E52</color>
<color name="Puce">#7F5A58</color>
<color name="DullPurple">#7F525D</color>
<color name="RosyBrown">#B38481</color>
<color name="KhakiRose">#C5908E</color>
<color name="PinkBow">#C48189</color>
<color name="LipstickPink">#C48793</color>
<color name="Rose">#E8ADAA</color>
<color name="DesertSand">#EDC9AF</color>
<color name="PigPink">#FDD7E4</color>
<color name="CottonCandy">#FCDFFF</color>
<color name="PinkBubblegum">#FFDFDD</color>
<color name="MistyRose">#FBBBB9</color>
<color name="Pink">#FAAFBE</color>
<color name="LightPink">#FAAFBA</color>
<color name="FlamingoPink">#F9A7B0</color>
<color name="PinkRose">#E7A1B0</color>
<color name="PinkDaisy">#E799A3</color>
<color name="CadillacPink">#E38AAE</color>
<color name="CarnationPink">#F778A1</color>
<color name="BlushRed">#E56E94</color>
<color name="HotPink">#F660AB</color>
<color name="WatermelonPink">#FC6C85</color>
<color name="VioletRed">#F6358A</color>
<color name="DeepPink">#F52887</color>
<color name="PinkCupcake">#E45E9D</color>
<color name="PinkLemonade">#E4287C</color>
<color name="NeonPink">#F535AA</color>
<color name="Magenta">#FF00FF</color>
<color name="DimorphothecaMagenta">#E3319D</color>
<color name="BrightNeonPink">#F433FF</color>
<color name="PaleVioletRed">#D16587</color>
<color name="TulipPink">#C25A7C</color>
<color name="MediumVioletRed">#CA226B</color>
<color name="RoguePink">#C12869</color>
<color name="BurntPink">#C12267</color>
<color name="BashfulPink">#C25283</color>
<color name="Carnation_Pink">#C12283</color>
<color name="Plum">#B93B8F</color>
<color name="ViolaPurple">#7E587E</color>
<color name="PurpleIris">#571B7E</color>
<color name="PlumPurple">#583759</color>
<color name="Indigo">#4B0082</color>
<color name="PurpleMonster">#461B7E</color>
<color name="PurpleHaze">#4E387E</color>
<color name="Eggplant">#614051</color>
<color name="Grape">#5E5A80</color>
<color name="PurpleJam">#6A287E</color>
<color name="DarkOrchid">#7D1B7E</color>
<color name="PurpleFlower">#A74AC7</color>
<color name="MediumOrchid">#B048B5</color>
<color name="PurpleAmethyst">#6C2DC7</color>
<color name="DarkViolet">#842DCE</color>
<color name="Violet">#8D38C9</color>
<color name="PurpleSageBush">#7A5DC7</color>
<color name="LovelyPurple">#7F38EC</color>
<color name="Purple">#8E35EF</color>
<color name="AztechPurple">#893BFF</color>
<color name="MediumPurple">#8467D7</color>
<color name="JasminePurple">#A23BEC</color>
<color name="PurpleDaffodil">#B041FF</color>
<color name="TyrianPurple">#C45AEC</color>
<color name="CrocusPurple">#9172EC</color>
<color name="PurpleMimosa">#9E7BFF</color>
<color name="HeliotropePurple">#D462FF</color>
<color name="Crimson">#E238EC</color>
<color name="PurpleDragon">#C38EC7</color>
<color name="Lilac">#C8A2C8</color>
<color name="BlushPink">#E6A9EC</color>
<color name="Mauve">#E0B0FF</color>
<color name="WiseriaPurple">#C6AEC7</color>
<color name="BlossomPink">#F9B7FF</color>
<color name="Thistle">#D2B9D3</color>
<color name="Periwinkle">#E9CFEC</color>
<color name="LavenderPinocchio">#EBDDE2</color>
<color name="Lavender">#E3E4FA</color>
<color name="Pearl">#FDEEF4</color>
<color name="SeaShell">#FFF5EE</color>
<color name="MilkWhite">#FEFCFF</color>
<color name="White">#FFFFFF</color>

What is the default username and password in Tomcat?

Look in your conf/tomcat-users.xml. If there is nothing there, you'd have to configure it.

How can I read SMS messages from the device programmatically in Android?

Kotlin Code to read SMS :

1- Add this permission to AndroidManifest.xml :

    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

2-Create a BroadCastreceiver Class :

package utils.broadcastreceivers

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import android.util.Log

class MySMSBroadCastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
    var body = ""
    val bundle = intent?.extras
    val pdusArr = bundle!!.get("pdus") as Array<Any>
    var messages: Array<SmsMessage?>  = arrayOfNulls(pdusArr.size)

 // if SMSis Long and contain more than 1 Message we'll read all of them
    for (i in pdusArr.indices) {
        messages[i] = SmsMessage.createFromPdu(pdusArr[i] as ByteArray)
    }
      var MobileNumber: String? = messages[0]?.originatingAddress
       Log.i(TAG, "MobileNumber =$MobileNumber")         
       val bodyText = StringBuilder()
        for (i in messages.indices) {
            bodyText.append(messages[i]?.messageBody)
        }
        body = bodyText.toString()
        if (body.isNotEmpty()){
       // Do something, save SMS in DB or variable , static object or .... 
                       Log.i("Inside Receiver :" , "body =$body")
        }
    }
 }

3-Get SMS Permission if Android 6 and above:

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && 
    ActivityCompat.checkSelfPermission(context!!,
            Manifest.permission.RECEIVE_SMS
        ) != PackageManager.PERMISSION_GRANTED
    ) { // Needs permission

            requestPermissions(arrayOf(Manifest.permission.RECEIVE_SMS),
            PERMISSIONS_REQUEST_READ_SMS
        )

    } else { // Permission has already been granted

    }

4- Add this request code to Activity or fragment :

 companion object {
    const val PERMISSIONS_REQUEST_READ_SMS = 100
   }

5- Override Check permisstion Request result fun :

 override fun onRequestPermissionsResult(
    requestCode: Int, permissions: Array<out String>,
    grantResults: IntArray
) {
    when (requestCode) {

        PERMISSIONS_REQUEST_READ_SMS -> {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("BroadCastReceiver", "PERMISSIONS_REQUEST_READ_SMS Granted")
            } else {
                //  toast("Permission must be granted  ")
            }
        }
    }
}

How to detect the screen resolution with JavaScript?

Using jQuery you can do:

$(window).width()
$(window).height()

CSS for grabbing cursors (drag & drop)

CSS3 grab and grabbing are now allowed values for cursor. In order to provide several fallbacks for cross-browser compatibility3 including custom cursor files, a complete solution would look like this:

.draggable {
    cursor: move; /* fallback: no `url()` support or images disabled */
    cursor: url(images/grab.cur); /* fallback: Internet Explorer */
    cursor: -webkit-grab; /* Chrome 1-21, Safari 4+ */
    cursor:    -moz-grab; /* Firefox 1.5-26 */
    cursor:         grab; /* W3C standards syntax, should come least */
}

.draggable:active {
    cursor: url(images/grabbing.cur);
    cursor: -webkit-grabbing;
    cursor:    -moz-grabbing;
    cursor:         grabbing;
}

Update 2019-10-07:

.draggable {
    cursor: move; /* fallback: no `url()` support or images disabled */
    cursor: url(images/grab.cur); /* fallback: Chrome 1-21, Firefox 1.5-26, Safari 4+, IE, Edge 12-14, Android 2.1-4.4.4 */
    cursor: grab; /* W3C standards syntax, all modern browser */
}

.draggable:active {
    cursor: url(images/grabbing.cur);
    cursor: grabbing;
}

How to save and extract session data in codeigniter

In CodeIgniter you can store your session value as single or also in array format as below:

If you want store any user’s data in session like userId, userName, userContact etc, then you should store in array:

<?php
$this->load->library('session');
$this->session->set_userdata(array(
'userId'  => $user->userId,
'userName' => $user->userName,
'userContact '  => $user->userContact 
)); 
?>

Get in details with Example Demo :

http://devgambit.com/how-to-store-and-get-session-value-in-codeigniter/

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

Select multiple columns in data.table by their numeric indices

If you want to use column names to select the columns, simply use .(), which is an alias for list():

library(data.table)
dt <- data.table(a = 1:2, b = 2:3, c = 3:4)
dt[ , .(b, c)] # select the columns b and c
# Result:
#    b c
# 1: 2 3
# 2: 3 4

What is Dependency Injection?

Dependency Injection (DI) is one from Design Patterns, which uses the basic feature of OOP - the relationship in one object with another object. While inheritance inherits one object to do more complex and specific another object, relationship or association simply creates a pointer to another object from one object using attribute. The power of DI is in combination with other features of OOP as are interfaces and hiding code. Suppose, we have a customer (subscriber) in the library, which can borrow only one book for simplicity.

Interface of book:

package com.deepam.hidden;

public interface BookInterface {

public BookInterface setHeight(int height);
public BookInterface setPages(int pages);   
public int getHeight();
public int getPages();  

public String toString();
}

Next we can have many kind of books; one of type is fiction:

package com.deepam.hidden;

public class FictionBook implements BookInterface {
int height = 0; // height in cm
int pages = 0; // number of pages

/** constructor */
public FictionBook() {
    // TODO Auto-generated constructor stub
}

@Override
public FictionBook setHeight(int height) {
  this.height = height;
  return this;
}

@Override
public FictionBook setPages(int pages) {
  this.pages = pages;
  return this;      
}

@Override
public int getHeight() {
    // TODO Auto-generated method stub
    return height;
}

@Override
public int getPages() {
    // TODO Auto-generated method stub
    return pages;
}

@Override
public String toString(){
    return ("height: " + height + ", " + "pages: " + pages);
}
}

Now subscriber can have association to the book:

package com.deepam.hidden;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Subscriber {
BookInterface book;

/** constructor*/
public Subscriber() {
    // TODO Auto-generated constructor stub
}

// injection I
public void setBook(BookInterface book) {
    this.book = book;
}

// injection II
public BookInterface setBook(String bookName) {
    try {
        Class<?> cl = Class.forName(bookName);
        Constructor<?> constructor = cl.getConstructor(); // use it for parameters in constructor
        BookInterface book = (BookInterface) constructor.newInstance();
        //book = (BookInterface) Class.forName(bookName).newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return book;
}

public BookInterface getBook() {
  return book;
}

public static void main(String[] args) {

}

}

All the three classes can be hidden for it's own implementation. Now we can use this code for DI:

package com.deepam.implement;

import com.deepam.hidden.Subscriber;
import com.deepam.hidden.FictionBook;

public class CallHiddenImplBook {

public CallHiddenImplBook() {
    // TODO Auto-generated constructor stub
}

public void doIt() {
    Subscriber ab = new Subscriber();

    // injection I
    FictionBook bookI = new FictionBook();
    bookI.setHeight(30); // cm
    bookI.setPages(250);
    ab.setBook(bookI); // inject
    System.out.println("injection I " + ab.getBook().toString());

    // injection II
    FictionBook bookII = ((FictionBook) ab.setBook("com.deepam.hidden.FictionBook")).setHeight(5).setPages(108); // inject and set
    System.out.println("injection II " + ab.getBook().toString());      
}

public static void main(String[] args) {
    CallHiddenImplBook kh = new CallHiddenImplBook();
    kh.doIt();
}
}

There are many different ways how to use dependency injection. It is possible to combine it with Singleton, etc., but still in basic it is only association realized by creating attribute of object type inside another object. The usefulness is only and only in feature, that code, which we should write again and again is always prepared and done for us forward. This is why DI so closely binded with Inversion of Control (IoC) which means, that our program passes control another running module, which does injections of beans to our code. (Each object, which can be injected can be signed or considered as a Bean.) For example in Spring it is done by creating and initialization ApplicationContext container, which does this work for us. We simply in our code create the Context and invoke initialization the beans. In that moment injection has been done automatically.

SoapUI "failed to load url" error when loading WSDL

For java version above 1.8, Use below command to setup soapUI jar

java -jar --add-modules java.xml.bind --add-modules java.xml.ws <path for jar file+jar file name.jar>

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

__FILE__ macro shows full path

I did a macro __FILENAME__ that avoids cutting full path each time. The issue is to hold the resulting file name in a cpp-local variable.

It can be easily done by defining a static global variable in .h file. This definition gives separate and independent variables in each .cpp file that includes the .h. In order to be a multithreading-proof it worth to make the variable(s) also thread local (TLS).

One variable stores the File Name (shrunk). Another holds the non-cut value that __FILE__ gave. The h file:

static __declspec( thread ) const char* fileAndThreadLocal_strFilePath = NULL;
static __declspec( thread ) const char* fileAndThreadLocal_strFileName = NULL;

The macro itself calls method with all the logic:

#define __FILENAME__ \
    GetSourceFileName(__FILE__, fileAndThreadLocal_strFilePath, fileAndThreadLocal_strFileName)

And the function is implemented this way:

const char* GetSourceFileName(const char* strFilePath, 
                              const char*& rstrFilePathHolder, 
                              const char*& rstrFileNameHolder)
{
    if(strFilePath != rstrFilePathHolder)
    {
        // 
        // This if works in 2 cases: 
        // - when first time called in the cpp (ordinary case) or
        // - when the macro __FILENAME__ is used in both h and cpp files 
        //   and so the method is consequentially called 
        //     once with strFilePath == "UserPath/HeaderFileThatUsesMyMACRO.h" and 
        //     once with strFilePath == "UserPath/CPPFileThatUsesMyMACRO.cpp"
        //
        rstrFileNameHolder = removePath(strFilePath);
        rstrFilePathHolder = strFilePath;
    }
    return rstrFileNameHolder;
}

The removePath() can be implemented in different ways, but the fast and simple seems to be with strrchr:

const char* removePath(const char* path)
{
    const char* pDelimeter = strrchr (path, '\\');
    if (pDelimeter)
        path = pDelimeter+1;

    pDelimeter = strrchr (path, '/');
    if (pDelimeter)
        path = pDelimeter+1;

    return path;
}

Convert an image to grayscale

The code below is the simplest solution:

Bitmap bt = new Bitmap("imageFilePath");

for (int y = 0; y < bt.Height; y++)
{
    for (int x = 0; x < bt.Width; x++)
    {
        Color c = bt.GetPixel(x, y);

        int r = c.R;
        int g = c.G;
        int b = c.B;
        int avg = (r + g + b) / 3;
        bt.SetPixel(x, y, Color.FromArgb(avg,avg,avg));
    }   
}

bt.Save("d:\\out.bmp");

Converting Go struct to JSON

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless:

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.

Difference between app.use and app.get in express.js

Simply app.use means “Run this on ALL requests”
app.get means “Run this on a GET request, for the given URL”

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

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.

What does it mean if a Python object is "subscriptable" or not?

I had this same issue. I was doing

arr = []
arr.append["HI"]

So using [ was causing error. It should be arr.append("HI")

Batch files: List all files in a directory with relative paths

You could simply get the character length of the current directory, and remove them from your absolute list

setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
  set "absPath=%%g"
  setlocal EnableDelayedExpansion
  set "relPath=!absPath:~%len%!"
  echo(!relPath!
  endlocal
)

How to redirect back to form with input - Laravel 5

You can use any of these two:

return redirect()->back()->withInput(Input::all())->with('message', 'Some message');

Or,

return redirect('url_goes_here')->withInput(Input::all())->with('message', 'Some message');

Sorting rows in a data table

 table.DefaultView.Sort = "[occr] DESC";

DB query builder toArray() laravel 4

If you prefer to use Query Builder instead of Eloquent here is the solutions

$result = DB::table('user')->where('name',=,'Jhon')->get();

First Solution

$array = (array) $result;

Second Solution

$array = get_object_vars($result);

Third Solution

$array = json_decode(json_encode($result), true);

hope it may help

What is the maximum length of a String in PHP?

The maximum length of a string variable is only 2GiB - (2^(32-1) bits). Variables can be addressed on a character (8 bits/1 byte) basis and the addressing is done by signed integers which is why the limit is what it is. Arrays can contain multiple variables that each follow the previous restriction but can have a total cumulative size up to memory_limit of which a string variable is also subject to.

Is there a replacement for unistd.h for Windows (Visual C)?

Try including the io.h file. It seems to be the Visual Studio's equivalent of unistd.h.

I hope this helps.

How to convert POJO to JSON and vice versa?

Use GSON for converting POJO to JSONObject. Refer here.

For converting JSONObject to POJO, just call the setter method in the POJO and assign the values directly from the JSONObject.

Deleting an object in C++

Isn't this the normal way to free the memory associated with an object?

This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it, you will leak that object.

It is far better to use a smart pointer container, which you can use to get scope-bound resource management (it's more commonly called resource acquisition is initialization, or RAII).

As an example of automatic resource management:

void test()
{
    std::auto_ptr<Object1> obj1(new Object1);

} // The object is automatically deleted when the scope ends.

Depending on your use case, auto_ptr might not provide the semantics you need. In that case, you can consider using shared_ptr.

As for why your program crashes when you delete the object, you have not given sufficient code for anyone to be able to answer that question with any certainty.

PHP json_encode encoding numbers as strings

I've done a very quick test :

$a = array(
    'id' => 152,
    'another' => 'test',
    'ananother' => 456,
);
$json = json_encode($a);
echo $json;

This seems to be like what you describe, if I'm not mistaken ?

And I'm getting as output :

{"id":152,"another":"test","ananother":456}

So, in this case, the integers have not been converted to string.


Still, this might be dependant of the version of PHP we are using : there have been a couple of json_encode related bugs corrected, depending on the version of PHP...

This test has been made with PHP 5.2.6 ; I'm getting the same thing with PHP 5.2.9 and 5.3.0 ; I don't have another 5.2.x version to test with, though :-(

Which version of PHP are you using ? Or is your test-case more complex than the example you posted ?

Maybe one bug report on http://bugs.php.net/ could be related ? For instance, Bug #40503 : json_encode integer conversion is inconsistent with PHP ?


Maybe Bug #38680 could interest you too, btw ?

.NET - Get protocol, host, and port

The following (C#) code should do the trick

Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;

Scroll to element on click in Angular 4

You can do this by using jquery :

ts code :

    scrollTOElement = (element, offsetParam?, speedParam?) => {
    const toElement = $(element);
    const focusElement = $(element);
    const offset = offsetParam * 1 || 200;
    const speed = speedParam * 1 || 500;
    $('html, body').animate({
      scrollTop: toElement.offset().top + offset
    }, speed);
    if (focusElement) {
      $(focusElement).focus();
    }
  }

html code :

<button (click)="scrollTOElement('#elementTo',500,3000)">Scroll</button>

Apply this on elements you want to scroll :

<div id="elementTo">some content</div>

Here is a stackblitz sample.

How to pop an alert message box using PHP?

Use jQuery before the php command alert

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I'm not sure if I am correct, but from the request header that you post:

Request headers

Accept: Application/json

Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36

Content-Type: application/x-www-form-urlencoded

Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

it seems like you didn't config your request body to JSON type.

HTML Input Box - Disable

<input type="text" disabled="disabled" />

See the W3C HTML Specification on the input tag for more information.

Parse HTML table to Python list?

Sven Marnach excellent solution is directly translatable into ElementTree which is part of recent Python distributions:

from xml.etree import ElementTree as ET

s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""

table = ET.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print(dict(zip(headers, values)))

same output as Sven Marnach's answer...

How do I get the name of a Ruby class?

Both result.class.to_s and result.class.name work.

Does C have a string type?

C does not support a first class string type.

C++ has std::string

How to set cellpadding and cellspacing in table with CSS?

Use padding on the cells and border-spacing on the table. The former will give you cellpadding while the latter will give you cellspacing.

table { border-spacing: 5px; } /* cellspacing */

th, td { padding: 5px; } /* cellpadding */

jsFiddle Demo

Add marker to Google Map on Click

Currently the method to add the listener to the map would be

map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

And not

google.maps.event.addListener(map, 'click', function(e) {
    placeMarker(e.latLng, map);
});

Reference

Extract substring using regexp in plain bash

If your string is

foo="US/Central - 10:26 PM (CST)"

then

echo "${foo}" | cut -d ' ' -f3

will do the job.

Create Django model or update if exists

If you're looking for "update if exists else create" use case, please refer to @Zags excellent answer


Django already has a get_or_create, https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create

For you it could be :

id = 'some identifier'
person, created = Person.objects.get_or_create(identifier=id)

if created:
   # means you have created a new person
else:
   # person just refers to the existing one

Merging multiple PDFs using iTextSharp in c#.net

Using iTextSharp.dll

protected void Page_Load(object sender, EventArgs e)
{
    String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
    MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
    if (System.IO.File.Exists(destinationFile))
        System.IO.File.Delete(destinationFile);

    string[] sSrcFile;
    sSrcFile = new string[2];

    string[] arr = new string[2];
    for (int i = 0; i <= sourceFiles.Length - 1; i++)
    {
        if (sourceFiles[i] != null)
        {
            if (sourceFiles[i].Trim() != "")
                arr[i] = sourceFiles[i].ToString();
        }
    }

    if (arr != null)
    {
        sSrcFile = new string[2];

        for (int ic = 0; ic <= arr.Length - 1; ic++)
        {
            sSrcFile[ic] = arr[ic].ToString();
        }
    }
    try
    {
        int f = 0;

        PdfReader reader = new PdfReader(sSrcFile[f]);
        int n = reader.NumberOfPages;
        Response.Write("There are " + n + " pages in the original file.");
        Document document = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;

        int rotation;
        while (f < sSrcFile.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;

                document.SetPageSize(PageSize.A4);
                document.NewPage();
                page = writer.GetImportedPage(reader, i);

                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                Response.Write("\n Processed page " + i);
            }

            f++;
            if (f < sSrcFile.Length)
            {
                reader = new PdfReader(sSrcFile[f]);
                n = reader.NumberOfPages;
                Response.Write("There are " + n + " pages in the original file.");
            }
        }
        Response.Write("Success");
        document.Close();
    }
    catch (Exception e)
    {
        Response.Write(e.Message);
    }


}

glm rotate usage in Opengl

You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).

All you need to do is (see here)

Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Note that to convert from degrees to radians, use glm::radians(degrees)

That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.

note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6

Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

How can I dismiss the on screen keyboard?

FocusScope.of(context).unfocus() has a downside when using with filtered listView. Apart from so many details and concisely, use keyboard_dismisser package in https://pub.dev/packages/keyboard_dismisser will solve all the problems.

What is the best way to trigger onchange event in react js

Triggering change events on arbitrary elements creates dependencies between components which are hard to reason about. It's better to stick with React's one-way data flow.

There is no simple snippet to trigger React's change event. The logic is implemented in ChangeEventPlugin.js and there are different code branches for different input types and browsers. Moreover, the implementation details vary across versions of React.

I have built react-trigger-change that does the thing, but it is intended to be used for testing, not as a production dependency:

let node;
ReactDOM.render(
  <input
    onChange={() => console.log('changed')}
    ref={(input) => { node = input; }}
  />,
  mountNode
);

reactTriggerChange(node); // 'changed' is logged

CodePen

How to reload a div without reloading the entire page?

$("#div_element").load('script.php');

demo: http://sandbox.phpcode.eu/g/2ecbe/3

whole code:

<div id="submit">ajax</div> 
<div id="div_element"></div> 
<script> 
$('#submit').click(function(event){ 
   $("#div_element").load('script.php?html=some_arguments');  

}); 
</script> 

Trying to embed newline in a variable in bash

Summary

  1. Inserting \n

    p="${var1}\n${var2}"
    echo -e "${p}"
    
  2. Inserting a new line in the source code

    p="${var1}
    ${var2}"
    echo "${p}"
    
  3. Using $'\n' (only and )

    p="${var1}"$'\n'"${var2}"
    echo "${p}"
    

Details

1. Inserting \n

p="${var1}\n${var2}"
echo -e "${p}"

echo -e interprets the two characters "\n" as a new line.

var="a b c"
first_loop=true
for i in $var
do
   p="$p\n$i"            # Append
   unset first_loop
done
echo -e "$p"             # Use -e

Avoid extra leading newline

var="a b c"
first_loop=1
for i in $var
do
   (( $first_loop )) &&  # "((...))" is bash specific
   p="$i"            ||  # First -> Set
   p="$p\n$i"            # After -> Append
   unset first_loop
done
echo -e "$p"             # Use -e

Using a function

embed_newline()
{
   local p="$1"
   shift
   for i in "$@"
   do
      p="$p\n$i"         # Append
   done
   echo -e "$p"          # Use -e
}

var="a b c"
p=$( embed_newline $var )  # Do not use double quotes "$var"
echo "$p"

2. Inserting a new line in the source code

var="a b c"
for i in $var
do
   p="$p
$i"       # New line directly in the source code
done
echo "$p" # Double quotes required
          # But -e not required

Avoid extra leading newline

var="a b c"
first_loop=1
for i in $var
do
   (( $first_loop )) &&  # "((...))" is bash specific
   p="$i"            ||  # First -> Set
   p="$p
$i"                      # After -> Append
   unset first_loop
done
echo "$p"                # No need -e

Using a function

embed_newline()
{
   local p="$1"
   shift
   for i in "$@"
   do
      p="$p
$i"                      # Append
   done
   echo "$p"             # No need -e
}

var="a b c"
p=$( embed_newline $var )  # Do not use double quotes "$var"
echo "$p"

3. Using $'\n' (less portable)

and interprets $'\n' as a new line.

var="a b c"
for i in $var
do
   p="$p"$'\n'"$i"
done
echo "$p" # Double quotes required
          # But -e not required

Avoid extra leading newline

var="a b c"
first_loop=1
for i in $var
do
   (( $first_loop )) &&  # "((...))" is bash specific
   p="$i"            ||  # First -> Set
   p="$p"$'\n'"$i"       # After -> Append
   unset first_loop
done
echo "$p"                # No need -e

Using a function

embed_newline()
{
   local p="$1"
   shift
   for i in "$@"
   do
      p="$p"$'\n'"$i"    # Append
   done
   echo "$p"             # No need -e
}

var="a b c"
p=$( embed_newline $var )  # Do not use double quotes "$var"
echo "$p"

Output is the same for all

a
b
c

Special thanks to contributors of this answer: kevinf, Gordon Davisson, l0b0, Dolda2000 and tripleee.


EDIT

How do I see all foreign keys to a table or column?

For a Table:

SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = '<database>' AND
  REFERENCED_TABLE_NAME = '<table>';

For a Column:

SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = '<database>' AND
  REFERENCED_TABLE_NAME = '<table>' AND
  REFERENCED_COLUMN_NAME = '<column>';

Basically, we changed REFERENCED_TABLE_NAME with REFERENCED_COLUMN_NAME in the where clause.

How to make a local variable (inside a function) global

Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:

def foo():
    global bar
    bar = 32

I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.

When to use EntityManager.find() vs EntityManager.getReference() with JPA

Because a reference is 'managed', but not hydrated, it can also allow you to remove an entity by ID, without needing to load it into memory first.

As you can't remove an unmanaged entity, it's just plain silly to load all fields using find(...) or createQuery(...), only to immediately delete it.

MyLargeObject myObject = em.getReference(MyLargeObject.class, objectId);
em.remove(myObject);

Export a list into a CSV or TXT file in R

I export lists into YAML format with CPAN YAML package.

l <- list(a="1", b=1, c=list(a="1", b=1))
yaml::write_yaml(l, "list.yaml")

Bonus of YAML that it's a human readable text format so it's easy to read/share/import/etc

$ cat list.yaml
a: '1'
b: 1.0
c:
  a: '1'
  b: 1.0

Ranges of floating point datatype in C?

Infinity, NaN and subnormals

These are important caveats that no other answer has mentioned so far.

First read this introduction to IEEE 754 and subnormal numbers: What is a subnormal floating point number?

Then, for single precision floats (32-bit):

  • IEEE 754 says that if the exponent is all ones (0xFF == 255), then it represents either NaN or Infinity.

    This is why the largest non-infinite number has exponent 0xFE == 254 and not 0xFF.

    Then with the bias, it becomes:

    254 - 127 == 127
    
  • FLT_MIN is the smallest normal number. But there are smaller subnormal ones! Those take up the -127 exponent slot.

All asserts of the following program pass on Ubuntu 18.04 amd64:

#include <assert.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

float float_from_bytes(
    uint32_t sign,
    uint32_t exponent,
    uint32_t fraction
) {
    uint32_t bytes;
    bytes = 0;
    bytes |= sign;
    bytes <<= 8;
    bytes |= exponent;
    bytes <<= 23;
    bytes |= fraction;
    return *(float*)&bytes;
}

int main(void) {
    /* All 1 exponent and non-0 fraction means NaN.
     * There are of course many possible representations,
     * and some have special semantics such as signalling vs not.
     */
    assert(isnan(float_from_bytes(0, 0xFF, 1)));
    assert(isnan(NAN));
    printf("nan                  = %e\n", NAN);

    /* All 1 exponent and 0 fraction means infinity. */
    assert(INFINITY == float_from_bytes(0, 0xFF, 0));
    assert(isinf(INFINITY));
    printf("infinity             = %e\n", INFINITY);

    /* ANSI C defines FLT_MAX as the largest non-infinite number. */
    assert(FLT_MAX == 0x1.FFFFFEp127f);
    /* Not 0xFF because that is infinite. */
    assert(FLT_MAX == float_from_bytes(0, 0xFE, 0x7FFFFF));
    assert(!isinf(FLT_MAX));
    assert(FLT_MAX < INFINITY);
    printf("largest non infinite = %e\n", FLT_MAX);

    /* ANSI C defines FLT_MIN as the smallest non-subnormal number. */
    assert(FLT_MIN == 0x1.0p-126f);
    assert(FLT_MIN == float_from_bytes(0, 1, 0));
    assert(isnormal(FLT_MIN));
    printf("smallest normal      = %e\n", FLT_MIN);

    /* The smallest non-zero subnormal number. */
    float smallest_subnormal = float_from_bytes(0, 0, 1);
    assert(smallest_subnormal == 0x0.000002p-126f);
    assert(0.0f < smallest_subnormal);
    assert(!isnormal(smallest_subnormal));
    printf("smallest subnormal   = %e\n", smallest_subnormal);

    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run with:

gcc -ggdb3 -O0 -std=c11 -Wall -Wextra -Wpedantic -Werror -o subnormal.out subnormal.c
./subnormal.out

Output:

nan                  = nan
infinity             = inf
largest non infinite = 3.402823e+38
smallest normal      = 1.175494e-38
smallest subnormal   = 1.401298e-45

getApplication() vs. getApplicationContext()

To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.

C++ multiline string literal

Since an ounce of experience is worth a ton of theory, I tried a little test program for MULTILINE:

#define MULTILINE(...) #__VA_ARGS__

const char *mstr[] =
{
    MULTILINE(1, 2, 3),       // "1, 2, 3"
    MULTILINE(1,2,3),         // "1,2,3"
    MULTILINE(1 , 2 , 3),     // "1 , 2 , 3"
    MULTILINE( 1 , 2 , 3 ),   // "1 , 2 , 3"
    MULTILINE((1,  2,  3)),   // "(1,  2,  3)"
    MULTILINE(1
              2
              3),             // "1 2 3"
    MULTILINE(1\n2\n3\n),     // "1\n2\n3\n"
    MULTILINE(1\n
              2\n
              3\n),           // "1\n 2\n 3\n"
    MULTILINE(1, "2" \3)      // "1, \"2\" \3"
};

Compile this fragment with cpp -P -std=c++11 filename to reproduce.

The trick behind #__VA_ARGS__ is that __VA_ARGS__ does not process the comma separator. So you can pass it to the stringizing operator. Leading and trailing spaces are trimmed, and spaces (including newlines) between words are compressed to a single space then. Parentheses need to be balanced. I think these shortcomings explain why the designers of C++11, despite #__VA_ARGS__, saw the need for raw string literals.

Putty: Getting Server refused our key Error

In my case I had to change the permissions of /home/user from 0755 to 0700 as well.

ActiveRecord OR query

I'd like to add this is a solution to search multiple attributes of an ActiveRecord. Since

.where(A: param[:A], B: param[:B])

will search for A and B.

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

Setting width and height

In my case, passing responsive: false under options solved the problem. I'm not sure why everybody is telling you to do the opposite, especially since true is the default.

Git merge without auto commit

I prefer this way so I don't need to remember any rare parameters.

git merge branch_name

It will then say your branch is ahead by "#" commits, you can now pop these commits off and put them into the working changes with the following:

git reset @~#

For example if after the merge it is 1 commit ahead, use:

git reset @~1

Note: On Windows, quotes are needed. (As Josh noted in comments) eg:

git reset "@~1"

label or @html.Label ASP.net MVC 4

The helpers are there mainly to help you display labels, form inputs, etc for the strongly typed properties of your model. By using the helpers and Visual Studio Intellisense, you can greatly reduce the number of typos that you could make when generating a web page.

With that said, you can continue to create your elements manually for both properties of your view model or items that you want to display that are not part of your view model.

Is there a way to get the git root directory in one command?

I wanted to expand upon Daniel Brockman's excellent comment.

Defining git config --global alias.exec '!exec ' allows you to do things like git exec make because, as man git-config states:

If the alias expansion is prefixed with an exclamation point, it will be treated as a shell command. [...] Note that shell commands will be executed from the top-level directory of a repository, which may not necessarily be the current directory.

It's also handy to know that $GIT_PREFIX will be the path to the current directory relative to the top-level directory of a repository. But, knowing it is only half the battle™. Shell variable expansion makes it rather hard to use. So I suggest using bash -c like so:

git exec bash -c 'ls -l $GIT_PREFIX'

other commands include:

git exec pwd
git exec make

What is the size limit of a post request?

It is up to the http server to decide if there is a limit. The product I work on allows the admin to configure the limit.

Distribution certificate / private key not installed

If you are being stuck on this problem. After switch the computer and not able to upload your build to App Store. Simply click manage certificate on the error page, the + plus on the bottom left corner and create a new distribution certificate. Then you'll be good to go.

C# Sort and OrderBy comparison

you should calculate the complexity of algorithms used by the methods OrderBy and Sort. QuickSort has a complexity of n (log n) as i remember, where n is the length of the array.

i've searched for orderby's too, but i could not find any information even in msdn library. if you have not any same values and sorting related to only one property, i prefer to use Sort() method; if not than use OrderBy.

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

I have several library projects with the same package name specified in the AndroidManifest (so no duplicate field names are generated by R.java). I had to remove any permissions and activities from the AndroidManifest.xml for all library projects to remove the error so Manifest.java wasn't created multiple times. Hopefully this can help someone.

Why is division in Ruby returning an integer instead of decimal value?

You can check it with irb:

$ irb
>> 2 / 3
=> 0
>> 2.to_f / 3
=> 0.666666666666667
>> 2 / 3.to_f
=> 0.666666666666667

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

I had a similar issue and tried the other suggestions.

Utilizing the PdaNet driver in the download from http://www.junefabrics.com/android/download.php is what finally did the job and allowed me to finally connect via ADB. Prior to installing the driver from here I was unable to recognize my Nexus in order to sideload the new Android 4.2 on my device.

I am running Windows 7 64 bit with my Nexus 7.

Check whether variable is number or string in JavaScript

Beware that typeof NaN is... 'number'

typeof NaN === 'number'; // true

how to make a whole row in a table clickable as a link?

Here is simple solution..

<tr style='cursor: pointer; cursor: hand;' onclick="window.location='google.com';"></tr>

With MySQL, how can I generate a column containing the record index in a table?

SELECT @i:=@i+1 AS iterator, t.*
FROM tablename t,(SELECT @i:=0) foo

Getting rid of all the rounded corners in Twitter Bootstrap

You may also want to have a look at FlatStrap. It provides a Metro-Style replacement for the Bootstrap CSS without rounded corners, gradients and drop shadows.

How can I include null values in a MIN or MAX?

In my expression, count(enddate) counts how many rows where the enddate column is not null. The count(*) expression counts total rows. By comparing, you can easily tell if any value in the enddate column contains null. If they are identical, then max(enddate) is the result. Otherwise the case will default to returning null which is also the answer. This is a very popular way to do this exact check.

SELECT recordid, 
MIN(startdate), 
case when count(enddate) = count(*) then max(enddate) end
FROM tmp 
GROUP BY recordid

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

Python object deleting itself

'self' is only a reference to the object. 'del self' is deleting the 'self' reference from the local namespace of the kill function, instead of the actual object.

To see this for yourself, look at what happens when these two functions are executed:

>>> class A():
...     def kill_a(self):
...         print self
...         del self
...     def kill_b(self):
...         del self
...         print self
... 
>>> a = A()
>>> b = A()
>>> a.kill_a()
<__main__.A instance at 0xb771250c>
>>> b.kill_b()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in kill_b
UnboundLocalError: local variable 'self' referenced before assignment

Giving multiple URL patterns to Servlet Filter

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
 * Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
    ...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
    ...

Radio buttons and label to display in same line

** Used table to align the radio and text in one line

_x000D_
_x000D_
<div >_x000D_
  <table>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td><strong>Do you want to add new server ?</strong></td>_x000D_
        <td><input type="radio" name="addServer" id="serverYes" value="1"></td>_x000D_
        <td>Yes</td>_x000D_
        <td><input type="radio" name="addServer" id="serverNo" value="1"></td>_x000D_
        <td>No</td>_x000D_
_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

**

Android check null or empty string in Android

Checking for empty string if it is equal to null, length is zero or containing "null" string

public static boolean isEmptyString(String text) {
        return (text == null || text.trim().equals("null") || text.trim()
                .length() <= 0);
    }

How to set up a PostgreSQL database in Django

The immediate problem seems to be that you're missing the psycopg2 module.

Test if object implements interface

Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}

I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.

.NET console application as Windows service

I've had great success with TopShelf.

TopShelf is a Nuget package designed to make it easy to create .NET Windows apps that can run as console apps or as Windows Services. You can quickly hook up events such as your service Start and Stop events, configure using code e.g. to set the account it runs as, configure dependencies on other services, and configure how it recovers from errors.

From the Package Manager Console (Nuget):

Install-Package Topshelf

Refer to the code samples to get started.

Example:

HostFactory.Run(x =>                                 
{
    x.Service<TownCrier>(s =>                        
    {
       s.ConstructUsing(name=> new TownCrier());     
       s.WhenStarted(tc => tc.Start());              
       s.WhenStopped(tc => tc.Stop());               
    });
    x.RunAsLocalSystem();                            

    x.SetDescription("Sample Topshelf Host");        
    x.SetDisplayName("Stuff");                       
    x.SetServiceName("stuff");                       
}); 

TopShelf also takes care of service installation, which can save a lot of time and removes boilerplate code from your solution. To install your .exe as a service you just execute the following from the command prompt:

myservice.exe install -servicename "MyService" -displayname "My Service" -description "This is my service."

You don't need to hook up a ServiceInstaller and all that - TopShelf does it all for you.

Can you autoplay HTML5 videos on the iPad?

Let video muted first to ensure autoplay in ios, then unmute it if you want.

<video autoplay loop muted playsinline>
  <source src="video.mp4?123" type="video/mp4">
</video>

<script type="text/javascript">
$(function () {
  if (!navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
    $("video").prop('muted', false);
  }
});
</script>

How do I cast a JSON Object to a TypeScript class?

In my case it works. I used functions Object.assign (target, sources ...). First, the creation of the correct object, then copies the data from json object to the target.Example :

let u:User = new User();
Object.assign(u , jsonUsers);

And a more advanced example of use. An example using the array.

this.someService.getUsers().then((users: User[]) => {
  this.users = [];
  for (let i in users) {
    let u:User = new User();
    Object.assign(u , users[i]);
    this.users[i] = u;
    console.log("user:" + this.users[i].id);
    console.log("user id from function(test it work) :" + this.users[i].getId());
  }

});

export class User {
  id:number;
  name:string;
  fullname:string;
  email:string;

  public getId(){
    return this.id;
  }
}

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

xlarge screens are at least 960dp x 720dp layout-xlarge 10" tablet (720x1280 mdpi, 800x1280 mdpi, etc.)

large screens are at least 640dp x 480dp tweener tablet like the Streak (480x800 mdpi), 7" tablet (600x1024 mdpi)

normal screens are at least 470dp x 320dp layout typical phone screen (480x800 hdpi)

small screens are at least 426dp x 320dp typical phone screen (240x320 ldpi, 320x480 mdpi, etc.)

How to remove the border highlight on an input text element

Try this:

*:focus {
    outline: none;
}

This would affect all your pages.

How to auto-size an iFrame?

My solution, (using jquery):

<iframe id="Iframe1" class="tabFrame" width="100%" height="100%" scrolling="no" src="http://samedomain" frameborder="0" >
</iframe>  
<script type="text/javascript">
    $(function () {

        $('.tabFrame').load(function () {
            var iframeContentWindow = this.contentWindow;
            var height = iframeContentWindow.$(document).height();
            this.style.height = height + 'px';
        });
    });
</script>

What's a clean way to stop mongod on Mac OS X?

I prefer to stop the MongoDB server using the port command itself.

sudo port unload mongodb

And to start it again.

sudo port load mongodb

Start / Stop a Windows Service from a non-Administrator user account

subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.

Java: How to convert List to Map

Alexis has already posted an answer in Java 8 using method toMap(keyMapper, valueMapper). As per doc for this method implementation:

There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

So in case we are interested in a specific implementation of Map interface e.g. HashMap then we can use the overloaded form as:

Map<String, Item> map2 =
                itemList.stream().collect(Collectors.toMap(Item::getKey, //key for map
                        Function.identity(),    // value for map
                        (o,n) -> o,             // merge function in case of conflict with keys
                        HashMap::new));         // map factory - we want HashMap and not any Map implementation

Though using either Function.identity() or i->i is fine but it seems Function.identity() instead of i -> i might save some memory as per this related answer.

How to vertically align text inside a flexbox?

You could change the ul and li displays to table and table-cell. Then, vertical-align would work for you:

ul {
    height: 20%;
    width: 100%;
    display: table;
}

li {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    background: silver;
    width: 100%; 
}

http://codepen.io/anon/pen/pckvK

getFilesDir() vs Environment.getDataDirectory()

Environment returns user data directory. And getFilesDir returns application data directory.

How can I move a tag on a git branch to a different commit?

I'll leave here just another form of this command that suited my needs.
There was a tag v0.0.1.2 that I wanted to move.

$ git tag -f v0.0.1.2 63eff6a

Updated tag 'v0.0.1.2' (was 8078562)

And then:

$ git push --tags --force

How can one tell the version of React running at runtime in the browser?

First Install React dev tools if not installed and then use the run below code in the browser console :

__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.get(1).version

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

After all the Jquery script tag's add

<script>jQuery.noConflict();</script>

to avoid the conflict between Prototype and Jquery.

Modular multiplicative inverse function in Python

Many of the links above are broken as for 1/23/2017. I found this implementation: https://courses.csail.mit.edu/6.857/2016/files/ffield.py

Clear text in EditText when entered

Your code should be:

    public class Project extends Activity implements OnClickListener {
            /** Called when the activity is first created. */
            EditText editText;
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);            

                setContentView(R.layout.main);
                editText = (EditText)findViewById(R.id.editText1);
                editText.setOnClickListener(this);            
            }

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if(v == editText) {
                    editText.setText("");
                }
            }
        }

html select option SELECTED

Just use the array of options, to see, which option is currently selected.

$options = array( 'one', 'two', 'three' );

$output = '';
for( $i=0; $i<count($options); $i++ ) {
  $output .= '<option ' 
             . ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>' 
             . $options[$i] 
             . '</option>';
}

Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.

Get Filename Without Extension in Python

In most cases, you shouldn't use a regex for that.

os.path.splitext(filename)[0]

This will also handle a filename like .bashrc correctly by keeping the whole name.

Remote JMX connection

Thanks a lot, it works like this:

java -Djava.rmi.server.hostname=xxx.xxx.xxx.xxx -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=25000 -jar myjar.jar

How does one sum only those rows in excel not filtered out?

You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.

The formula would look like this:

=SUBTOTAL(9,B1:B20)

The function number 9, tells it to use the SUM function on the data range B1:B20.

If you are 'filtering' by hiding rows, the function number should be updated to 109.

=SUBTOTAL(109,B1:B20)

The function number 109 is for the SUM function as well, but hidden rows are ignored.

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

I had a little different problem. In Project - Properties - Libraries - JRE library, I had the wrong JRE lib version. Remove and set the actual one, and voila - all Access restriction... warnings are away.

Getting input values from text box

Remove the id="pass" off the td element. Right now the js will get the td element instead of the input hence the value is undefined.

Java: Casting Object to Array type

Your values object is obviously an Object[] containing a String[] containing the values.

String[] stringValues = (String[])values[0];

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

What is the use of "assert"?

Basically the assert keyword meaning is that if the condition is not true then it through an assertionerror else it continue for example in python.

code-1

a=5

b=6

assert a==b

OUTPUT:

assert a==b

AssertionError

code-2

a=5

b=5

assert a==b

OUTPUT:

Process finished with exit code 0

Converting integer to string in Python

To manage non-integer inputs:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0

UICollectionView auto scroll to cell at IndexPath

As an alternative to mentioned above. Call after data load:

Swift

collectionView.reloadData()
collectionView.layoutIfNeeded()
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .right)

Why my regexp for hyphenated words doesn't work?

A couple of things:

  1. Your regexes need to be anchored by separators* or you'll match partial words, as is the case now
  2. You're not using the proper syntax for a non-capturing group. It's (?: not (:?

If you address the first problem, you won't need groups at all.

*That is, a blank or beginning/end of string.

Testing whether a value is odd or even

Otherway using strings because why not

function isEven(__num){
    return String(__num/2).indexOf('.') === -1;
}

How can I create and style a div using JavaScript?

Depends on how you're doing it. Pure javascript:

var div = document.createElement('div');
div.innerHTML = "my <b>new</b> skill - <large>DOM maniuplation!</large>";
// set style
div.style.color = 'red';
// better to use CSS though - just set class
div.setAttribute('class', 'myclass'); // and make sure myclass has some styles in css
document.body.appendChild(div);

Doing the same using jquery is embarrassingly easy:

$('body')
.append('my DOM manupulation skills dont seem like a big deal when using jquery')
.css('color', 'red').addClass('myclass');

Cheers!

GenyMotion Unable to start the Genymotion virtual device

For windows users: Disable Hyper-V and its tools

If you are a windows user, the problem might simply be because of having multiple virtualization technologies in your system.

You might be having Hyper-V and its related features enabled. Just simply turning them off and rebooting your system can do you help sometimes.

enter image description here

Here is how you do it:

  1. Fire up Run (Ctrl+R)
  2. Type appwiz.cpl and press enter
  3. Head over to Turn Windows features on or off
  4. Find Hyper-V and deselect everything under it.
  5. Press Ok and give your system a restart.

Fireup your genymotion and check to see if it works again. If there is an error prompt saying something like DHCP cant assign IP... just try restarting your genymotion application.

How to include External CSS and JS file in Laravel 5

Ok so I was able to figure out for the version 5.2. You will first need to create assets folder in your public folder then put css folder and all css files into it then link it like this :

<link href="assets/css/bootstrap.min.css" rel="stylesheet">

Hope that helps!

Sort Dictionary by keys

I tried all of the above, in a nutshell all you need is

let sorted = dictionary.sorted { $0.key < $1.key }
let keysArraySorted = Array(sorted.map({ $0.key }))
let valuesArraySorted = Array(sorted.map({ $0.value }))

How to unpublish an app in Google Play Developer Console

To unpublish your app on the Google Play store:

  1. Go to https://market.android.com/publish/Home, and log in to your Google Play account.
  2. Click on the application you want to delete.
  3. Click on the Store Presence menu, and click the “Pricing and Distribution” item.
  4. Click Unpublish

How to find NSDocumentDirectory in Swift?

Apparently, the compiler thinks NSSearchPathDirectory:0 is an array, and of course it expects the type NSSearchPathDirectory instead. Certainly not a helpful error message.

But as to the reasons:

First, you are confusing the argument names and types. Take a look at the function definition:

func NSSearchPathForDirectoriesInDomains(
    directory: NSSearchPathDirectory,
    domainMask: NSSearchPathDomainMask,
    expandTilde: Bool) -> AnyObject[]!
  • directory and domainMask are the names, you are using the types, but you should leave them out for functions anyway. They are used primarily in methods.
  • Also, Swift is strongly typed, so you shouldn't just use 0. Use the enum's value instead.
  • And finally, it returns an array, not just a single path.

So that leaves us with (updated for Swift 2.0):

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

and for Swift 3:

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

How to show shadow around the linearlayout in Android?

Try this.. layout_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#CABBBBBB"/>
            <corners android:radius="2dp" />
        </shape>
    </item>

    <item
        android:left="0dp"
        android:right="0dp"
        android:top="0dp"
        android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white"/>
            <corners android:radius="2dp" />
        </shape>
    </item>
</layer-list>

Apply to your layout like this

 android:background="@drawable/layout_shadow"

jQuery issue in Internet Explorer 8

I had the same problems.

I solved it verifying that IE8 was not configured correctly to reach the SRC URL.

I changed this, it works right.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

What version of tomcat are you using ? What appears to me is that the tomcat version is not supporting the servlet & jsp versions you're using. You can change to something like below or look into your version of tomcat on what it supports and change the versions accordingly.

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

How do you check for permissions to write to a directory or file?

Its a fixed version of MaxOvrdrv's Code.

public static bool IsReadable(this DirectoryInfo di)
{
    AuthorizationRuleCollection rules;
    WindowsIdentity identity;
    try
    {
        rules = di.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
        identity = WindowsIdentity.GetCurrent();
    }
    catch (UnauthorizedAccessException uae)
    {
        Debug.WriteLine(uae.ToString());
        return false;
    }

    bool isAllow = false;
    string userSID = identity.User.Value;

    foreach (FileSystemAccessRule rule in rules)
    {
        if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
        {
            if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
                rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
                rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) && rule.AccessControlType == AccessControlType.Deny)
                return false;
            else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) &&
                rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) &&
                rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) && rule.AccessControlType == AccessControlType.Allow)
                isAllow = true;

        }
    }
    return isAllow;
}

public static bool IsWriteable(this DirectoryInfo me)
{
    AuthorizationRuleCollection rules;
    WindowsIdentity identity;
    try
    {
        rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
        identity = WindowsIdentity.GetCurrent();
    }
    catch (UnauthorizedAccessException uae)
    {
        Debug.WriteLine(uae.ToString());
        return false;
    }

    bool isAllow = false;
    string userSID = identity.User.Value;

    foreach (FileSystemAccessRule rule in rules)
    {
        if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
        {
            if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
                rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
                rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
                rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
                rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Deny)
                return false;
            else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) &&
                rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) &&
                rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) &&
                rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) &&
                rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Allow)
                isAllow = true;

        }
    }
    return isAllow;
}

Creating a Shopping Cart using only HTML/JavaScript

Here's a one page cart written in Javascript with localStorage. Here's a full working pen. Previously found on Codebox

cart.js

var cart = {
  // (A) PROPERTIES
  hPdt : null, // HTML products list
  hItems : null, // HTML current cart
  items : {}, // Current items in cart

  // (B) LOCALSTORAGE CART
  // (B1) SAVE CURRENT CART INTO LOCALSTORAGE
  save : function () {
    localStorage.setItem("cart", JSON.stringify(cart.items));
  },

  // (B2) LOAD CART FROM LOCALSTORAGE
  load : function () {
    cart.items = localStorage.getItem("cart");
    if (cart.items == null) { cart.items = {}; }
    else { cart.items = JSON.parse(cart.items); }
  },

  // (B3) EMPTY ENTIRE CART
  nuke : function () {
    if (confirm("Empty cart?")) {
      cart.items = {};
      localStorage.removeItem("cart");
      cart.list();
    }
  },

  // (C) INITIALIZE
  init : function () {
    // (C1) GET HTML ELEMENTS
    cart.hPdt = document.getElementById("cart-products");
    cart.hItems = document.getElementById("cart-items");

    // (C2) DRAW PRODUCTS LIST
    cart.hPdt.innerHTML = "";
    let p, item, part;
    for (let id in products) {
      // WRAPPER
      p = products[id];
      item = document.createElement("div");
      item.className = "p-item";
      cart.hPdt.appendChild(item);

      // PRODUCT IMAGE
      part = document.createElement("img");
      part.src = "images/" +p.img;
      part.className = "p-img";
      item.appendChild(part);

      // PRODUCT NAME
      part = document.createElement("div");
      part.innerHTML = p.name;
      part.className = "p-name";
      item.appendChild(part);

      // PRODUCT DESCRIPTION
      part = document.createElement("div");
      part.innerHTML = p.desc;
      part.className = "p-desc";
      item.appendChild(part);

      // PRODUCT PRICE
      part = document.createElement("div");
      part.innerHTML = "$" + p.price;
      part.className = "p-price";
      item.appendChild(part);

      // ADD TO CART
      part = document.createElement("input");
      part.type = "button";
      part.value = "Add to Cart";
      part.className = "cart p-add";
      part.onclick = cart.add;
      part.dataset.id = id;
      item.appendChild(part);
    }

    // (C3) LOAD CART FROM PREVIOUS SESSION
    cart.load();

    // (C4) LIST CURRENT CART ITEMS
    cart.list();
  },

  // (D) LIST CURRENT CART ITEMS (IN HTML)
  list : function () {
    // (D1) RESET
    cart.hItems.innerHTML = "";
    let item, part, pdt;
    let empty = true;
    for (let key in cart.items) {
      if(cart.items.hasOwnProperty(key)) { empty = false; break; }
    }

    // (D2) CART IS EMPTY
    if (empty) {
      item = document.createElement("div");
      item.innerHTML = "Cart is empty";
      cart.hItems.appendChild(item);
    }

    // (D3) CART IS NOT EMPTY - LIST ITEMS
    else {
      let p, total = 0, subtotal = 0;
      for (let id in cart.items) {
        // ITEM
        p = products[id];
        item = document.createElement("div");
        item.className = "c-item";
        cart.hItems.appendChild(item);

        // NAME
        part = document.createElement("div");
        part.innerHTML = p.name;
        part.className = "c-name";
        item.appendChild(part);

        // REMOVE
        part = document.createElement("input");
        part.type = "button";
        part.value = "X";
        part.dataset.id = id;
        part.className = "c-del cart";
        part.addEventListener("click", cart.remove);
        item.appendChild(part);

        // QUANTITY
        part = document.createElement("input");
        part.type = "number";
        part.value = cart.items[id];
        part.dataset.id = id;
        part.className = "c-qty";
        part.addEventListener("change", cart.change);
        item.appendChild(part);

        // SUBTOTAL
        subtotal = cart.items[id] * p.price;
        total += subtotal;
      }

      // EMPTY BUTTONS
      item = document.createElement("input");
      item.type = "button";
      item.value = "Empty";
      item.addEventListener("click", cart.nuke);
      item.className = "c-empty cart";
      cart.hItems.appendChild(item);

      // CHECKOUT BUTTONS
      item = document.createElement("input");
      item.type = "button";
      item.value = "Checkout - " + "$" + total;
      item.addEventListener("click", cart.checkout);
      item.className = "c-checkout cart";
      cart.hItems.appendChild(item);
    }
  },

  // (E) ADD ITEM INTO CART
  add : function () {
    if (cart.items[this.dataset.id] == undefined) {
      cart.items[this.dataset.id] = 1;
    } else {
      cart.items[this.dataset.id]++;
    }
    cart.save();
    cart.list();
  },

  // (F) CHANGE QUANTITY
  change : function () {
    if (this.value == 0) {
      delete cart.items[this.dataset.id];
    } else {
      cart.items[this.dataset.id] = this.value;
    }
    cart.save();
    cart.list();
  },
  
  // (G) REMOVE ITEM FROM CART
  remove : function () {
    delete cart.items[this.dataset.id];
    cart.save();
    cart.list();
  },
  
  // (H) CHECKOUT
  checkout : function () {
    // SEND DATA TO SERVER
    // CHECKS
    // SEND AN EMAIL
    // RECORD TO DATABASE
    // PAYMENT
    // WHATEVER IS REQUIRED
    alert("TO DO");

    /*
    var data = new FormData();
    data.append('cart', JSON.stringify(cart.items));
    data.append('products', JSON.stringify(products));
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "SERVER-SCRIPT");
    xhr.onload = function(){ ... };
    xhr.send(data);
    */
  }
};
window.addEventListener("DOMContentLoaded", cart.init);

Print array to a file

Just use print_r ; ) Read the documentation:

If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will return the information rather than print it.

So this is one possibility:

$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($array, TRUE));
fclose($fp);

The preferred way of creating a new element with jQuery

The first option gives you more flexibilty:

var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);

And of course .html('*') overrides the content while .append('*') doesn't, but I guess, this wasn't your question.

Another good practice is prefixing your jQuery variables with $:
Is there any specific reason behind using $ with variable in jQuery

Placing quotes around the "class" property name will make it more compatible with less flexible browsers.

mongodb/mongoose findMany - find all documents with IDs listed in array

Ids is the array of object ids:

const ids =  [
    '4ed3ede8844f0f351100000c',
    '4ed3f117a844e0471100000d', 
    '4ed3f18132f50c491100000e',
];

Using Mongoose with callback:

Model.find().where('_id').in(ids).exec((err, records) => {});

Using Mongoose with async function:

const records = await Model.find().where('_id').in(ids).exec();

Or more concise:

const records = await Model.find({ '_id': { $in: ids } });

Don't forget to change Model with your actual model.

What is the "double tilde" (~~) operator in JavaScript?

The diffrence is very simple:

Long version

If you want to have better readability, use Math.floor. But if you want to minimize it, use tilde ~~.

There are a lot of sources on the internet saying Math.floor is faster, but sometimes ~~. I would not recommend you think about speed because it is not going to be noticed when running the code. Maybe in tests etc, but no human can see a diffrence here. What would be faster is to use ~~ for a faster load time.

Short version

~~ is shorter/takes less space. Math.floor improves the readability. Sometimes tilde is faster, sometimes Math.floor is faster, but it is not noticeable.

svn list of files that are modified in local copy

this should do it in Windows: svn stat | find "M"

Parse string to DateTime in C#

Put the value of a human-readable string into a .NET DateTime with code like this:

DateTime.ParseExact("April 16, 2011 4:27 pm", "MMMM d, yyyy h:mm tt", null);

How do I fix "Expected to return a value at the end of arrow function" warning?

The easiest way only if you don't need return something it'ts just return null

How to tell if node.js is installed or not

Open a terminal window. Type:

node -v

This will display your nodejs version.

Navigate to where you saved your script and input:

node script.js

This will run your script.

wait until all threads finish their work in java

Store the Thread-objects into some collection (like a List or a Set), then loop through the collection once the threads are started and call join() on the Threads.

How to copy folders to docker image from Dockerfile?

I don't completely understand the case of the original poster but I can proof that it's possible to copy directory structure using COPY in Dockerfile.

Suppose you have this folder structure:

folder1
  file1.html
  file2.html
folder2
  file3.html
  file4.html
  subfolder
    file5.html
    file6.html

To copy it to the destination image you can use such a Dockerfile content:

FROM nginx

COPY ./folder1/ /usr/share/nginx/html/folder1/
COPY ./folder2/ /usr/share/nginx/html/folder2/

RUN ls -laR /usr/share/nginx/html/*

The output of docker build . as follows:

$ docker build --no-cache .
Sending build context to Docker daemon  9.728kB
Step 1/4 : FROM nginx
 ---> 7042885a156a
Step 2/4 : COPY ./folder1/ /usr/share/nginx/html/folder1/
 ---> 6388fd58798b
Step 3/4 : COPY ./folder2/ /usr/share/nginx/html/folder2/
 ---> fb6c6eacf41e
Step 4/4 : RUN ls -laR /usr/share/nginx/html/*
 ---> Running in face3cbc0031
-rw-r--r-- 1 root root  494 Dec 25 09:56 /usr/share/nginx/html/50x.html
-rw-r--r-- 1 root root  612 Dec 25 09:56 /usr/share/nginx/html/index.html

/usr/share/nginx/html/folder1:
total 16
drwxr-xr-x 2 root root 4096 Jan 16 10:43 .
drwxr-xr-x 1 root root 4096 Jan 16 10:43 ..
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file1.html
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file2.html

/usr/share/nginx/html/folder2:
total 20
drwxr-xr-x 3 root root 4096 Jan 16 10:43 .
drwxr-xr-x 1 root root 4096 Jan 16 10:43 ..
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file3.html
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file4.html
drwxr-xr-x 2 root root 4096 Jan 16 10:33 subfolder

/usr/share/nginx/html/folder2/subfolder:
total 16
drwxr-xr-x 2 root root 4096 Jan 16 10:33 .
drwxr-xr-x 3 root root 4096 Jan 16 10:43 ..
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file5.html
-rwxr-xr-x 1 root root    7 Jan 16 10:32 file6.html
Removing intermediate container face3cbc0031
 ---> 0e0062afab76
Successfully built 0e0062afab76

Change Active Menu Item on Page Scroll?

Just check my Code and Sniper and demo link :

    // Basice Code keep it 
    $(document).ready(function () {
        $(document).on("scroll", onScroll);

        //smoothscroll
        $('a[href^="#"]').on('click', function (e) {
            e.preventDefault();
            $(document).off("scroll");

            $('a').each(function () {
                $(this).removeClass('active');
            })
            $(this).addClass('active');

            var target = this.hash,
                menu = target;
            $target = $(target);
            $('html, body').stop().animate({
                'scrollTop': $target.offset().top+2
            }, 500, 'swing', function () {
                window.location.hash = target;
                $(document).on("scroll", onScroll);
            });
        });
    });

// Use Your Class or ID For Selection 

    function onScroll(event){
        var scrollPos = $(document).scrollTop();
        $('#menu-center a').each(function () {
            var currLink = $(this);
            var refElement = $(currLink.attr("href"));
            if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
                $('#menu-center ul li a').removeClass("active");
                currLink.addClass("active");
            }
            else{
                currLink.removeClass("active");
            }
        });
    }

demo live

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    $(document).on("scroll", onScroll);_x000D_
    _x000D_
    //smoothscroll_x000D_
    $('a[href^="#"]').on('click', function (e) {_x000D_
        e.preventDefault();_x000D_
        $(document).off("scroll");_x000D_
        _x000D_
        $('a').each(function () {_x000D_
            $(this).removeClass('active');_x000D_
        })_x000D_
        $(this).addClass('active');_x000D_
      _x000D_
        var target = this.hash,_x000D_
            menu = target;_x000D_
        $target = $(target);_x000D_
        $('html, body').stop().animate({_x000D_
            'scrollTop': $target.offset().top+2_x000D_
        }, 500, 'swing', function () {_x000D_
            window.location.hash = target;_x000D_
            $(document).on("scroll", onScroll);_x000D_
        });_x000D_
    });_x000D_
});_x000D_
_x000D_
function onScroll(event){_x000D_
    var scrollPos = $(document).scrollTop();_x000D_
    $('#menu-center a').each(function () {_x000D_
        var currLink = $(this);_x000D_
        var refElement = $(currLink.attr("href"));_x000D_
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {_x000D_
            $('#menu-center ul li a').removeClass("active");_x000D_
            currLink.addClass("active");_x000D_
        }_x000D_
        else{_x000D_
            currLink.removeClass("active");_x000D_
        }_x000D_
    });_x000D_
}
_x000D_
body, html {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    height: 100%;_x000D_
    width: 100%;_x000D_
}_x000D_
.menu {_x000D_
    width: 100%;_x000D_
    height: 75px;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    position: fixed;_x000D_
    background-color:rgba(4, 180, 49, 0.6);_x000D_
    -webkit-transition: all 0.4s ease;_x000D_
    -moz-transition: all 0.4s ease;_x000D_
    -o-transition: all 0.4s ease;_x000D_
    transition: all 0.4s ease;_x000D_
}_x000D_
.light-menu {_x000D_
    width: 100%;_x000D_
    height: 75px;_x000D_
    background-color: rgba(255, 255, 255, 1);_x000D_
    position: fixed;_x000D_
    background-color:rgba(4, 180, 49, 0.6);_x000D_
    -webkit-transition: all 0.4s ease;_x000D_
    -moz-transition: all 0.4s ease;_x000D_
    -o-transition: all 0.4s ease;_x000D_
    transition: all 0.4s ease;_x000D_
}_x000D_
#menu-center {_x000D_
    width: 980px;_x000D_
    height: 75px;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
#menu-center ul {_x000D_
    margin: 0 0 0 0;_x000D_
}_x000D_
#menu-center ul li a{_x000D_
  padding: 32px 40px;_x000D_
}_x000D_
#menu-center ul li {_x000D_
    list-style: none;_x000D_
    margin: 0 0 0 -4px;_x000D_
    display: inline;_x000D_
_x000D_
}_x000D_
.active, #menu-center ul li a:hover  {_x000D_
    font-family:'Droid Sans', serif;_x000D_
    font-size: 14px;_x000D_
    color: #fff;_x000D_
    text-decoration: none;_x000D_
    line-height: 50px;_x000D_
 background-color: rgba(0, 0, 0, 0.12);_x000D_
 padding: 32px 40px;_x000D_
_x000D_
}_x000D_
a {_x000D_
    font-family:'Droid Sans', serif;_x000D_
    font-size: 14px;_x000D_
    color: black;_x000D_
    text-decoration: none;_x000D_
    line-height: 72px;_x000D_
}_x000D_
#home {_x000D_
    background-color: #286090;_x000D_
    height: 100vh;_x000D_
    width: 100%;_x000D_
    overflow: hidden;_x000D_
}_x000D_
#portfolio {_x000D_
    background: gray; _x000D_
    height: 100vh;_x000D_
    width: 100%;_x000D_
}_x000D_
#about {_x000D_
    background-color: blue;_x000D_
    height: 100vh;_x000D_
    width: 100%;_x000D_
}_x000D_
#contact {_x000D_
    background-color: rgb(154, 45, 45);_x000D_
    height: 100vh;_x000D_
    width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- <div class="container"> --->_x000D_
   <div class="m1 menu">_x000D_
   <div id="menu-center">_x000D_
    <ul>_x000D_
     <li><a class="active" href="#home">Home</a>_x000D_
_x000D_
     </li>_x000D_
     <li><a href="#portfolio">Portfolio</a>_x000D_
_x000D_
     </li>_x000D_
     <li><a href="#about">About</a>_x000D_
_x000D_
     </li>_x000D_
     <li><a href="#contact">Contact</a>_x000D_
_x000D_
     </li>_x000D_
    </ul>_x000D_
   </div>_x000D_
   </div>_x000D_
   <div id="home"></div>_x000D_
   <div id="portfolio"></div>_x000D_
   <div id="about"></div>_x000D_
   <div id="contact"></div>
_x000D_
_x000D_
_x000D_

Difference between Return and Break statements

break just breaks the loop & return gets control back to the caller method.

Can you append strings to variables in PHP?

In PHP use .= to append strings, and not +=.

Why does this output 0? [...] Does PHP not like += with strings?

+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.


More about operators in PHP:

Convert a secure string to plain text

You may also use PSCredential.GetNetworkCredential() :

$SecurePassword = Get-Content C:\Users\tmarsh\Documents\securePassword.txt | ConvertTo-SecureString
$UnsecurePassword = (New-Object PSCredential "user",$SecurePassword).GetNetworkCredential().Password

Node.js Hostname/IP doesn't match certificate's altnames

The other way to fix this in other circumstances is to use NODE_TLS_REJECT_UNAUTHORIZED=0 as an environment variable

NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js

WARNING: This is a bad idea security-wise

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

Basic Ajax send/receive with node.js

RESTful API (Route):

rtr.route('/testing')
.get((req, res)=>{
    res.render('test')
})
.post((req, res, next)=>{
       res.render('test')
})

AJAX Code:

$(function(){
$('#anyid').on('click', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'GET',
        contentType: 'application/json',
        success: function(res){
            console.log('GET Request')
        }
    })
})

$('#anyid').on('submit', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            info: "put data here to pass in JSON format."
        }),
        success: function(res){
            console.log('POST Request')
        }
    })
})
})

TypeError: a bytes-like object is required, not 'str' in python and CSV

file = open('parsed_data.txt', 'w')
for link in soup.findAll('a', attrs={'href': re.compile("^http")}): print (link)
soup_link = str(link)
print (soup_link)
file.write(soup_link)
file.flush()
file.close()

In my case, I used BeautifulSoup to write a .txt with Python 3.x. It had the same issue. Just as @tsduteba said, change the 'wb' in the first line to 'w'.

How to change the size of the radio button using CSS?

You can control radio button's size with css style:

style="height:35px; width:35px;"

This directly controls the radio button size.

<input type="radio" name="radio" value="value" style="height:35px; width:35px; vertical-align: middle;">

AngularJS: How to run additional code after AngularJS has rendered a template?

In some scenarios where you update a service and redirect to a new view(page) and then your directive gets loaded before your services are updated then you can use $rootScope.$broadcast if your $watch or $timeout fails

View

<service-history log="log" data-ng-repeat="log in requiedData"></service-history>

Controller

app.controller("MyController",['$scope','$rootScope', function($scope, $rootScope) {

   $scope.$on('$viewContentLoaded', function () {
       SomeSerive.getHistory().then(function(data) {
           $scope.requiedData = data;
           $rootScope.$broadcast("history-updation");
       });
  });

}]);

Directive

app.directive("serviceHistory", function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
           log: '='
        },
        link: function($scope, element, attrs) {
            function updateHistory() {
               if(log) {
                   //do something
               }
            }
            $rootScope.$on("history-updation", updateHistory);
        }
   };
});

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

.col-xs-$   Extra Small     Phones Less than 768px 
.col-sm-$   Small Devices   Tablets 768px and Up 
.col-md-$   Medium Devices  Desktops 992px and Up 
.col-lg-$   Large Devices   Large Desktops 1200px and Up 

Adding POST parameters before submit

You could do an ajax call.

That way, you would be able to populate the POST array yourself through the ajax 'data: ' parameter

var params = {
  url: window.location.pathname,
  time: new Date().getTime(), 
};


$.ajax({
  method: "POST",
  url: "your/script.php",
  data: params
});

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

This is the most simple solution for me:

just the current date

$tStamp = Get-Date -format yyyy_MM_dd_HHmmss

current date with some months added

$tStamp = Get-Date (get-date).AddMonths(6).Date -Format yyyyMMdd

Can I nest a <button> element inside an <a> using HTML5?

It is illegal in HTML5 to embed a button element inside a link.

Better to use CSS on the default and :active (pressed) states:

_x000D_
_x000D_
body{background-color:#F0F0F0} /* JUST TO MAKE THE BORDER STAND OUT */_x000D_
a.Button{padding:.1em .4em;color:#0000D0;background-color:#E0E0E0;font:normal 80% sans-serif;font-weight:700;border:2px #606060 solid;text-decoration:none}_x000D_
a.Button:not(:active){border-left-color:#FFFFFF;border-top-color:#FFFFFF}_x000D_
a.Button:active{border-right-color:#FFFFFF;border-bottom-color:#FFFFFF}
_x000D_
<p><a class="Button" href="www.stackoverflow.com">Click me<a>
_x000D_
_x000D_
_x000D_

REST API - Use the "Accept: application/json" HTTP Header

You guessed right, HTTP Headers are not part of the URL.

And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.

The most common scenario is that your server consumes a third party REST Api.

To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).

The code to forge the request, send it and finally get the response back depends on your server side language.

If you want to test a REST Api you may use curl tool from the command line.

curl makes a request and outputs the response to stdout (unless otherwise instructed).

In your case the test request would be issued like this:

$curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'

The H or --header directive sets a header and its value.

Remove insignificant trailing zeros from a number?

The toFixed method will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.

(4.55555).toFixed(2);
//-> "4.56"

(4).toFixed(2);
//-> "4.00"

If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.

+(4.55555).toFixed(2);
//-> 4.56

+(4).toFixed(2);
//-> 4

How to recursively delete an entire directory with PowerShell 2.0?

To delete the complete contents including the folder structure use

get-childitem $dest -recurse | foreach ($_) {remove-item $_.fullname -recurse}

The -recurse added to remove-item ensures interactive prompts are disabled.

jump to line X in nano editor

The shortcut is: CTRL+shift+- ("shift+-" results in "_") After typing the shortcut, nano will let you to enter the line you wanna jump to, type in the line number, then press ENTR.

Copy data from another Workbook through VBA

Are you looking for the syntax to open them:

Dim wkbk As Workbook

Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")

Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

How do I clone a generic list in C#?

Unless you need an actual clone of every single object inside your List<T>, the best way to clone a list is to create a new list with the old list as the collection parameter.

List<T> myList = ...;
List<T> cloneOfMyList = new List<T>(myList);

Changes to myList such as insert or remove will not affect cloneOfMyList and vice versa.

The actual objects the two Lists contain are still the same however.

How can I get the key value in a JSON object?

First off, you're not dealing with a "JSON object." You're dealing with a JavaScript object. JSON is a textual notation, but if your example code works ([0].amount), you've already deserialized that notation into a JavaScript object graph. (What you've quoted isn't valid JSON at all; in JSON, the keys must be in double quotes. What you've quoted is a JavaScript object literal, which is a superset of JSON.)

Here, length of this array is 2.

No, it's 3.

So, i need to get the name (like amount or job... totally four name) and also to count how many names are there?

If you're using an environment that has full ECMAScript5 support, you can use Object.keys (spec | MDN) to get the enumerable keys for one of the objects as an array. If not (or if you just want to loop through them rather than getting an array of them), you can use for..in:

var entry;
var name;
entry = array[0];
for (name in entry) {
    // here, `name` will be "amount", "job", "month", then "year" (in no defined order)
}

Full working example:

_x000D_
_x000D_
(function() {_x000D_
  _x000D_
  var array = [_x000D_
    {_x000D_
      amount: 12185,_x000D_
      job: "GAPA",_x000D_
      month: "JANUARY",_x000D_
      year: "2010"_x000D_
    },_x000D_
    {_x000D_
      amount: 147421,_x000D_
      job: "GAPA",_x000D_
      month: "MAY",_x000D_
      year: "2010"_x000D_
    },_x000D_
    {_x000D_
      amount: 2347,_x000D_
      job: "GAPA",_x000D_
      month: "AUGUST",_x000D_
      year: "2010"_x000D_
    }_x000D_
  ];_x000D_
  _x000D_
  var entry;_x000D_
  var name;_x000D_
  var count;_x000D_
  _x000D_
  entry = array[0];_x000D_
  _x000D_
  display("Keys for entry 0:");_x000D_
  count = 0;_x000D_
  for (name in entry) {_x000D_
    display(name);_x000D_
    ++count;_x000D_
  }_x000D_
  display("Total enumerable keys: " + count);_x000D_
_x000D_
  // === Basic utility functions_x000D_
  _x000D_
  function display(msg) {_x000D_
    var p = document.createElement('p');_x000D_
    p.innerHTML = msg;_x000D_
    document.body.appendChild(p);_x000D_
  }_x000D_
  _x000D_
})();
_x000D_
_x000D_
_x000D_

Since you're dealing with raw objects, the above for..in loop is fine (unless someone has committed the sin of mucking about with Object.prototype, but let's assume not). But if the object you want the keys from may also inherit enumerable properties from its prototype, you can restrict the loop to only the object's own keys (and not the keys of its prototype) by adding a hasOwnProperty call in there:

for (name in entry) {
  if (entry.hasOwnProperty(name)) {
    display(name);
    ++count;
  }
}