Programs & Examples On #Graphical logo

Graphical logos, such as corporate logos (to distinguish from the Logo programming language)

Rails 4: assets not loading in production

I'm running Ubuntu Server 14.04, Ruby 2.2.1 and Rails 4.2.4 I have followed a deploy turorial from DigitalOcean and everything went well but when I go to the browser and enter the IP address of my VPS my app is loaded but without styles and javascript.

The app is running with Unicorn and Nginx. To fix this problem I entered my server using SSH with my user 'deployer' and go to my app path which is '/home/deployer/apps/blog' and run the following command:

RAILS_ENV=production bin/rake assets:precompile

Then I just restart the VPS and that's it! It works for me!

Hope it could be useful for somebody else!

Generate a range of dates using SQL

Oracle specific, and doesn't rely on pre-existing large tables or complicated system views over data dictionary objects.

SELECT c1 from dual
  MODEL DIMENSION BY (1 as rn)  MEASURES (sysdate as c1)
  RULES ITERATE (365) 
  (c1[ITERATION_NUMBER]=SYSDATE-ITERATION_NUMBER)
order by 1

Get Row Index on Asp.net Rowcommand event

ImageButton \ Button etc.

CommandArgument='<%# Container.DataItemIndex%>' 

code-behind

protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = e.CommandArgument;
}

Angular 4 - get input value

If you dont want to use two way data binding. You can do this.

In HTML

<form (ngSubmit)="onSubmit($event)">
   <input name="player" value="Name">
</form>

In component

onSubmit(event: any) {
   return event.target.player.value;
}

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

Indeed there is.

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

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

Filtering lists using LINQ

var thisList = new List<string>{ "a", "b", "c" };
var otherList = new List<string> {"a", "b"};

var theOnesThatDontMatch = thisList
        .Where(item=> otherList.All(otherItem=> item != otherItem))
        .ToList();

var theOnesThatDoMatch = thisList
        .Where(item=> otherList.Any(otherItem=> item == otherItem))
        .ToList();

Console.WriteLine("don't match: {0}", string.Join(",", theOnesThatDontMatch));
Console.WriteLine("do match: {0}", string.Join(",", theOnesThatDoMatch));

//Output:
//don't match: c
//do match: a,b

Adapt the list types and lambdas accordingly, and you can filter out anything.

https://dotnetfiddle.net/6bMCvN

Failed binder transaction when putting an bitmap dynamically in a widget

The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. Consequently this exception can be thrown when there are many transactions in progress even when most of the individual transactions are of moderate size.

refer this link

Error: Cannot pull with rebase: You have unstaged changes

Pulling with rebase is a good practice in general.

However you cannot do that if your index is not clean, i.e. you have made changes that have not been committed.

You can do this to work around, assuming you want to keep your changes:

  1. stash your changes with: git stash
  2. pull from master with rebase
  3. reapply the changes you stashed in (1) with: git stash apply stash@{0} or the simpler git stash pop

How to deep merge instead of shallow merge?

Does anybody know if deep merging exists in the ES6/ES7 spec?

Object.assign documentation suggests it doesn't do deep clone.

Calling a method inside another method in same class

The add method that takes a String and a Person is calling a different add method that takes a Position. The one that takes Position is inherited from the ArrayList class.

Since your class Staff extends ArrayList<Position>, it automatically has the add(Position) method. The new add(String, Person) method is one that was written particularly for the Staff class.

Oracle : how to subtract two dates and get minutes of the result

I think you can adapt the function to substract the two timestamps:

return  EXTRACT(MINUTE FROM 
  TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
-
  TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
);

I think you could simplify it by just using CAST(p_date as TIMESTAMP).

return  EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));

Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.

How do I speed up the gwt compiler?

If you run the GWT compiler with the -localWorkers flag, the compiler will compile multiple permutations in parallel. This lets you use all the cores of a multi-core machine, for example -localWorkers 2 will tell the compiler to do compile two permutations in parallel. You won't get order of magnitudes differences (not everything in the compiler is parallelizable) but it is still a noticable speedup if you are compiling multiple permutations.

If you're willing to use the trunk version of GWT, you'll be able to use hosted mode for any browser (out of process hosted mode), which alleviates most of the current issues with hosted mode. That seems to be where the GWT is going - always develop with hosted mode, since compiles aren't likely to get magnitudes faster.

MySQL - Get row number on select

You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).

SELECT 0 INTO @x;

SELECT itemID, 
       COUNT(*) AS ordercount, 
       (@x:=@x+1) AS rownumber 
FROM orders 
GROUP BY itemID 
ORDER BY ordercount DESC; 

HTTP Basic: Access denied fatal: Authentication failed

  1. Generate an access token with never expire date, and select all the options available.
  2. Remove the existing SSH keys.
  3. Clone the repo with the https instead of ssh.
  4. Use the username but use the generated access token instead of password.

enter image description here

alternatively you can set remote to http by using this command in the existing repo, and use this command git remote set-url origin https://gitlab.com/[username]/[repo-name].git

Max parallel http connections in a browser?

Firefox stores that number in this setting (you find it in about:config): network.http.max-connections-per-server

For the max connections, Firefox stores that in this setting: network.http.max-connections

How can I view the contents of an ElasticSearch index?

If you didn't index too much data into the index yet, you can use term facet query on the field that you would like to debug to see the tokens and their frequencies:

curl -XDELETE 'http://localhost:9200/test-idx'
echo
curl -XPUT 'http://localhost:9200/test-idx' -d '
{
    "settings": {
        "index.number_of_shards" : 1,
        "index.number_of_replicas": 0
    },
    "mappings": {            
        "doc": {
            "properties": {
                "message": {"type": "string", "analyzer": "snowball"}
            }
        }
    }

}'
echo
curl -XPUT 'http://localhost:9200/test-idx/doc/1' -d '
{
  "message": "How is this going to be indexed?"
}
'
echo
curl -XPOST 'http://localhost:9200/test-idx/_refresh'
echo
curl -XGET 'http://localhost:9200/test-idx/doc/_search?pretty=true&search_type=count' -d '{
    "query": {
        "match": {
            "_id": "1"
        }
    },
    "facets": {
        "tokens": {
            "terms": {
                "field": "message"
            }
        }
    }
}
'
echo

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

Firebug-like debugger for Google Chrome

This doesn't answer your question but, in case you missed it, Chris Pederick's Web Developer is now available for Chrome: https://chrome.google.com/extensions/detail/bfbameneiokkgbdmiekhjnmfkcnldhhm.

Key existence check in HashMap

Just use containsKey() for clarity. It's fast and keeps the code clean and readable. The whole point of HashMaps is that the key lookup is fast, just make sure the hashCode() and equals() are properly implemented.

Fetch the row which has the Max value for a column

In Oracle 12c+, you can use Top n queries along with analytic function rank to achieve this very concisely without subqueries:

select *
from your_table
order by rank() over (partition by user_id order by my_date desc)
fetch first 1 row with ties;

The above returns all the rows with max my_date per user.

If you want only one row with max date, then replace the rank with row_number:

select *
from your_table
order by row_number() over (partition by user_id order by my_date desc)
fetch first 1 row with ties; 

How to assign an action for UIImageView object in Swift

Swift 4 Code


Step 1 In ViewdidLoad()

   let pictureTap = UITapGestureRecognizer(target: self, action: #selector(MyInfoTableViewController.imageTapped))
       userImageView.addGestureRecognizer(pictureTap)
       userImageView.isUserInteractionEnabled = true

Step 2 Add Following Function

@objc func imageTapped() {

        let imageView = userImageView
        let newImageView = UIImageView(image: imageView?.image)
        newImageView.frame = UIScreen.main.bounds
        newImageView.backgroundColor = UIColor.black
        newImageView.contentMode = .scaleAspectFit
        newImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        newImageView.addGestureRecognizer(tap)
        self.view.addSubview(newImageView)

        self.navigationController?.isNavigationBarHidden = true
        self.tabBarController?.tabBar.isHidden = true

    }

It's Tested And Working Properly

Set focus on textbox in WPF

Another possible solution is to use FocusBehavior provided by free DevExpress MVVM Framework:

<TextBox Text="This control is focused on startup">
    <dxmvvm:Interaction.Behaviors>
        <dxmvvm:FocusBehavior/>
    </dxmvvm:Interaction.Behaviors>
</TextBox>

It allows you to focus a control when it's loaded, when a certain event is raised or a property is changed.

How to get file size in Java

Use the length() method in the File class. From the javadocs:

Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.

UPDATED Nowadays we should use the Files.size() method:

Paths path = Paths.get("/path/to/file");
long size = Files.size(path);

For the second part of the question, straight from File's javadocs:

  • getUsableSpace() Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname

  • getTotalSpace() Returns the size of the partition named by this abstract pathname

  • getFreeSpace() Returns the number of unallocated bytes in the partition named by this abstract path name

"Integer number too large" error message for 600851475143

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

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

for example :

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

How do I disable text selection with CSS or JavaScript?

UPDATE January, 2017:

According to Can I use, the user-select is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).


All of the correct CSS variations are:

_x000D_
_x000D_
.noselect {_x000D_
  -webkit-touch-callout: none; /* iOS Safari */_x000D_
    -webkit-user-select: none; /* Safari */_x000D_
     -khtml-user-select: none; /* Konqueror HTML */_x000D_
       -moz-user-select: none; /* Firefox */_x000D_
        -ms-user-select: none; /* Internet Explorer/Edge */_x000D_
            user-select: none; /* Non-prefixed version, currently_x000D_
                                  supported by Chrome and Opera */_x000D_
}
_x000D_
<p>_x000D_
  Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
  Unselectable text._x000D_
</p>
_x000D_
_x000D_
_x000D_


Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.


More information can be found in Mozilla Developer Network documentation.

Is there a CSS selector for elements containing certain text?

If you're using Chimp / Webdriver.io, they support a lot more CSS selectors than the CSS spec.

This, for example, will click on the first anchor that contains the words "Bad bear":

browser.click("a*=Bad Bear");

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <br/>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:

.hideDiv
{
    display:none;
}

How to get the xml node value in string

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}

or you could wrap in foreach loop to print each value

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    foreach(XmlNode curr in n) {
        Console.WriteLine(curr.InnerText);
    }
}

Add st, nd, rd and th (ordinal) suffix to a number

Strongly recommend the excellent date-fns library. Fast, modular, immutable, works with standard dates.

import * as DateFns from 'date-fns';

const ordinalInt = DateFns.format(someInt, 'do');

See date-fns docs: https://date-fns.org/v2.0.0-alpha.9/docs/format

PHP compare time

$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}

A solution using DateTime (that also regards the timezone).

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}

http://php.net/datetime.diff

Python - Check If Word Is In A String

What is wrong with:

if word in mystring: 
   print 'success'

Where to find the complete definition of off_t type?

If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)

Is it ok to run docker from inside docker?

Running Docker inside Docker (a.k.a. dind), while possible, should be avoided, if at all possible. (Source provided below.) Instead, you want to set up a way for your main container to produce and communicate with sibling containers.

Jérôme Petazzoni — the author of the feature that made it possible for Docker to run inside a Docker container — actually wrote a blog post saying not to do it. The use case he describes matches the OP's exact use case of a CI Docker container that needs to run jobs inside other Docker containers.

Petazzoni lists two reasons why dind is troublesome:

  1. It does not cooperate well with Linux Security Modules (LSM).
  2. It creates a mismatch in file systems that creates problems for the containers created inside parent containers.

From that blog post, he describes the following alternative,

[The] simplest way is to just expose the Docker socket to your CI container, by bind-mounting it with the -v flag.

Simply put, when you start your CI container (Jenkins or other), instead of hacking something together with Docker-in-Docker, start it with:

docker run -v /var/run/docker.sock:/var/run/docker.sock ...

Now this container will have access to the Docker socket, and will therefore be able to start containers. Except that instead of starting "child" containers, it will start "sibling" containers.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I'm going to improve the answer by supporting partitioned tables:

find partition scheme and partition key using below scritps:

declare @partition_scheme varchar(100) = (
select distinct ps.Name AS PartitionScheme
from sys.indexes i  
join sys.partitions p ON i.object_id=p.object_id AND i.index_id=p.index_id  
join sys.partition_schemes ps on ps.data_space_id = i.data_space_id  
where i.object_id = object_id('your table name')
)
print @partition_scheme

declare @partition_column varchar(100) = (
select c.name 
from  sys.tables          t
join  sys.indexes         i 
      on(i.object_id = t.object_id 
  and i.index_id < 2)
join  sys.index_columns  ic 
  on(ic.partition_ordinal > 0 
  and ic.index_id = i.index_id and ic.object_id = t.object_id)
join  sys.columns         c 
  on(c.object_id = ic.object_id 
  and c.column_id = ic.column_id)
where t.object_id  = object_id('your table name')
)
print @partition_column

then change the generation query by adding below line at the right place:

+ IIF(@partition_scheme is null, '', 'ON [' + @partition_scheme + ']([' + @partition_column + '])')

Datatables on-the-fly resizing

I was having the exact same problem as OP. I had a DataTable which would not readjust its width after a jQuery animation (toogle("fast")) resized its container.

After reading these answers, and lots of try and error this did the trick for me:

  $("#animatedElement").toggle(100, function() {    
    $("#dataTableId").resize();
  });

After many test, i realized that i need to wait for the animation to finish for dataTables to calculate the correct width.

What is the difference between UTF-8 and Unicode?

"Unicode" is unfortunately used in various different ways, depending on the context. Its most correct use (IMO) is as a coded character set - i.e. a set of characters and a mapping between the characters and integer code points representing them.

UTF-8 is a character encoding - a way of converting from sequences of bytes to sequences of characters and vice versa. It covers the whole of the Unicode character set. ASCII is encoded as a single byte per character, and other characters take more bytes depending on their exact code point (up to 4 bytes for all currently defined code points, i.e. up to U-0010FFFF, and indeed 4 bytes could cope with up to U-001FFFFF).

When "Unicode" is used as the name of a character encoding (e.g. as the .NET Encoding.Unicode property) it usually means UTF-16, which encodes most common characters as two bytes. Some platforms (notably .NET and Java) use UTF-16 as their "native" character encoding. This leads to hairy problems if you need to worry about characters which can't be encoded in a single UTF-16 value (they're encoded as "surrogate pairs") - but most developers never worry about this, IME.

Some references on Unicode:

A 'for' loop to iterate over an enum in Java

If you don't care about the order this should work:

Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
    // do stuff
}

ImportError: No module named PIL

I had the same problem and i fixed it by checking what version pip (pip3 --version) is, then realizing I'm typing python<uncorrect version> filename.py instead of python<correct version> filename.py

Can I use break to exit multiple nested 'for' loops?

break will exit only the innermost loop containing it.

You can use goto to break out of any number of loops.

Of course goto is often Considered Harmful.

is it proper to use the break function[...]?

Using break and goto can make it more difficult to reason about the correctness of a program. See here for a discussion on this: Dijkstra was not insane.

Disable browser cache for entire ASP.NET website

You can try below code in Global.asax file.

protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        Response.Cache.SetNoStore();
    }

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

Regex to test if string begins with http:// or https://

Case insensitive:

var re = new RegExp("^(http|https)://", "i");
var str = "My String";
var match = re.test(str);

Error in model.frame.default: variable lengths differ

Its simple, just make sure the data type in your columns are the same. For e.g. I faced the same error, that and an another error:

Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

So, I went back to my excel file or csv file, set a filter on the variable throwing me an error and checked if the distinct datatypes are the same. And... Oh! it had numbers and strings, so I converted numbers to string and it worked just fine for me.

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

Combine Multiple child rows into one row MYSQL

Joe Edel's answer to himself is actually the right approach to resolve the pivot problem.

Basically the idea is to list out the columns in the base table firstly, and then any number of options.value from the joint option table. Just left join the same option table multiple times in order to get all the options.

What needs to be done by the programming language is to build this query dynamically according to a list of options needs to be queried.

How to read PDF files using Java?

with Apache PDFBox it goes like this:

PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(document);
    System.out.println("Text:" + text);
}
document.close();

How to put a tooltip on a user-defined function

Also you can use, this Macro to assign Descriptions to arguments and the UDF:

Private Sub RegisterMyFunction()
Application.MacroOptions _
    Macro:="SampleFunction", _      '' Your UDF name
    Description:="calculates a result based on provided inputs", _
    Category:="My UDF Category", _  '' Or use numbers, a list in the link below
    ArgumentDescriptions:=Array( _  '' One by each argument
        "is the first argument.  tell the user what it does", _
        "is the second argument.  tell the user what it does")
End Sub

Credits to Kendall and the original post here. For the UDF Categories

Escape single quote character for use in an SQLite query

for replace all (') in your string, use

.replace(/\'/g,"''")

example:

sample = "St. Mary's and St. John's";
escapedSample = sample.replace(/\'/g,"''")

Sum columns with null values in oracle

The other answers regarding the use of nvl() are correct however none seem to address a more salient point:

Should you even have NULLs in this column?

Do they have a meaning other than 0?

This seems like a case where you should have a NOT NULL DEFAULT 0 on th ecolumn

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

You can use the template syntax of ngFor on groups and the usual syntax inside it for the actual rows like:

<table>
  <template let-group ngFor [ngForOf]="groups">
    <tr *ngFor="let row of group.items">{{row}}</tr>
  </template>
</table>

Check this plunk

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

About Android Studio Gradle plugin version and Required Gradle version, you can see more detailed answer here: What is real Android Studio Gradle Version?

For each version of this Gradle plugin, it requires a minimum Gradle version as listed on below table

(Reference page:gradle-plugin#updating-gradle).

enter image description here

When you update Android Studio, you may receive a prompt to also update Gradle to the latest available version.

For example, Android Gradle Plugin version 3.1.0+ requires a minimal gradle version 4.4.

You can be configured via Android Studio File -> Project Structure -> Project. See below:

enter image description here

Or you can manually modify the file gradle/wrapper/gradle-wrapper.properties. For example:

distributionUrl = https\://services.gradle.org/distributions/gradle-4.6-all.zip

basic authorization command for curl

Use the -H header again before the Authorization:Basic things. So it will be

curl -i \
    -H 'Accept:application/json' \
    -H 'Authorization:Basic BASE64_string' \
    http://example.com

Here, BASE64_string = Base64 of username:password

jQuery Set Cursor Position in Text Area

This worked for me on Safari 5 on Mac OSX, jQuery 1.4:

$("Selector")[elementIx].selectionStart = desiredStartPos; 
$("Selector")[elementIx].selectionEnd = desiredEndPos;

How to resize array in C++?

The size of an array is static in C++. You cannot dynamically resize it. That's what std::vector is for:

std::vector<int> v; // size of the vector starts at 0

v.push_back(10); // v now has 1 element
v.push_back(20); // v now has 2 elements
v.push_back(30); // v now has 3 elements

v.pop_back(); // removes the 30 and resizes v to 2

v.resize(v.size() - 1); // resizes v to 1

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

this script cleans all views, SPS, functions PKs, FKs and tables.

/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])

WHILE @name is not null
BEGIN
    SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Procedure: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped View: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Function: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint IS NOT NULL
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
        EXEC (@SQL)
        PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
        EXEC (@SQL)
        PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

Any way to generate ant build.xml file automatically from Eclipse?

I've had the same problem, our work environment is based on Eclipse Java projects, and we needed to build automatically an ANT file so that we could use a continuous integration server (Jenkins, in our case).

We rolled out our own Eclipse Java to Ant tool, which is now available on GitHub:

ant-build-for-java

To use it, call:

java -jar ant-build-for-java.jar <folder with repositories> [<.userlibraries file>]

The first argument is the folder with the repositories. It will search the folder recursively for any .project file. The tool will create a build.xml in the given folder.

Optionally, the second argument can be an exported .userlibraries file, from Eclipse, needed when any of the projects use Eclipse user libraries. The tool was tested only with user libraries using relative paths, it's how we use them in our repo. This implies that JARs and other archives needed by projects are inside an Eclipse project, and referenced from there.

The tool only supports dependencies from other Eclipse projects and from Eclipse user libraries.

jquery UI dialog: how to initialize without a title bar?

Have you tried solution from jQuery UI docs? https://api.jqueryui.com/dialog/#method-open

As it say you can do like this...

In CSS:

.no-titlebar .ui-dialog-titlebar {
  display: none;
}

In JS:

$( "#dialog" ).dialog({
  dialogClass: "no-titlebar"
});

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

Python - How to concatenate to a string in a for loop?

endstring = ''
for s in list:
    endstring += s

Change string color with NSAttributedString?

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

static let foregroundColor: NSAttributedStringKey

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

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

import UIKit

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

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

import UIKit

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

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

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

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

    override func viewDidLoad() {
        super.viewDidLoad()

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

        // Set display
        updateDisplay()
    }

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

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

}

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

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

How to use the COLLATE in a JOIN in SQL Server?

As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p
  ON (p.vTreasuryId = f.RFC) COLLATE Database_Default 

JavaScript variable assignments from tuples

As an update to The Minister's answer, you can now do this with es2015:

function Tuple(...args) {
  args.forEach((val, idx) => 
    Object.defineProperty(this, "item"+idx, { get: () => val })
  )
}


var t = new Tuple("a", 123)
console.log(t.item0) // "a"
t.item0 = "b"
console.log(t.item0) // "a"

https://jsbin.com/fubaluwimo/edit?js,console

HTML input field hint

With a bit of JavaScript:

<input 
  value="Enter username..." 
  onfocus="if (this.value === 'Enter username...') this.value=''" ... />

HTML5 has a nice attribute for this, called placeholder:

<input placeholder="Enter username.." ... />

but this attribute is not supported in old browsers.

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

Tkinter scrollbar for frame

Please note that the proposed code is only valid with Python 2

Here is an example:

from Tkinter import *   # from x import * is bad practice
from ttk import *

# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling

    """
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)            

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)


if __name__ == "__main__":

    class SampleApp(Tk):
        def __init__(self, *args, **kwargs):
            root = Tk.__init__(self, *args, **kwargs)


            self.frame = VerticalScrolledFrame(root)
            self.frame.pack()
            self.label = Label(text="Shrink the window to activate the scrollbar.")
            self.label.pack()
            buttons = []
            for i in range(10):
                buttons.append(Button(self.frame.interior, text="Button " + str(i)))
                buttons[-1].pack()

    app = SampleApp()
    app.mainloop()

It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though.

edit:

to 1)
IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it.
One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves.

to 2)
You are talking about the data function? Place works for me, too. (In general I prefer grid).

to 3)
Well, it positions the window on the canvas.

One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.

Multiple argument IF statement - T-SQL

Not sure what the problem is, this seems to work just fine?

DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        Select 'This works just fine' as Msg
    END
Else
    BEGIN
    Select 'No Lol' as Msg
    END

java.io.StreamCorruptedException: invalid stream header: 7371007E

This exception may also occur if you are using Sockets on one side and SSLSockets on the other. Consistency is important.

Change the background color of a row in a JTable

The call to getTableCellRendererComponent(...) includes the value of the cell for which a renderer is sought.

You can use that value to compute a color. If you're also using an AbstractTableModel, you can provide a value of arbitrary type to your renderer.

Once you have a color, you can setBackground() on the component that you're returning.

nginx showing blank PHP pages

Many users fall in this thread expecting to find a solution for blank pages being displayed while using nginx+php-fpm, me being one of them. This is a recap of what I ended up doing after reading many of the answers here plus my own investigations (updated to php7.2):

1) Open /etc/php/7.2/fpm/pool.d/www.conf and check the value of parameter listen.

listen = /var/run/php/php7.2-fpm.sock

2) Parameter listen should match fastcgi_pass parameter in your site configuration file (i,e: /etc/nginx/sites-enabled/default).

fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;

3) Check the file actually exists:

$ file /var/run/php/php7.2-fpm.sock 
/var/run/php/php7.2-fpm.sock: socket

4) If it doesn't exist that means php7.2-fpm is not running, so you need to restart it:

$ sudo /etc/init.d/php7.2-fpm restart
[ ok ] Restarting php7.2-fpm (via systemctl): php7.2-fpm.service.


With regard to the location section in /etc/nginx/sites-enabled/default:

   # pass PHP scripts to FastCGI server
   #
   location ~ \.php$ {
      include snippets/fastcgi-php.conf;

      # With php-fpm (or other unix sockets):
      fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
   }

Check the file snippets/fastcgi-php.conf exists at location /etc/nginx/:

$ file /etc/nginx/snippets/fastcgi-php.conf
/etc/nginx/snippets/fastcgi-php.conf: ASCII text

This file contains a list of variable definitions required by php7.2-fpm. The variables are defined directly or through an include of a separated file.

 include fastcgi.conf;

This file is located at /etc/nginx/fastcgi.conf and it looks like:

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
...
fastcgi_param  REDIRECT_STATUS    200;

nginx includes two possible parameter files: fastcgi_params and fastcgi.conf. The difference between both is the definition of variable SCRIPT_FILENAME:

$ diff fastcgi_params fastcgi.conf 
1a2
> fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

To make a long story short, fastcgi.conf should always work. If for some reason you're set up is using fastcgi_params, you should define SCRIPT_FILENAME:

location ~ \.php$ {
  include snippets/fastcgi-php.conf;

  # With php-fpm (or other unix sockets):
  fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;

  fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
}

Now reload nginx configuration:

$ sudo nginx -s reload

And check a php file is displayed correctly. For instance:

/var/www/html/test.php

<pre><?php var_export($_SERVER)?></pre>

Where /var/www/html is the path to the document root.

If despite all that, you're still seeing a blank file, make sure your php.ini has short_open_tag enabled (if you're testing a PHP page with short tags).

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

The list returned by Arrays.asList() might be immutable. Could you try

List<String> list = new ArrayList(Arrays.asList(split));

MySQL IF ELSEIF in select query

You have what you have used in stored procedures like this for reference, but they are not intended to be used as you have now. You can use IF as shown by duskwuff. But a Case statement is better for eyes. Like this:

select id, 
    (
    CASE 
        WHEN qty_1 <= '23' THEN price
        WHEN '23' > qty_1 && qty_2 <= '23' THEN price_2
        WHEN '23' > qty_2 && qty_3 <= '23' THEN price_3
        WHEN '23' > qty_3 THEN price_4
        ELSE 1
    END) AS total
 from product;

This looks cleaner. I suppose you do not require the inner SELECT anyway..

Getting request payload from POST request in Java servlet

With Apache Commons IO you can do this in one line.

IOUtils.toString(request.getReader())

How to open google chrome from terminal?

On Linux, just use this command in a terminal:

google-chrome

TSQL How do you output PRINT in a user defined function?

No, you can not.

You can call a function from a stored procedure and debug a stored procedure (this will step into the function)

Is there a Google Chrome-only CSS hack?

I have found this works ONLY in Chrome (where it's red) and not Safari and all other browsers (where it's green)...

.style {
color: green;
(-bracket-:hack;
    color: red;
);
}

From http://mynthon.net/howto/webdev/css-hacks-for-google-chrome.htm

Access a global variable in a PHP function

You need to pass the variable into the function:

$data = 'My data';

function menugen($data)
{
    echo $data;
}

HTTP Request in Kotlin

Without adding additional dependencies, this works. You don't need Volley for this. This works using the current version of Kotlin as of Dec 2018: Kotlin 1.3.10

If using Android Studio, you'll need to add this declaration in your AndroidManifest.xml:

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

You should manually declare imports here. The auto-import tool caused me many conflicts.:

import android.os.AsyncTask
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.net.URL
import java.net.URLEncoder
import javax.net.ssl.HttpsURLConnection

You can't perform network requests on a background thread. You must subclass AsyncTask.

To call the method:

NetworkTask().execute(requestURL, queryString)

Declaration:

private class NetworkTask : AsyncTask<String, Int, Long>() {
    override fun doInBackground(vararg parts: String): Long? {
        val requestURL = parts.first()
        val queryString = parts.last()

        // Set up request
        val connection: HttpsURLConnection = URL(requestURL).openConnection() as HttpsURLConnection
        // Default is GET so you must override this for post
        connection.requestMethod = "POST"
        // To send a post body, output must be true
        connection.doOutput = true
        // Create the stream
        val outputStream: OutputStream = connection.outputStream
        // Create a writer container to pass the output over the stream
        val outputWriter = OutputStreamWriter(outputStream)
        // Add the string to the writer container
        outputWriter.write(queryString)
        // Send the data
        outputWriter.flush()

        // Create an input stream to read the response
        val inputStream = BufferedReader(InputStreamReader(connection.inputStream)).use {
            // Container for input stream data
            val response = StringBuffer()
            var inputLine = it.readLine()
            // Add each line to the response container
            while (inputLine != null) {
                response.append(inputLine)
                inputLine = it.readLine()
            }
            it.close()
            // TODO: Add main thread callback to parse response
            println(">>>> Response: $response")
        }
        connection.disconnect()

        return 0
    }

    protected fun onProgressUpdate(vararg progress: Int) {
    }

    override fun onPostExecute(result: Long?) {
    }
}

Java - JPA - @Version annotation

Every time an entity is updated in the database the version field will be increased by one. Every operation that updates the entity in the database will have appended WHERE version = VERSION_THAT_WAS_LOADED_FROM_DATABASE to its query.

In checking affected rows of your operation the jpa framework can make sure there was no concurrent modification between loading and persisting your entity because the query would not find your entity in the database when it's version number has been increased between load and persist.

Send json post using php

You can use CURL for this purpose see the example code:

$url = "your url";    
$content = json_encode("your data to be sent");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}


curl_close($curl);

$response = json_decode($json_response, true);

Removing leading and trailing spaces from a string

I am currently using these functions:

// trim from left
inline std::string& ltrim(std::string& s, const char* t = " \t\n\r\f\v")
{
    s.erase(0, s.find_first_not_of(t));
    return s;
}

// trim from right
inline std::string& rtrim(std::string& s, const char* t = " \t\n\r\f\v")
{
    s.erase(s.find_last_not_of(t) + 1);
    return s;
}

// trim from left & right
inline std::string& trim(std::string& s, const char* t = " \t\n\r\f\v")
{
    return ltrim(rtrim(s, t), t);
}

// copying versions

inline std::string ltrim_copy(std::string s, const char* t = " \t\n\r\f\v")
{
    return ltrim(s, t);
}

inline std::string rtrim_copy(std::string s, const char* t = " \t\n\r\f\v")
{
    return rtrim(s, t);
}

inline std::string trim_copy(std::string s, const char* t = " \t\n\r\f\v")
{
    return trim(s, t);
}

RESTful URL design for search

In addition i would also suggest:

/cars/search/all{?color,model,year}
/cars/search/by-parameters{?color,model,year}
/cars/search/by-vendor{?vendor}

Here, Search is considered as a child resource of Cars resource.

Dynamic button click event handler

@Debasish Sahu, your answer is an answer to another question, namely: how to know which button (or any other control) was clicked when there is a common handler for a couple of controls? So I'm giving an answer to this question how I usually do it, almost the same as yours, but note that also works without type conversion when it handles the same type of Controls:

Private Sub btn_done_clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim selectedBtn As Button = sender
    MsgBox("you have clicked button " & selectedBtn.Name)
End Sub

Error 500: Premature end of script headers

In my case (referencing a PHP file in the top folder of a Wordpress plugin) I had to change the permissions on that folder. My test environment was fine, but when deployed the folder had 775. I changed it to 755 and it works fine.

How to define Singleton in TypeScript

You can use class expressions for this (as of 1.6 I believe).

var x = new (class {
    /* ... lots of singleton logic ... */
    public someMethod() { ... }
})();

or with the name if your class needs to access its type internally

var x = new (class Singleton {
    /* ... lots of singleton logic ... */
    public someMethod(): Singleton { ... }
})();

Another option is to use a local class inside of your singleton using some static members

class Singleton {

    private static _instance;
    public static get instance() {

        class InternalSingleton {
            someMethod() { }

            //more singleton logic
        }

        if(!Singleton._instance) {
            Singleton._instance = new InternalSingleton();
        }

        return <InternalSingleton>Singleton._instance;
    }
}

var x = Singleton.instance;
x.someMethod();

ArrayList of String Arrays

Simple and straight forward way to create ArrayList of String

    List<String> category = Arrays.asList("everton", "liverpool", "swansea", "chelsea");

Cheers

How to resize the jQuery DatePicker control

$('.ui-datepicker').css('font-size', $('.ui-datepicker').width() / 20 + 'px');

How can I determine whether a 2D Point is within a Polygon?

If you are looking for a java-script library there's a javascript google maps v3 extension for the Polygon class to detect whether or not a point resides within it.

var polygon = new google.maps.Polygon([], "#000000", 1, 1, "#336699", 0.3);
var isWithinPolygon = polygon.containsLatLng(40, -90);

Google Extention Github

HTTP response header content disposition for attachments

neither use inline; nor attachment; just use

response.setContentType("text/xml");
response.setHeader( "Content-Disposition", "filename=" + filename );

or

response.setHeader( "Content-Disposition", "filename=\"" + filename + "\"" );

or

response.setHeader( "Content-Disposition", "filename=\"" + 
  filename.substring(0, filename.lastIndexOf('.')) + "\"");

Merge or combine by rownames

cbind.fill <- function(x, y){
  xrn <- rownames(x)
  yrn <- rownames(y)
  rn <- union(xrn, yrn)
  xcn <- colnames(x)
  ycn <- colnames(y)
  if(is.null(xrn) | is.null(yrn) | is.null(xcn) | is.null(ycn)) 
    stop("NULL rownames or colnames")
  z <- matrix(NA, nrow=length(rn), ncol=length(xcn)+length(ycn))
  rownames(z) <- rn
  colnames(z) <- c(xcn, ycn)
  idx <- match(rn, xrn)
  z[!is.na(idx), 1:length(xcn)] <- x[na.omit(idx),]
  idy <- match(rn, yrn)
  z[!is.na(idy), length(xcn)+(1:length(ycn))] <- y[na.omit(idy),]
  return(z)
}

Declaring abstract method in TypeScript

The name property is marked as protected. This was added in TypeScript 1.3 and is now firmly established.

The makeSound method is marked as abstract, as is the class. You cannot directly instantiate an Animal now, because it is abstract. This is part of TypeScript 1.6, which is now officially live.

abstract class Animal {
    constructor(protected name: string) { }

    abstract makeSound(input : string) : string;

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }

    makeSound(input : string) : string {
        return "sssss"+input;
    }

    move() {
        alert("Slithering...");
        super.move(5);
    }
}

The old way of mimicking an abstract method was to throw an error if anyone used it. You shouldn't need to do this any more once TypeScript 1.6 lands in your project:

class Animal {
    constructor(public name) { }
    makeSound(input : string) : string {
        throw new Error('This method is abstract');
    }
    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name) { super(name); }
    makeSound(input : string) : string {
        return "sssss"+input;
    }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

Possible to extend types in Typescript?

The keyword extends can be used for interfaces and classes only.

If you just want to declare a type that has additional properties, you can use intersection type:

type UserEvent = Event & {UserId: string}

UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type, if the type satisfies some restrictions:

type Event = {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

It does not work the other way round - UserEvent must be declared as interface, not a type if you want to use extends syntax.

And it's still impossible to use extend with arbitrary types - for example, it does not work if Event is a type parameter without any constraints.

button image as form input submit button?

Make the submit button the main image you are using. So the form tags would come first then submit button which is your only image so the image is your clickable image form. Then just make sure to put whatever you are passing before the submit button code.

Importing a csv into mysql via command line

I know this says command line, but just a tidbit of something quick to try that might work, if you've got MySQL workbench and the csv isn't too large, you can simply

  • SELECT * FROM table
  • Copy entire CSV
  • Paste csv into the query results section of Workbench
  • Hope for the best

I say hope for the best because this is MySQL Workbench. You never know when it's going to explode


If you want to do this on a remote server, you would do

mysql -h<server|ip> -u<username> -p --local-infile bark -e "LOAD DATA LOCAL INFILE '<filename.csv>'  INTO TABLE <table>  FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'"

Note, I didn't put a password after -p as putting one on the command line is considered bad practice

Why AVD Manager options are not showing in Android Studio

The only thing that worked for me (with an existing project on a fresh install of macOS) was:

"File" > "Sync Project with Gradle Files"

This was odd to me since building the project succeeded with no errors or log messages, but I couldn’t run the project and there was nothing Android in the Tools menu.

I had already tried creating a new Android project and running that. It didn't help with my existing project.

Standard deviation of a list

In python 2.7 you can use NumPy's numpy.std() gives the population standard deviation.

In Python 3.4 statistics.stdev() returns the sample standard deviation. The pstdv() function is the same as numpy.std().

How does tuple comparison work in Python?

The Python documentation does explain it.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

Best way to pretty print a hash

Another solution which works better for me than pp or awesome_print:

require 'pry' # must install the gem... but you ALWAYS want pry installed anyways
Pry::ColorPrinter.pp(obj)

Remove all elements contained in another array

If you are using an array of objects. Then the below code should do the magic, where an object property will be the criteria to remove duplicate items.

In the below example, duplicates have been removed comparing name of each item.

Try this example. http://jsfiddle.net/deepak7641/zLj133rh/

_x000D_
_x000D_
var myArray = [_x000D_
  {name: 'deepak', place: 'bangalore'}, _x000D_
  {name: 'chirag', place: 'bangalore'}, _x000D_
  {name: 'alok', place: 'berhampur'}, _x000D_
  {name: 'chandan', place: 'mumbai'}_x000D_
];_x000D_
var toRemove = [_x000D_
  {name: 'deepak', place: 'bangalore'},_x000D_
  {name: 'alok', place: 'berhampur'}_x000D_
];_x000D_
_x000D_
for( var i=myArray.length - 1; i>=0; i--){_x000D_
  for( var j=0; j<toRemove.length; j++){_x000D_
      if(myArray[i] && (myArray[i].name === toRemove[j].name)){_x000D_
      myArray.splice(i, 1);_x000D_
     }_x000D_
    }_x000D_
}_x000D_
_x000D_
alert(JSON.stringify(myArray));
_x000D_
_x000D_
_x000D_

How to set bootstrap navbar active class with Angular JS?

A very elegant way is to use ng-controller to run a single controller outside of the ng-view:

<div class="collapse navbar-collapse" ng-controller="HeaderController">
    <ul class="nav navbar-nav">
        <li ng-class="{ active: isActive('/')}"><a href="/">Home</a></li>
        <li ng-class="{ active: isActive('/dogs')}"><a href="/dogs">Dogs</a></li>
        <li ng-class="{ active: isActive('/cats')}"><a href="/cats">Cats</a></li>
    </ul>
</div>
<div ng-view></div>

and include in controllers.js:

function HeaderController($scope, $location) 
{ 
    $scope.isActive = function (viewLocation) { 
        return viewLocation === $location.path();
    };
}

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

Can a java lambda have more than 1 parameter?

Some lambda function :

import org.junit.Test;
import java.awt.event.ActionListener;
import java.util.function.Function;

public class TestLambda {

@Test
public void testLambda() {

    System.out.println("test some lambda function");

    ////////////////////////////////////////////
    //1-any input | any output:
    //lambda define:
    Runnable lambda1 = () -> System.out.println("no parameter");
    //lambda execute:
    lambda1.run();


    ////////////////////////////////////////////
    //2-one input(as ActionEvent) | any output:
    //lambda define:
    ActionListener lambda2 = (p) -> System.out.println("One parameter as action");
    //lambda execute:
    lambda2.actionPerformed(null);


    ////////////////////////////////////////////
    //3-one input | by output(as Integer):
    //lambda define:
    Function<String, Integer> lambda3 = (p1) -> {
        System.out.println("one parameters: " + p1);
        return 10;
    };
    //lambda execute:
    lambda3.apply("test");


    ////////////////////////////////////////////
    //4-two input | any output
    //lambda define:
    TwoParameterFunctionWithoutReturn<String, Integer> lambda4 = (p1, p2) -> {
        System.out.println("two parameters: " + p1 + ", " + p2);
    };
    //lambda execute:
    lambda4.apply("param1", 10);


    ////////////////////////////////////////////
    //5-two input | by output(as Integer)
    //lambda define:
    TwoParameterFunctionByReturn<Integer, Integer> lambda5 = (p1, p2) -> {
        System.out.println("two parameters: " + p1 + ", " + p2);
        return p1 + p2;
    };
    //lambda execute:
    lambda5.apply(10, 20);


    ////////////////////////////////////////////
    //6-three input(Integer,Integer,String) | by output(as Integer)
    //lambda define:
    ThreeParameterFunctionByReturn<Integer, Integer, Integer> lambda6 = (p1, p2, p3) -> {
        System.out.println("three parameters: " + p1 + ", " + p2 + ", " + p3);
        return p1 + p2 + p3;
    };
    //lambda execute:
    lambda6.apply(10, 20, 30);

}


@FunctionalInterface
public interface TwoParameterFunctionWithoutReturn<T, U> {
    public void apply(T t, U u);
}

@FunctionalInterface
public interface TwoParameterFunctionByReturn<T, U> {
    public T apply(T t, U u);
}

@FunctionalInterface
public interface ThreeParameterFunctionByReturn<M, N, O> {
    public Integer apply(M m, N n, O o);
}
}

How to get a product's image in Magento?

echo $_product->getImageUrl();

This method of the Product class should do the trick for you.

How to add 10 minutes to my (String) time?

I would use Joda Time, parse the time as a LocalTime, and then use

time = time.plusMinutes(10);

Short but complete program to demonstrate this:

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
        LocalTime time = formatter.parseLocalTime("14:10");
        time = time.plusMinutes(10);
        System.out.println(formatter.print(time));
    }       
}

Note that I would definitely use Joda Time instead of java.util.Date/Calendar if you possibly can - it's a much nicer API.

figure of imshow() is too small

If you don't give an aspect argument to imshow, it will use the value for image.aspect in your matplotlibrc. The default for this value in a new matplotlibrc is equal. So imshow will plot your array with equal aspect ratio.

If you don't need an equal aspect you can set aspect to auto

imshow(random.rand(8, 90), interpolation='nearest', aspect='auto')

which gives the following figure

imshow-auto

If you want an equal aspect ratio you have to adapt your figsize according to the aspect

fig, ax = subplots(figsize=(18, 2))
ax.imshow(random.rand(8, 90), interpolation='nearest')
tight_layout()

which gives you:

imshow-equal

jQuery select2 get value of select tag?

Other answers wasn't working for me so i developed solution:

I created option with class="option-item" for easy targeting

HTML :

<select id="select-test">
<option value="5-val" id="first-id" class="option-item"> First option </option>
</select>

Then for every selected option i added display none property

CSS:

option:checked {
   display: none;
}

Now we can add change to our SelectBox to find our selected option with display none property by simple :hidden attribute

JQuery:

$('#select-test').change(function(){
//value 
    $('#select-test').find('.option-item:hidden').val();
//id
    $('#select-test').find('.option-item:hidden').attr('id');
//text
    $('#select-test').find('.option-item:hidden').text();
});

Working fiddle: https://jsfiddle.net/Friiz/2dk4003j/10/

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

what is Array.any? for javascript

polyfill* :

Array.prototype.any=function(){
    return (this.some)?this.some(...arguments):this.filter(...arguments).reduce((a,b)=> a || b)
};

If you want to call it as Ruby , that it means .any not .any(), use :

Object.defineProperty( Array.prototype, 'any', {
  get: function ( ) { return (this.some)?this.some(function(e){return e}):this.filter(function(e){return e}).reduce((a,b)=> a || b) }
} ); 

__

`* : https://en.wikipedia.org/wiki/Polyfill

Getting "conflicting types for function" in C, why?

A C Function-Declaration Backgrounder

In C, function declarations don't work like they do in other languages: The C compiler itself doesn't search backward and forward in the file to find the function's declaration from the place you call it, and it doesn't scan the file multiple times to figure out the relationships either: The compiler only scans forward in the file exactly once, from top to bottom. Connecting function calls to function declarations is part of the linker's job, and is only done after the file is compiled down to raw assembly instructions.

This means that as the compiler scans forward through the file, the very first time the compiler encounters the name of a function, one of two things have to be the case: It either is seeing the function declaration itself, in which case the compiler knows exactly what the function is and what types it takes as arguments and what types it returns — or it's a call to the function, and the compiler has to guess how the function will eventually be declared.

(There's a third option, where the name is used in a function prototype, but we'll ignore that for now, since if you're seeing this problem in the first place, you're probably not using prototypes.)

History Lesson

In the earliest days of C, the fact that the compiler had to guess types wasn't really an issue: All of the types were more-or-less the same — pretty much everything was either an int or a pointer, and they were the same size. (In fact, in B, the language that preceded C, there were no types at all; everything was just an int or pointer and its type was determined solely by how you used it!) So the compiler could safely guess the behavior of any function just based on the number of parameters that were passed: If you passed two parameters, the compiler would push two things onto the call stack, and presumably the callee would have two arguments declared, and that would all line up. If you passed only one parameter but the function expected two, it would still sort-of work, and the second argument would just be ignored/garbage. If you passed three parameters and the function expected two, it would also still sort-of work, and the third parameter would be ignored and stomped on by the function's local variables. (Some old C code still expects these mismatched-argument rules will work, too.)

But having the compiler let you pass anything to anything isn't really a good way to design a programming language. It worked well in the early days because the early C programmers were mostly wizards, and they knew not to pass the wrong type to functions, and even if they did get the types wrong, there were always tools like lint that could do deeper double-checking of your C code and warn you about such things.

Fast-forward to today, and we're not quite in the same boat. C has grown up, and a lot of people are programming in it who aren't wizards, and to accommodate them (and to accommodate everyone else who regularly used lint anyway), the compilers have taken on many of the abilities that were previously part of lint — especially the part where they check your code to ensure it's type-safe. Early C compilers would let you write int foo = "hello"; and it would just blithely assign the pointer to the integer, and it was up to you to make sure you weren't doing anything stupid. Modern C compilers complain loudly when you get your types wrong, and that's a good thing.

Type Conflicts

So what's all this got to do with the mysterious conflicting-type error on the line of the function declaration? As I said above, C compilers still have to either know or guess what a name means the first time they see that name as they scan forward through the file: They can know what it means it if it's an actual function declaration itself (or a function "prototype," more on that shortly), but if it's just a call to the function, they have to guess. And, sadly, the guess is often wrong.

When the compiler saw your call to do_something(), it looked at how it was invoked, and it concluded that do_something() would eventually be declared like this:

int do_something(char arg1[], char arg2[])
{
    ...
}

Why did it conclude that? Because that's how you called it! (Some C compilers may conclude that it was int do_something(int arg1, int arg2), or simply int do_something(...), both of which are even farther from what you want, but the important point is that regardless of how the compiler guesses the types, it guesses them differently from what your actual function uses.)

Later on, as the compiler scans forward in the file, it sees your actual declaration of char *do_something(char *, char *). That function declaration isn't even close to the declaration that the compiler guessed, which means that the line where the compiler compiled the call was compiled wrong, and the program is just not going to work. So it rightly prints an error telling you that your code isn't going to work as written.

You might be wondering, "Why does it assume I'm returning an int?" Well, it assumes that type because there's no information to the contrary: printf() can take in any type in its variable arguments, so without a better answer, int is as good a guess as any. (Many early C compilers always assumed int for every unspecified type, and assumed you meant ... for the arguments for every function declared f() — not void — which is why many modern code standards recommend always putting void in for the arguments if there really aren't supposed to be any.)

The Fix

There are two common fixes for the function-declaration error.

The first solution, which is recommended by many other answers here, is to put a prototype in the source code above the place where the function is first called. A prototype looks just like the function's declaration, but it has a semicolon where the body should be:

char *do_something(char *dest, const char *src);

By putting the prototype first, the compiler then knows what the function will eventually look like, so it doesn't have to guess. By convention, programmers often put prototypes at the top of the file, just under the #include statements, to ensure that they'll always be defined before any potential usages of them.

The other solution, which also shows up in some real-world code, is to simply reorder your functions so that the function declarations are always before anything that calls them! You could move the entire char *do_something(char *dest, const char *src) { ... } function above the first call to it, and the compiler then would know exactly what the function looks like and wouldn't have to guess.

In practice, most people use function prototypes, because you can also take function prototypes and move them into header (.h) files so that code in other .c files can call those functions. But either solution works, and many codebases use both.

C99 and C11

It is useful to note that the rules are slightly different in the newer versions of the C standard. In the earlier versions (C89 and K&R), the compiler really would guess the types at function-call time (and K&R-era compilers often wouldn't even warn you if they were wrong). C99 and C11 both require that the function declaration/prototype must precede the first call, and it's an error if it doesn't. But many modern C compilers — mainly for backward compatibility with earlier code — will only warn about a missing prototype and not consider it an error.

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

This question already has a great answer, but I ran into the same error, in a different scenario: displaying a List in an EditorTemplate.

I have a model like this:

public class Foo
{
    public string FooName { get; set; }
    public List<Bar> Bars { get; set; }
}

public class Bar
{
    public string BarName { get; set; }
}

And this is my main view:

@model Foo

@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
@Html.EditorFor(m => m.Bars)

And this is my Bar EditorTemplate (Bar.cshtml)

@model List<Bar>

<div class="some-style">
    @foreach (var item in Model)
    {
        <label>@item.BarName</label>
    }
</div>

And I got this error:

The model item passed into the dictionary is of type 'Bar', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Bar]


The reason for this error is that EditorFor already iterates the List for you, so if you pass a collection to it, it would display the editor template once for each item in the collection.

This is how I fixed this problem:

Brought the styles outside of the editor template, and into the main view:

@model Foo

@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
<div class="some-style">
    @Html.EditorFor(m => m.Bars)
</div>

And changed the EditorTemplate (Bar.cshtml) to this:

@model Bar

<label>@Model.BarName</label>

Changing file extension in Python

An elegant way using pathlib.Path:

from pathlib import Path
p = Path('mysequence.fasta')
p.rename(p.with_suffix('.aln'))

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

<input type="hidden" id="date"/>
<script>document.getElementById("date").value = new Date().toJSON().slice(0,10)</script>

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

With boto3, this is the code :

s3_client = boto3.resource('s3', region_name='eu-central-1')

or

s3_client = boto3.client('s3', region_name='eu-central-1')

How to install Visual C++ Build tools?

I had the same issue too, the problem is exacerbated with the download link now only working for Visual Studio 2017, and installing the package from the download link did nothing for VS2015, although it took up 5gB of space.

I looked everywhere on how to do it with the Nu Get package manager and I couldn't find the solution.

It turns out it's even simpler than that, all you have to do is right-click the project or solution in the Solution Explorer from within Visual Studio, and click "Install Missing Components"

Comment shortcut Android Studio

Comment method like pro developers:

Windows/linux:

Line Comment : Ctrl + /

Block Comment : Ctrl + Shift

Method Commenting:

Type `/**` and press `Enter Key`

it will add the comment snippet like we see in standard documentation, give it a try this once.

/**
 * 
 * @param addOpacity
 */
public void setOpacityOnUserImage(boolean addOpacity) {
// Your business logic. 
}

Change grid interval and specify tick labels in Matplotlib

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop ? put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things: You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax. Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid
ax.grid(which='both')

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

plt.show()

Output is this:

result

Add resources, config files to your jar using gradle

Thanks guys, I was migrating an existing project to Gradle and didn't like the idea of changing the project structure that much.

I have figured it out, thought this information could be useful to beginners.

Here is a sample task from my 'build.gradle':

version = '1.0.0'

jar {
   baseName = 'analytics'
   from('src/main/java') {
      include 'config/**/*.xml'
   }

   manifest {
       attributes 'Implementation-Title': 'Analytics Library', 'Implementation-Version': version
   }
}

Why does this code using random strings print "hello world"?

From the Java docs, this is an intentional feature when specifying a seed value for the Random class.

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code.

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html

Odd though, you would think there are implicit security issues in having predictable 'random' numbers.

Check if element is clickable in Selenium Java

wait.until(ExpectedConditions) won't return null, it will either meet the condition or throw TimeoutException.

You can check if the element is displayed and enabled

WebElement element = driver.findElement(By.xpath);
if (element.isDisplayed() && element.isEnabled()) {
    element.click();
}

How to check if an element is in an array

Here is my little extension I just wrote to check if my delegate array contains a delegate object or not (Swift 2). :) It Also works with value types like a charm.

extension Array
{
    func containsObject(object: Any) -> Bool
    {
        if let anObject: AnyObject = object as? AnyObject
        {
            for obj in self
            {
                if let anObj: AnyObject = obj as? AnyObject
                {
                    if anObj === anObject { return true }
                }
            }
        }
        return false
    }
}

If you have an idea how to optimize this code, than just let me know.

Loaded nib but the 'view' outlet was not set

Just had the same error in my project, but different reason. In my case I had an IBOutlet setup with the name "View" in my custom UITableViewController class. I knew "view" was special because that is a member of the base class, but I didn't think View (different case) would also be a problem. I guess some areas of Cocoa are not case-sensitive, and probably loading a xib is one of those areas. So I just renamed it to DefaultView and all is good now.

How can I render a list select box (dropdown) with bootstrap?

I'm currently fighting with dropdowns and I'd like to share my experiences:

There are specific situations where <select> can't be used and must be 'emulated' with dropdown.

For example if you want to create bootstrap input groups, like Buttons with dropdowns (see http://getbootstrap.com/components/#input-groups-buttons-dropdowns). Unfortunately <select> is not supported in input groups, it will not be rendered properly.

Or does anybody solved this already? I would be very interested on the solution.

And to make it even more complicated, you can't use so simply $(this).text() to catch what user selected in dropdown if you're using glypicons or font awesome icons as content for dropdown. For example: <li id="someId"><a href="#0"><i class="fa fa-minus"></i></a></li> Because in this case there is no text and if you will add some then it will be also displayed in dropdown element and this is unwanted.

I found two possible solutions:

1) Use $(this).html() to get content of the selected <li> element and then to examine it, but you will get something like <a href="#0"><i class="fa fa-minus"></i></a> so you need to play with this to extract what you need.

2) Use $(this).text() and hide the text in element in hidden span: <li id="someId"><a href="#0"><i class="fa fa-minus"><span class="hidden">text</span></i></a></li>. For me this is simple and elegant solution, you can put any text you need, text will be hidden, and you don't need to do any transformations of $(this).html() result like in option 1) to get what you need.

I hope it's clear and can help somebody :-)

How to generate unique IDs for form labels in React?

I create a uniqueId generator module (Typescript):

const uniqueId = ((): ((prefix: string) => string) => {
  let counter = 0;
  return (prefix: string): string => `${prefix}${++counter}`;
})();

export default uniqueId;

And use top module to generate unique ids:

import React, { FC, ReactElement } from 'react'
import uniqueId from '../../modules/uniqueId';

const Component: FC = (): ReactElement => {
  const [inputId] = useState(uniqueId('input-'));
  return (
    <label htmlFor={inputId}>
      <span>text</span>
      <input id={inputId} type="text" />
    </label>
  );
};     

Sum function in VBA

Range("A10") = WorksheetFunction.Sum(Worksheets("Sheet1").Range("A1", "A9"))

Where

Range("A10") is the answer cell

Range("A1", "A9") is the range to calculate

Linq code to select one item

These are the preferred methods:

var item = Items.SingleOrDefault(x => x.Id == 123);

Or

var item = Items.Single(x => x.Id == 123);

How do I get a list of folders and sub folders without the files?

 Displays a list of files and subdirectories in a directory.

 DIR [ drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
          Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
           H  Hidden files               A  Files ready for archiving
           S  System files               I  Not content indexed files
           L  Reparse Points             -  Prefix meaning not

just set type of desired file attribute, in your case /A:D (directory)

dir /s/b/o:n/A:D > f.txt

ArrayList - How to modify a member of an object?

Try this.This works while traversing the code and modifying the fields at once of all the elements of Arraylist.

public Employee(String name,String email){
this.name=name;
this.email=email;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setEmail(String email) {
this.email = email;
}

public String getEmail() {
return email;
}

for(int i=0;i++){
List.get(i).setName("Anonymous");
List.get(i).setEmail("[email protected]");
}

Interface naming in Java

As another poster said, it's typically preferable to have interfaces define capabilities not types. I would tend not to "implement" something like a "User," and this is why "IUser" often isn't really necessary in the way described here. I often see classes as nouns and interfaces as adjectives:

class Number implements Comparable{...}  
class MyThread implements Runnable{...}
class SessionData implements Serializable{....}

Sometimes an Adjective doesn't make sense, but I'd still generally be using interfaces to model behavior, actions, capabilities, properties, etc,... not types.

Also, If you were really only going to make one User and call it User then what's the point of also having an IUser interface? And if you are going to have a few different types of users that need to implement a common interface, what does appending an "I" to the interface save you in choosing names of the implementations?

I think a more realistic example would be that some types of users need to be able to login to a particular API. We could define a Login interface, and then have a "User" parent class with SuperUser, DefaultUser, AdminUser, AdministrativeContact, etc suclasses, some of which will or won't implement the Login (Loginable?) interface as necessary.

Dynamically updating css in Angular 2

Check working Demo here

import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from 'angular2/form';

import {Directive, ElementRef, Renderer, Input,ViewChild,AfterViewInit} from 'angular2/core';

@Component({
  selector: 'my-app',
    template: `
    <style>
       .myStyle{
        width:200px;
        height:100px;
        border:1px solid;
        margin-top:20px;
        background:gray;
        text-align:center;
       }
    </style>

          <div [class.myStyle]="my" [style.background-color]="randomColor" [style.width]="width+'px'" [style.height]="height+'px'"> my width={{width}} & height={{height}}</div>
    `,
    directives: []
})

export class AppComponent {
  my:boolean=true;
  width:number=200px;
  height:number=100px;
  randomColor;
  randomNumber;
  intervalId;
  textArray = [
    'blue',
    'green',
    'yellow',
    'orange',
    'pink'
  ];


  constructor() 
  {
    this.start();
  }

      start()
      { 
        this.randomNumber = Math.floor(Math.random()*this.textArray.length);
        this.randomColor=this.textArray[this.randomNumber];
        console.log('start' + this.randomNumber);
        this.intervalId = setInterval(()=>{
         this.width=this.width+20;
         this.height=this.height+10;
         console.log(this.width +" "+ this.height)
         if(this.width==300)
         {
           this.stop();
         }

        }, 1000);
      }
      stop()
      {
        console.log('stop');
        clearInterval(this.intervalId);
        this.width=200;
        this.height=100;
        this.start();

      }
 }

bootstrap(AppComponent, []);

C fopen vs open

If you have a FILE *, you can use functions like fscanf, fprintf and fgets etc. If you have just the file descriptor, you have limited (but likely faster) input and output routines read, write etc.

How can I capture the right-click event in JavaScript?

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum
</div>

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('success!');
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

App can't be opened because it is from an unidentified developer

Open terminal, go to extracted folder of eclipse and run the following command:

./eclipse -clean

How to establish a connection pool in JDBC?

As answered by others, you will probably be happy with Apache Dbcp or c3p0. Both are popular, and work fine.

Regarding your doubt

Doesn't javax.sql or java.sql have pooled connection implementations? Why wouldn't it be best to use these?

They don't provide implementations, rather interfaces and some support classes, only revelant to the programmers that implement third party libraries (pools or drivers). Normally you don't even look at that. Your code should deal with the connections from your pool just as they were "plain" connections, in a transparent way.

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

I started with Lua but, then I found that I wanted to see the results instead of just the good old command line flash. So i just added the following line to my file and hey presto, the standard:

please press any key to continue...

os.execute("PAUSE")

My example file is only a print and then a pause statment so I am sure you don't need that posted here.

I am not sure of the CPU implications of a running a process for a full script. However stopping the code mid flow in debugging could be useful.

When increasing the size of VARCHAR column on a large table could there be any problems?

In my case alter column was not working so one can use 'Modify' command, like:

alter table [table_name] MODIFY column [column_name] varchar(1200);

How do I get console input in javascript?

As you mentioned, prompt works for browsers all the way back to IE:

var answer = prompt('question', 'defaultAnswer');

prompt in IE

For Node.js > v7.6, you can use console-read-write, which is a wrapper around the low-level readline module:

const io = require('console-read-write');

async function main() {
  // Simple readline scenario
  io.write('I will echo whatever you write!');
  io.write(await io.read());

  // Simple question scenario
  io.write(`hello ${await io.ask('Who are you?')}!`);

  // Since you are not blocking the IO, you can go wild with while loops!
  let saidHi = false;
  while (!saidHi) {
    io.write('Say hi or I will repeat...');
    saidHi = await io.read() === 'hi';
  }

  io.write('Thanks! Now you may leave.');
}

main();
// I will echo whatever you write!
// > ok
// ok
// Who are you? someone
// hello someone!
// Say hi or I will repeat...
// > no
// Say hi or I will repeat...
// > ok
// Say hi or I will repeat...
// > hi
// Thanks! Now you may leave.

Disclosure I'm author and maintainer of console-read-write

For SpiderMonkey, simple readline as suggested by @MooGoo and @Zaz.

Maven: How to include jars, which are not available in reps into a J2EE project?

As you've said you don't want to set up your own repository, perhaps this will help.

You can use the install-file goal of the maven-install-plugin to install a file to the local repository. If you create a script with a Maven invocation for each file and keep it alongside the jars, you (and anyone else with access) can easily install the jars (and associated pom files) to their local repository.

For example:

mvn install:install-file -Dfile=/usr/jars/foo.jar -DpomFile=/usr/jars/foo.pom
mvn install:install-file -Dfile=/usr/jars/bar.jar -DpomFile=/usr/jars/bar.pom

or just

mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0 -Dpackaging=jar

You can then reference the dependencies as normal in your project.

However your best bet is still to set up an internal remote repository and I'd recommend using Nexus myself. It can run on your development box if needed, and the overhead is minimal.

Convert pyspark string to date format

The strptime() approach does not work for me. I get another cleaner solution, using cast:

from pyspark.sql.types import DateType
spark_df1 = spark_df.withColumn("record_date",spark_df['order_submitted_date'].cast(DateType()))
#below is the result
spark_df1.select('order_submitted_date','record_date').show(10,False)

+---------------------+-----------+
|order_submitted_date |record_date|
+---------------------+-----------+
|2015-08-19 12:54:16.0|2015-08-19 |
|2016-04-14 13:55:50.0|2016-04-14 |
|2013-10-11 18:23:36.0|2013-10-11 |
|2015-08-19 20:18:55.0|2015-08-19 |
|2015-08-20 12:07:40.0|2015-08-20 |
|2013-10-11 21:24:12.0|2013-10-11 |
|2013-10-11 23:29:28.0|2013-10-11 |
|2015-08-20 16:59:35.0|2015-08-20 |
|2015-08-20 17:32:03.0|2015-08-20 |
|2016-04-13 16:56:21.0|2016-04-13 |

How do I install Maven with Yum?

Maven is packaged for Fedora since mid 2014, so it is now pretty easy. Just type

sudo dnf install maven

Now test the installation, just run maven in a random directory

mvn

And it will fail, because you did not specify a goal, e.g. mvn package

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.102 s
[INFO] Finished at: 2017-11-14T13:45:00+01:00
[INFO] Final Memory: 8M/176M
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build

[...]

C/C++ line number

Use __LINE__ (that's double-underscore LINE double-underscore), the preprocessor will replace it with the line number on which it is encountered.

Email and phone Number Validation in android

I am always using this methode for Email Validation:

public boolean checkForEmail(Context c, EditText edit) {
    String str = edit.getText().toString();
    if (android.util.Patterns.EMAIL_ADDRESS.matcher(str).matches()) {
        return true;
    }
    Toast.makeText(c, "Email is not valid...", Toast.LENGTH_LONG).show();
    return false;
}

How to pass values across the pages in ASP.net without using Session

You can use query string to pass value from one page to another..

1.pass the value using querystring

 Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);

2.Retrive the value in the page u want by using any of these methods..

Method1:

    string v = Request.QueryString["value"];
    string n=Request.QueryString["number"];

Method2:

      NameValueCollection v = Request.QueryString;
    if (v.HasKeys())
    {
        string k = v.GetKey(0);
        string n = v.Get(0);
        if (k == "value")
        {
            lbltext.Text = n.ToString();
        }
        if (k == "value1")
        {
            lbltext.Text = "error occured";
        }
    }

NOTE:Method 2 is the fastest method.

How do I download a file with Angular2 or greater

Here's something I did in my case -

// service method
downloadFiles(vendorName, fileName) {
    return this.http.get(this.appconstants.filesDownloadUrl, { params: { vendorName: vendorName, fileName: fileName }, responseType: 'arraybuffer' }).map((res: ArrayBuffer) => { return res; })
        .catch((error: any) => _throw('Server error: ' + error));
}

// a controller function which actually downloads the file
saveData(data, fileName) {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    let blob = new Blob([data], { type: "octet/stream" }),
        url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
}

// a controller function to be called on requesting a download
downloadFiles() {
    this.service.downloadFiles(this.vendorName, this.fileName).subscribe(data => this.saveData(data, this.fileName), error => console.log("Error downloading the file."),
        () => console.info("OK"));
}

The solution is referenced from - here

How to extract the decimal part from a floating point number in C?

Use the floating number to subtract the floored value to get its fractional part:

double fractional = some_double - floor(some_double);

This prevents the typecasting to an integer, which may cause overflow if the floating number is very large that an integer value could not even contain it.

Also for negative values, this code gives you the positive fractional part of the floating number since floor() computes the largest integer value not greater than the input value.

How do I use the Tensorboard callback of Keras?

Create the Tensorboard callback:

from keras.callbacks import TensorBoard
from datetime import datetime
logDir = "./Graph/" + datetime.now().strftime("%Y%m%d-%H%M%S") + "/"
tb = TensorBoard(log_dir=logDir, histogram_freq=2, write_graph=True, write_images=True, write_grads=True)

Pass the Tensorboard callback to the fit call:

history = model.fit(X_train, y_train, epochs=200, callbacks=[tb])

When running the model, if you get a Keras error of

"You must feed a value for placeholder tensor"

try reseting the Keras session before the model creation by doing:

import keras.backend as K
K.clear_session()

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

This might not work for everyone, but I updated node and it fixed the issue for me when none of the above did

Use Async/Await with Axios in React.js

Two issues jump out:

  1. Your getData never returns anything, so its promise (async functions always return a promise) will resolve with undefined when it resolves

  2. The error message clearly shows you're trying to directly render the promise getData returns, rather than waiting for it to resolve and then rendering the resolution

Addressing #1: getData should return the result of calling json:

async getData(){
   const res = await axios('/data');
   return await res.json();
}

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do

<SomeElement>{getData()}</SomeElement>

...because that doesn't wait for the resolution. You'd need instead to use getData to set state:

this.getData().then(data => this.setState({data}))
              .catch(err => { /*...handle the error...*/});

...and use that state when rendering:

<SomeElement>{this.state.data}</SomeElement>

Update: Now that you've shown us your code, you'd need to do something like this:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            this.getData().then(data => this.setState({data}))
                          .catch(err => { /*...handle the error...*/});
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Futher update: You've indicated a preference for using await in componentDidMount rather than then and catch. You'd do that by nesting an async IIFE function within it and ensuring that function can't throw. (componentDidMount itself can't be async, nothing will consume that promise.) E.g.:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            (async () => {
                try {
                    this.setState({data: await this.getData()});
                } catch (e) {
                    //...handle the error...
                }
            })();
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Filtering DataSet

You can use DataTable.Select:

var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";

// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);  

Or you can use DataView:

ds.Tables[0].DefaultView.RowFilter = strExpr;  

UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:

var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I was getting this error when using Laravel and eloquent, trying to make a foreign key link would cause a 1452. The problem was lack of data in the linked table.

Please see here for an example: http://mstd.eu/index.php/2016/12/02/laravel-eloquent-integrity-constraint-violation-1452-foreign-key-constraint/

How do I add an active class to a Link from React Router?

To set class on the active navigation element

import { NavLink } from 'react-router-dom';

&

<NavLink to="/Home" activeClassName="active">Home</NavLink>

Node.js EACCES error when listening on most ports

It means node is not able to listen on defined port. Change it to something like 1234 or 2000 or 3000 and restart your server.

how to bypass Access-Control-Allow-Origin?

Have you tried actually adding the Access-Control-Allow-Origin header to the response sent from your server? Like, Access-Control-Allow-Origin: *?

How do I get the value of text input field using JavaScript?

<input id="new" >
    <button  onselect="myFunction()">it</button>    
    <script>
        function myFunction() {
            document.getElementById("new").value = "a";    
        }
    </script>

Python read in string from file and split it into values

I would do something like:

filename = "mynumbers.txt"
mynumbers = []
with open(filename) as f:
    for line in f:
        mynumbers.append([int(n) for n in line.strip().split(',')])
for pair in mynumbers:
    try:
        x,y = pair[0],pair[1]
        # Do Something with x and y
    except IndexError:
        print "A line in the file doesn't have enough entries."

The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

How to display multiple images in one figure correctly?

Here is my approach that you may try:

import numpy as np
import matplotlib.pyplot as plt

w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    img = np.random.randint(10, size=(h,w))
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
plt.show()

The resulting image:

output_image

(Original answer date: Oct 7 '17 at 4:20)

Edit 1

Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-

  1. access to individual axes of subplots
  2. possibility to plot more features on selected axes/subplot

New code:

import numpy as np
import matplotlib.pyplot as plt

w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5

# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# ax enables access to manipulate each of subplots
ax = []

for i in range(columns*rows):
    img = np.random.randint(10, size=(h,w))
    # create subplot and append to ax
    ax.append( fig.add_subplot(rows, columns, i+1) )
    ax[-1].set_title("ax:"+str(i))  # set title
    plt.imshow(img, alpha=0.25)

# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)

plt.show()  # finally, render the plot

The resulting plot:

enter image description here

Edit 2

In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index], which is more suitable for manipulation of array of many sub-plots.

import matplotlib.pyplot as plt
import numpy as np

# settings
h, w = 10, 10        # for raster image
nrows, ncols = 5, 4  # array of sub-plots
figsize = [6, 8]     # figure size, inches

# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)

# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
    # i runs from 0 to (nrows*ncols-1)
    # axi is equivalent with ax[rowid][colid]
    img = np.random.randint(10, size=(h,w))
    axi.imshow(img, alpha=0.25)
    # get indices of row/column
    rowid = i // ncols
    colid = i % ncols
    # write row/col indices as axes' title for identification
    axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))

# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)

plt.tight_layout(True)
plt.show()

The resulting plot:

plot3

How do I break a string across more than one line of code in JavaScript?

Put the backslash at the end of the line:

alert("Please Select file\
 to delete");

Edit    I have to note that this is not part of ECMAScript strings as line terminating characters are not allowed at all:

A 'LineTerminator' character cannot appear in a string literal, even if preceded by a backslash \. The correct way to cause a line terminator character to be part of the string value of a string literal is to use an escape sequence such as \n or \u000A.

So using string concatenation is the better choice.


Update 2015-01-05    String literals in ECMAScript5 allow the mentioned syntax:

A line terminator character cannot appear in a string literal, except as part of a LineContinuation to produce the empty character sequence. The correct way to cause a line terminator character to be part of the String value of a string literal is to use an escape sequence such as \n or \u000A.

Ruby: How to turn a hash into HTTP parameters?

2.6.3 :001 > hash = {:a => "a", :b => ["c", "d", "e"]}
=> {:a=>"a", :b=>["c", "d", "e"]}
2.6.3 :002 > hash.to_a.map { |x| "#{x[0]}=#{x[1].class == Array ? x[1].join(",") : x[1]}" 
}.join("&")
=> "a=a&b=c,d,e"

Gradle: Could not determine java version from '11.0.2'

Getting this error when doing a cordova build android --release

I was able to resolve this, after trying so so many different things, by simply doing :

npm install cordova -g   # to upgrade to version 10.0.0

cordova platform rm android
cordova platform add android    # to upgrade to android version 9.0.0

ASP.Net MVC - Read File from HttpPostedFileBase without save

A slight change to Thangamani Palanisamy answer, which allows the Binary reader to be disposed and corrects the input length issue in his comments.

string result = string.Empty;

using (BinaryReader b = new BinaryReader(file.InputStream))
{
  byte[] binData = b.ReadBytes(file.ContentLength);
  result = System.Text.Encoding.UTF8.GetString(binData);
}

How to recover corrupted Eclipse workspace?

I have succesfully recovered my existing workspace from a totally messed up situation (all kinds of core components giving NPE's and ClassCastExceptions and the like) by using this procedure:

  • Open Eclipse
  • Close error dialog
  • Select first project in the workspace
  • Right-click -> Refresh
  • Close error dialog
  • Close Eclipse
  • Close error dialog
  • Repeat for all projects in the workspace
  • (if your projects are in CVS/SVN etc, synchronize them)
  • Clean and rebuild all projects
  • Fixed

This whole procedure took me over half an hour for a big workspace, but it did fix it in the end.

In a Bash script, how can I exit the entire script if a certain condition occurs?

Try this statement:

exit 1

Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings.

Maven: How to rename the war file for the project?

You can follow the below step to modify the .war file name if you are using maven project.

Open pom.xml file of your maven project and go to the tag <build></build>,

  1. In that give your desired name between this tag : <finalName></finalName>.

    ex. : <finalName>krutik</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/

  2. If you want to access the url with slash '/' then you will have to specify then name as below:

    e.x. : <finalName>krutik#maheta</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/maheta

Uninstall Eclipse under OSX?

Here is my list of things to delete for OSX Mountain Lion

~/.eclipse (folder);

~/Library/Saved Application/org.eclipse.eclipse.savedState;

~/Library/Preferences/org.eclipse.eclipse.plist;

~/Library/Caches/org.eclipse.eclipse;

... and of course the eclipse install folder

CSS background-image-opacity?

.class {
    /* Fallback for web browsers that doesn't support RGBa */
    background: rgb(0, 0, 0);
    /* RGBa with 0.6 opacity */
    background: rgba(0, 0, 0, 0.6);
}

Copied from: http://robertnyman.com/2010/01/11/css-background-transparency-without-affecting-child-elements-through-rgba-and-filters/

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Show Hide div if, if statement is true

Probably the easiest to hide a div and show a div in PHP based on a variables and the operator.

<?php 
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
?>
<html>
<?php if($numrows > null){ ?>
     no meow :-(
<?php } ?>

<?php if($numrows < null){ ?>
     lots of meow
<?php } ?>
</html>

Here is my original code before adding your requirements:

<?php 
$address = 'meow';
?>
<?php if($address == null){ ?>
     no meow :-(
<?php } ?>

<?php if($address != null){ ?>
     lots of meow
<?php } ?>

Materialize CSS - Select Doesn't Seem to Render

The design of select functionality in materialize CSS is, in my opinion, a pretty good reason not to use it.

You have to initialize the select element with material_select(), as @littleguy23 mentions. If you don't, the select box is not even displayed! In an old-fashioned jQuery app, I can initialize it in the document ready function. Guess what, neither I nor many other people are using jQuery these days, nor do we initialize our apps in the document ready hook.

Dynamically created selects. What if I am creating selects dynamically, such as happens in a framework like Ember which generates views on the fly? I have to add logic in each view to initialize the select box every time a view is generated, or write a view mixin to handle that for me. And it's worse than that: when the view is generated, and in Ember terms didInsertElement is called, the binding to the list of options for the select box may not have been resolved yet, so I need special logic observing the option list to wait until it's populated before making the call to the material_select. If the options change, as they easily might, material_select has no idea about that and does not update the dropdown. I can call material_select again when the options change, but it appears that that does nothing (is ignored).

In other words, it appears that the design assumption behind materialize CSS's select boxes is that they are all there at page load, and their values never change.

Implementation. From an aesthetic point of view, I am also not in favor of the way materialize CSS implements its dropdowns, which is to create a parallel, shadow set of elements somewhere else in the DOM. Granted, alternatives such as select2 do the same thing, and there may be no other way to achieve some of the visual effects (really?). To me, though, when I inspect an element, I want to see the element, not some shadow version somewhere else that somebody magically created.

When Ember tears down the view, I am not sure that materialize CSS tears down the shadow elements it has created. Actually, I'd be quite surprised if it does. If my theory is correct, as views are generated and torn down, your DOM will end up getting polluted with dozens of sets of shadow dropdowns not connected to anything. This applies not only to Ember but any other MVC/template-based OPA front-end framework.

Bindings. I also have not been able to figure out how to get the value selected in the dialog box to bind back to anything useful in a framework like Ember that invokes select boxes through a {{view 'Ember.Select' value=country}} type interface. In other words, when something is selected, country is not updated. This is a deal-breaker.

Waves. By the way, the same issues apply to the "wave" effect on buttons. You have to initialize it every time a button is created. I personally don't care about the wave effect, and don't understand what all the fuss is about, but if you do want waves, be aware that you'll spend a good portion of the rest of your life worrying about how to initialize every single button when it's created.

I appreciate the effort made by the materialize CSS guys, and there are some nice visual effects there, but it's too big and has too many gotchas such as the above to be something that I would use. I'm now planning to rip out materialize CSS from my app and go back either to Bootstrap or a layer on top of Suit CSS. Your tools should make your life easier, not harder.

Reverse / invert a dictionary mapping

In addition to the other functions suggested above, if you like lambdas:

invert = lambda mydict: {v:k for k, v in mydict.items()}

Or, you could do it this way too:

invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )

How to continue the code on the next line in VBA

To have newline in code you use _

Example:

Dim a As Integer
a = 500 _
  + 80 _
  + 90

MsgBox a

Sort hash by key, return hash in Ruby

In Ruby 2.1 it is simple:

h.sort.to_h

How can I measure the actual memory usage of an application or process?

With ps or similar tools you will only get the amount of memory pages allocated by that process. This number is correct, but:

  • does not reflect the actual amount of memory used by the application, only the amount of memory reserved for it

  • can be misleading if pages are shared, for example by several threads or by using dynamically linked libraries

If you really want to know what amount of memory your application actually uses, you need to run it within a profiler. For example, Valgrind can give you insights about the amount of memory used, and, more importantly, about possible memory leaks in your program. The heap profiler tool of Valgrind is called 'massif':

Massif is a heap profiler. It performs detailed heap profiling by taking regular snapshots of a program's heap. It produces a graph showing heap usage over time, including information about which parts of the program are responsible for the most memory allocations. The graph is supplemented by a text or HTML file that includes more information for determining where the most memory is being allocated. Massif runs programs about 20x slower than normal.

As explained in the Valgrind documentation, you need to run the program through Valgrind:

valgrind --tool=massif <executable> <arguments>

Massif writes a dump of memory usage snapshots (e.g. massif.out.12345). These provide, (1) a timeline of memory usage, (2) for each snapshot, a record of where in your program memory was allocated. A great graphical tool for analyzing these files is massif-visualizer. But I found ms_print, a simple text-based tool shipped with Valgrind, to be of great help already.

To find memory leaks, use the (default) memcheck tool of valgrind.

Post-increment and Pre-increment concept?

Since we now have inline javascript snippets I might as well add an interactive example of pre and pos increment. It's not C++ but the concept stays the same.

_x000D_
_x000D_
let A = 1;_x000D_
let B = 1;_x000D_
_x000D_
console.log('A++ === 2', A++ === 2);_x000D_
console.log('++B === 2', ++B === 2);
_x000D_
_x000D_
_x000D_

Alternative for frames in html5 using iframes

While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.

Reset push notification settings for app

After hours of searching, and no luck with the suggestions above, this worked like to a charm for 3.x+

override func viewDidLoad() {
        super.viewDidLoad()


            requestAuthorization()

}

func requestAuthorization() {

        if #available(iOS 10.0, *) {

            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
                print("Access granted: \(granted.description)")
            }

        } else {
            // Fallback on earlier versions
        }

    }

How to clear a textbox using javascript

Your HTML code,

jquery code,

$("#textboxID").val('');

Replace String in all files in Eclipse

There is an option in search => file and shortcut is Ctrl+H. Go for further refer follow link. This is work fine with Eclipse Neon

Is there a way to find/replace across an entire project in Eclipse?

Can't access Eclipse marketplace

If you're able to successfully load a page from Eclipses internal web browser (by going to "Window"=>"Show View"=>"Other"=>"Internal Web Browser" and trying to open a page) BUT installing software from the eclipse marketplace and the "Help"=>"Install New Software" window are not working then this fix may help you (worked for me on a Windows 7 machine):

  1. Go to "Window"=>"Preferences"=>"General"=>"Network Connections" and set the Active Provider to "Native".
  2. Go into the Windows Control pannel and search firewall. Then select "Allow Program Through Windows Firewall" and click "Allow Other Program..." and add your eclipse installation.

enter image description here enter image description here

  1. Restart Eclipse and try refreshing a repository on the "Help"=>"Install New Software" window. It was able to successfull grab it for me.

counting the number of lines in a text file

with for-loop:

std::ifstream myFile;
std::string line;
int lines;

myFile.open(path);

for(lines = 0; std::getline(myFile,line); lines++);

std::cout << lines << std::endl;

Getting DOM node from React child element

I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.setRef = this.setRef.bind(this)
  }

  setRef(node) {
    this.childRef = node
  }

  render() {
    return <Child setRef={ this.setRef }/>
  }
}

const Child = ({ setRef }) => (
    <div ref={ setRef }>
    </div>
)

Here's an example of doing this with a modal:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      modalOpen: false
    }
    this.open = this.open.bind(this)
    this.close = this.close.bind(this)
    this.setModal = this.setModal.bind(this)
  }

  open() {
    this.setState({ open: true })
  }

  close(event) {
    if (!this.modal.contains(event.target)) {
      this.setState({ open: false })
    }
  }

  setModal(node) {
    this.modal = node
  }

  render() {
    let { modalOpen } = this.state
    return (
      <div>
        <button onClick={ this.open }>Open</button>
        {
          modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
        }
      </div>
    )
  }
}

const Modal = ({ close, setModal }) => (
  <div className='modal' onClick={ close }>
    <div className='modal-window' ref={ setModal }>
    </div>
  </div>
)

Latest jQuery version on Google's CDN

If you wish to use jQuery CDN other than Google hosted jQuery library, you might consider using this and ensures uses the latest version of jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

Convert file: Uri to File in Android

For this case, especially on Android, the way going for bytes is usually faster.

With this, I solved it by setting up a class FileHelper which is given the responsibility to deal with reading/writing bytes from/to file through stream and a class UriHelper which is given the responsibility to figure out path of Uri and permission.

As far as it's knew generally, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset) can help us to transfer string you want to bytes you need.

How to let UriHelper and FileHelper you to copy a picture noted by Uri into a file, you can run:

FileHelper.getInstance().copy(UriHelper.getInstance().toFile(uri_of_a_picture)
                        , FileHelper.getInstance().createExternalFile(null, UriHelper.getInstance().generateFileNameBasedOnTimeStamp()
                                + UriHelper.getInstance().getFileName(uri_of_a_picture, context), context)
                );

about my UriHelper:

public class UriHelper {
private static UriHelper INSTANCE = new UriHelper();

public static UriHelper getInstance() {
    return INSTANCE;
}

@SuppressLint("SimpleDateFormat")
public String generateFileNameBasedOnTimeStamp() {
    return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}

/**
 * if uri.getScheme.equals("content"), open it with a content resolver.
 * if the uri.Scheme.equals("file"), open it using normal file methods.
 */
//

public File toFile(Uri uri) {
    if (uri == null) return null;
    Logger.d(">>> uri path:" + uri.getPath());
    Logger.d(">>> uri string:" + uri.toString());
    return new File(uri.getPath());
}

public DocumentFile toDocumentFile(Uri uri) {
    if (uri == null) return null;
    Logger.d(">>> uri path:" + uri.getPath());
    Logger.d(">>> uri string:" + uri.toString());
    return DocumentFile.fromFile(new File(uri.getPath()));
}

public Uri toUri(File file) {
    if (file == null) return null;
    Logger.d(">>> file path:" + file.getAbsolutePath());
    return Uri.fromFile(file); //returns an immutable URI reference representing the file
}

public String getPath(Uri uri, Context context) {
    if (uri == null) return null;
    if (uri.getScheme() == null) return null;
    Logger.d(">>> uri path:" + uri.getPath());
    Logger.d(">>> uri string:" + uri.toString());
    String path;
    if (uri.getScheme().equals("content")) {
        //Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor == null) {
            Logger.e("!!! cursor is null");
            return null;
        }
        if (cursor.getCount() >= 0) {
            Logger.d("... the numbers of rows:" + cursor.getCount()
                        + "and the numbers of columns:" + cursor.getColumnCount());
            if (cursor.isBeforeFirst()) {
                while (cursor.moveToNext()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i<cursor.getColumnCount(); i++) {
                        stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
                        stringBuilder.append("\n");
                    }
                    Logger.d(stringBuilder.toString());
                }
            } else {
                cursor.moveToFirst();
                do {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i<cursor.getColumnCount(); i++) {
                        stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
                        stringBuilder.append("\n");
                    }
                    Logger.d(stringBuilder.toString());
                } while (cursor.moveToNext());
            }
            path = uri.getPath();
            cursor.close();
            Logger.d("... content scheme:" + uri.getScheme() + "  and return:" + path);
            return path;
        } else {
            path = uri.getPath();
            Logger.d("... content scheme:" + uri.getScheme()
                    + " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
                    + "  and return:" + path);
            return path;
        }
    } else {
        path = uri.getPath();
        Logger.d("... not content scheme:" + uri.getScheme() + "  and return:" + path);
        return path;
    }
}

public String getFileName(Uri uri, Context context) {
    if (uri == null) return null;
    if (uri.getScheme() == null) return null;
    Logger.d(">>> uri path:" + uri.getPath());
    Logger.d(">>> uri string:" + uri.toString());
    String path;
    if (uri.getScheme().equals("content")) {
        //Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA}, null, null, null);
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor == null) {
            Logger.e("!!! cursor is null");
            return null;
        }
        if (cursor.getCount() >= 0) {
            Logger.d("... the numbers of rows:" + cursor.getCount()
                    + "and the numbers of columns:" + cursor.getColumnCount());
            if (cursor.isBeforeFirst()) {
                while (cursor.moveToNext()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i<cursor.getColumnCount(); i++) {
                        stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
                        stringBuilder.append("\n");
                    }
                    Logger.d(stringBuilder.toString());
                }
            } else {
                cursor.moveToFirst();
                do {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i<cursor.getColumnCount(); i++) {
                        stringBuilder.append("... iterating cursor.getString(" + i +"(" + cursor.getColumnName(i) + ")):" + cursor.getString(i));
                        stringBuilder.append("\n");
                    }
                    Logger.d(stringBuilder.toString());
                } while (cursor.moveToNext());
            }
            cursor.moveToFirst();
            path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
            cursor.close();
            Logger.d("... content scheme:" + uri.getScheme() + "  and return:" + path);
            return path;
        } else {
            path = uri.getLastPathSegment();
            Logger.d("... content scheme:" + uri.getScheme()
                    + " but the numbers of rows in the cursor is < 0:" + cursor.getCount()
                    + "  and return:" + path);
            return path;
        }
    } else {
        path = uri.getLastPathSegment();
        Logger.d("... not content scheme:" + uri.getScheme() + "  and return:" + path);
        return path;
    }
}

}

about my FileHelper:

public class FileHelper {
private static final String DEFAULT_DIR_NAME = "AmoFromTaiwan";
private static final int DEFAULT_BUFFER_SIZE = 1024;
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private static final int EOF = -1;
private static FileHelper INSTANCE = new FileHelper();

public static FileHelper getInstance() {
    return INSTANCE;
}

private boolean isExternalStorageWritable(Context context) {
    /*
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state);
    */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            Logger.e("!!! checkSelfPermission() not granted");
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        return true;
    }
}

private boolean isExternalStorageReadable(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            Logger.e("!!! checkSelfPermission() not granted");
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        return true;
    }
}

@SuppressLint("SimpleDateFormat")
private String generateFileNameBasedOnTimeStamp() {
    return new SimpleDateFormat("yyyyMMdd_hhmmss").format(new Date()) + ".jpeg";
}

public File createExternalFile(String dir_name, String file_name, Context context) {
    String dir_path;
    String file_path;
    File dir ;
    File file;
    if (!isExternalStorageWritable(context)) {
        Logger.e("!!! external storage not writable");
        return null;
    }
    if (dir_name == null) {
        dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
    } else {
        dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
    }
    Logger.d("... going to access an external dir:" + dir_path);
    dir = new File(dir_path);
    if (!dir.exists()) {
        Logger.d("... going to mkdirs:" + dir_path);
        if (!dir.mkdirs()) {
            Logger.e("!!! failed to mkdirs");
            return null;
        }
    }
    if (file_name == null) {
        file_path = dir_path + File.separator + generateFileNameBasedOnTimeStamp();
    } else {
        file_path = dir_path + File.separator + file_name;
    }
    Logger.d("... going to return an external dir:" + file_path);
    file = new File(file_path);
    if (file.exists()) {
        Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
        if (!file.delete()) {
            Logger.e("!!! failed to delete file");
            return null;
        }
    }
    return file;
}

public File createInternalFile(String dir_name, String file_name, Context context) {
    String dir_path;
    String file_path;
    File dir ;
    File file;
    if (dir_name == null) {
        dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
    } else {
        dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
    }
    dir_path = dir.getAbsolutePath();
    Logger.d("... going to access an internal dir:" + dir_path);
    if (!dir.exists()) {
        Logger.d("... going to mkdirs:" + dir_path);
        if (!dir.mkdirs()) {
            Logger.e("!!! mkdirs failed");
            return null;
        }
    }
    if (file_name == null) {
        file = new File(dir, generateFileNameBasedOnTimeStamp());
    } else {
        file = new File(dir, file_name);
    }
    file_path = file.getAbsolutePath();
    Logger.d("... going to return an internal dir:" + file_path);
    if (file.exists()) {
        Logger.d("... before creating to delete an external dir:" + file.getAbsolutePath());
        if (!file.delete()) {
            Logger.e("!!! failed to delete file");
            return null;
        }
    }
    return file;
}

public File getExternalFile(String dir_name, String file_name, Context context) {
    String dir_path;
    String file_path;
    File file;
    if (!isExternalStorageWritable(context)) {
        Logger.e("!!! external storage not writable");
        return null;
    }
    if (dir_name == null) {
        dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + DEFAULT_DIR_NAME;
    } else {
        dir_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + dir_name;
    }
    if (file_name == null) {
        file_path = dir_path;
    } else {
        file_path = dir_path + File.separator + file_name;
    }
    Logger.d("... going to return an external file:" + file_path);
    file = new File(file_path);
    if (file.exists()) {
        Logger.d("... file exists:" + file.getAbsolutePath());
    } else {
        Logger.e("!!! file does't exist:" + file.getAbsolutePath());
    }
    return file;
}

public File getInternalFile(String dir_name, String file_name, Context context) {
    String file_path;
    File dir ;
    File file;
    if (dir_name == null) {
        dir = new ContextWrapper(context).getDir(DEFAULT_DIR_NAME, Context.MODE_PRIVATE);
    } else {
        dir = new ContextWrapper(context).getDir(dir_name, Context.MODE_PRIVATE);
    }
    if (file_name == null) {
        file = new File(dir.getAbsolutePath());
    } else {
        file = new File(dir, file_name);
    }
    file_path = file.getAbsolutePath();
    Logger.d("... going to return an internal dir:" + file_path);
    if (file.exists()) {
        Logger.d("... file exists:" + file.getAbsolutePath());
    } else {
        Logger.e("!!! file does't exist:" + file.getAbsolutePath());
    }
    return file;
}

private byte[] readBytesFromFile(File file) {
    Logger.d(">>> path:" + file.getAbsolutePath());
    FileInputStream fis;
    long file_length;
    byte[] buffer;
    int offset = 0;
    int next = 0;
    if (!file.exists()) {
        Logger.e("!!! file doesn't exists");
        return null;
    }
    if (file.length() > Integer.MAX_VALUE) {
        Logger.e("!!! file length is out of max of int");
        return null;
    } else {
        file_length = file.length();
    }
    try {
        fis = new FileInputStream(file);
        //buffer = new byte[(int) file_length];
        buffer = new byte[(int) file.length()];
        long time_start = System.currentTimeMillis();
        while (true) {
            Logger.d("... now next:" + next + " and offset:" + offset);
            if (System.currentTimeMillis() - time_start > 1000) {
                Logger.e("!!! left due to time out");
                break;
            }
            next = fis.read(buffer, offset, (buffer.length-offset));
            if (next < 0 || offset >= buffer.length) {
                Logger.d("... completed to read");
                break;
            }
            offset += next;
        }
        //if (offset < buffer.length) {
        if (offset < (int) file_length) {
            Logger.e("!!! not complete to read");
            return null;
        }
        fis.close();
        return buffer;
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return null;
    }
}

public byte[] readBytesFromFile(File file, boolean is_fis_fos_only) {
    if (file == null) return null;
    if (is_fis_fos_only) {
        return readBytesFromFile(file);
    }
    Logger.d(">>> path:" + file.getAbsolutePath());
    FileInputStream fis;
    BufferedInputStream bis;
    ByteArrayOutputStream bos;
    byte[] buf = new byte[(int) file.length()];
    int num_read;
    if (!file.exists()) {
        Logger.e("!!! file doesn't exists");
        return null;
    }
    try {
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        bos = new ByteArrayOutputStream();
        long time_start = System.currentTimeMillis();
        while (true) {
            if (System.currentTimeMillis() - time_start > 1000) {
                Logger.e("!!! left due to time out");
                break;
            }
            num_read = bis.read(buf, 0, buf.length); //1024 bytes per call
            if (num_read < 0) break;
            bos.write(buf, 0, num_read);
        }
        buf = bos.toByteArray();
        fis.close();
        bis.close();
        bos.close();
        return buf;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Logger.e("!!! FileNotFoundException");
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return null;
    }
}

/**
 * streams (InputStream and OutputStream) transfer binary data
 * if to write a string to a stream, must first convert it to bytes, or in other words encode it
 */
public boolean writeStringToFile(File file, String string, Charset charset) {
    if (file == null) return false;
    if (string == null) return false;
    return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}

public boolean writeBytesToFile(File file, byte[] data) {
    if (file == null) return false;
    if (data == null) return false;
    FileOutputStream fos;
    BufferedOutputStream bos;
    try {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data, 0, data.length);
        bos.flush();
        bos.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return false;
    }
    return true;
}

/**
 * io blocks until some input/output is available.
 */
public boolean copy(File source, File destination) {
    if (source == null || destination == null) return false;
    Logger.d(">>> source:" + source.getAbsolutePath() + ", destination:" + destination.getAbsolutePath());
    try {
        FileInputStream fis = new FileInputStream(source);
        FileOutputStream fos = new FileOutputStream(destination);
        byte[] buffer = new byte[(int) source.length()];
        int len;
        while (EOF != (len = fis.read(buffer))) {
            fos.write(buffer, 0, len);
        }
        if (true) { //debug
            byte[] copies = readBytesFromFile(destination);
            if (copies != null) {
                int copy_len = copies.length;
                Logger.d("... stream read and write done for " + copy_len + " bytes");
            }
        }
        return destination.length() != 0;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

public void list(final String path, final String end, final List<File> files) {
    Logger.d(">>> path:" + path + ", end:" + end);
    File file = new File(path);
    if (file.isDirectory()) {
        for (File child : file.listFiles()){
            list(child.getAbsolutePath(), end, files);
        }
    } else if (file.isFile()) {
        if (end.equals("")) {
            files.add(file);
        } else {
            if (file.getName().endsWith(end)) files.add(file);
        }
    }
}

public String[] splitFileName(File file, String split) {
    String path;
    String ext;
    int lastIndexOfSplit = file.getAbsolutePath().lastIndexOf(split);
    if (lastIndexOfSplit < 0) {
        path = file.getAbsolutePath();
        ext = "";
    } else {
        path = file.getAbsolutePath().substring(0, lastIndexOfSplit);
        ext = file.getAbsolutePath().substring(lastIndexOfSplit);
    }
    return new String[] {path, ext};
}

public File rename(File old_file, String new_name) {
    if (old_file == null || new_name == null) return null;
    Logger.d(">>> old file path:" + old_file.getAbsolutePath() + ", new file name:" + new_name);
    File new_file = new File(old_file, new_name);
    if (!old_file.equals(new_file)) {
        if (new_file.exists()) { //if find out previous file/dir at new path name exists
            if (new_file.delete()) {
                Logger.d("... succeeded to delete previous file at new abstract path name:" + new_file.getAbsolutePath());
            } else {
                Logger.e("!!! failed to delete previous file at new abstract path name");
                return null;
            }
        }
        if (old_file.renameTo(new_file)) {
            Logger.d("... succeeded to rename old file to new abstract path name:" + new_file.getAbsolutePath());
        } else {
            Logger.e("!!! failed to rename old file to new abstract path name");
        }
    } else {
        Logger.d("... new and old file have the equal abstract path name:" + new_file.getAbsolutePath());
    }
    return new_file;
}

public boolean remove(final String path, final String end) {
    Logger.d(">>> path:" + path + ", end:" + end);
    File file = new File(path);
    boolean result = false;
    if (file.isDirectory()) {
        for (File child : file.listFiles()){
            result = remove(child.getAbsolutePath(), end);
        }
    } else if (file.isFile()) {
        if (end.equals("")) {
            result = file.delete();
        } else {
            if (file.getName().endsWith(end)) result = file.delete();
        }
    } else {
        Logger.e("!!! child is not file or directory");
    }
    return result;
}

@TargetApi(Build.VERSION_CODES.O)
public byte[] readNIOBytesFromFile(String path) throws IOException {
    Logger.d(">>> path:" + path);
    if (!Files.exists(Paths.get(path), LinkOption.NOFOLLOW_LINKS)) {
        Logger.e("!!! file doesn't exists");
        return null;
    } else {
        return Files.readAllBytes(Paths.get(path));
    }
}

@TargetApi(Build.VERSION_CODES.O)
public File writeNIOBytesToFile(String dir, String name, byte[] data) {
    Logger.d(">>> dir:" + dir + ", name:" + name);
    Path path_dir;
    Path path_file;
    try {
        if (!Files.exists(Paths.get(dir), LinkOption.NOFOLLOW_LINKS)) {
            Logger.d("... make a dir");
            path_dir = Files.createDirectories(Paths.get(dir));
            if (path_dir == null) {
                Logger.e("!!! failed to make a dir");
                return null;
            }
        }
        path_file = Files.write(Paths.get(name), data);
        return path_file.toFile();
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return null;
    }
}

@TargetApi(Build.VERSION_CODES.O)
public void listNIO(final String dir, final String end, final List<File> files) throws IOException {
    Logger.d(">>> dir:" + dir + ", end:" + end);
    Files.walkFileTree(Paths.get(dir), new FileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            Logger.d("... file:" + dir.getFileName());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            Logger.d("... file:" + file.getFileName());
            if (end.equals("")) {
                files.add(file.toFile());
            } else {
                if (file.endsWith(end)) files.add(file.toFile());
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            Logger.d("... file:" + file.getFileName());
            if (end.equals("")) {
                files.add(file.toFile());
            } else {
                if (file.endsWith(end)) files.add(file.toFile());
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
            Logger.d("... file:" + dir.getFileName());
            return FileVisitResult.CONTINUE;
        }
    });
}

/**
 * recursion
 */
private int factorial (int x) {
    if (x > 1) return (x*(factorial(x-1)));
    else if (x == 1) return x;
    else return 0;
}

}

How to copy to clipboard in Vim?

This answer is specific to MAC users.

The default VIM available with MAC does not come with clipboard option enabled. You need that option to access the system clipboard.

To check if your vim has that option enabled use the below command

vim --version

In the result, you should have +clipboard. If it is -clipboard, then your VIM does NOT have the option to access the system clipboard.

You need to MAKE and install your VIM with the option you need. Following are the commands.

# Create the directories you need
$ sudo mkdir -p /opt/local/bin
# Download, compile, and install the latest Vim
$ cd ~
$ git clone https://github.com/vim/vim.git
$ cd vim
$ ./configure --prefix=/opt/local
$ make
$ sudo make install
# Add the binary to your path, ahead of /usr/bin
$ echo 'PATH=/opt/local/bin:$PATH' >> ~/.bash_profile
# Reload bash_profile so the changes take effect in this window
$ source ~/.bash_profile"

The above will install the latest VIM with the option +clipboard enabled.

Now you need to set the system clipboard. Append the following line to ~/.vimrc

set clipboard=unnamed

Now you can yank text to system clipboard. Below steps explains how to yank.

  1. In vim command mode press v, this will switch you to VISUAL mode.
  2. Move the cursor around to select the text or lines you need to copy.
  3. Press y, this will copy the selected text to clipboard.
  4. Go to any external application and CMD + v to paste.

I use MACBook Pro with macOS Mojave and the above works in it.

connecting to phpMyAdmin database with PHP/MySQL

$db = new mysqli('Server_Name', 'Name', 'password', 'database_name');

JQuery get all elements by class name

Alternative solution (you can replace createElement with a your own element)

var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);

How to call window.alert("message"); from C#?

MessageBox like others said, or RegisterClientScriptBlock if you want something more arbitrary, but your use case is extremely dubious. Merely displaying exceptions is not something you want to do in production code - you don't want to expose that detail publicly and you do want to record it with proper logging privately.

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

How to add multiple files to Git at the same time

step1.

git init

step2.

a) for all files

git add -a

b) only specific folder

git add <folder1> <folder2> <etc.>

step3.

git commit -m "Your message about the commit"

step4.

enter image description here

git remote add origin https://github.com/yourUsername/yourRepository.git

step5.

git push -u origin master
git push origin master

if you are face this error than

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/harishkumawat2610/Qt5-with-C-plus-plus.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Use this command

git push --force origin master

How to resolve Unneccessary Stubbing exception

Looking at a part of your stack trace it looks like you are stubbing the dao.doSearch() elsewhere. More like repeatedly creating the stubs of the same method.

Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at service.Test.testDoSearch(Test.java:72)
Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class.

Consider the below Test Class for example:

@RunWith(MockitoJUnitRunner.class)
public class SomeTest {
    @Mock
    Service1 svc1Mock1;

    @Mock
    Service2 svc2Mock2;

    @InjectMock
    TestClass class;

    //Assume you have many dependencies and you want to set up all the stubs 
    //in one place assuming that all your tests need these stubs.

    //I know that any initialization code for the test can/should be in a 
    //@Before method. Lets assume there is another method just to create 
    //your stubs.

    public void setUpRequiredStubs() {
        when(svc1Mock1.someMethod(any(), any())).thenReturn(something));
        when(svc2Mock2.someOtherMethod(any())).thenReturn(somethingElse);
    }

    @Test
    public void methodUnderTest_StateUnderTest_ExpectedBehavior() {
        // You forget that you defined the stub for svcMock1.someMethod or 
        //thought you could redefine it. Well you cannot. That's going to be 
        //a problem and would throw your UnnecessaryStubbingException.
       when(svc1Mock1.someMethod(any(),any())).thenReturn(anyThing);//ERROR!
       setUpRequiredStubs();
    }
}

I would rather considering refactoring your tests to stub where necessary.

How can I change property names when serializing with Json.net?

There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject] or [JsonProperty].

There are predefined naming strategies like CamelCaseNamingStrategy, but you can implement your own ones.

The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I have same problem and i found solution which is given below with full datepicker using simple HTML,Javascript and CSS. In this code i prepare formate like dd/mm/yyyy but you can work any.

HTML Code:

    <body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt"  onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>

CSS Code:

#dt{text-indent: -500px;height:25px; width:200px;}

Javascript Code :

function mydate()
{
  //alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
 d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}

Output:

enter image description here

How to find the Number of CPU Cores via .NET/C#?

There are several different pieces of information relating to processors that you could get:

  1. Number of physical processors
  2. Number of cores
  3. Number of logical processors.

These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):

Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.

Physical Processors:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}

Cores:

int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
    coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);

Logical Processors:

Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);

OR

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}

Processors excluded from Windows:

You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:

static void Main(string[] args)
{
    int deviceCount = 0;
    IntPtr deviceList = IntPtr.Zero;
    // GUID for processor classid
    Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");

    try
    {
        // get a list of all processor devices
        deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
        // attempt to process each item in the list
        for (int deviceNumber = 0; ; deviceNumber++)
        {
            SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
            deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);

            // attempt to read the device info from the list, if this fails, we're at the end of the list
            if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
            {
                deviceCount = deviceNumber;
                break;
            }
        }
    }
    finally
    {
        if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
    }
    Console.WriteLine("Number of cores: {0}", deviceCount);
}

[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
    [MarshalAs(UnmanagedType.LPStr)]String enumerator,
    IntPtr hwndParent,
    Int32 Flags);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
    Int32 MemberIndex,
    ref SP_DEVINFO_DATA DeviceInterfaceData);

[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
    public int cbSize;
    public Guid ClassGuid;
    public uint DevInst;
    public IntPtr Reserved;
}

private enum DIGCF
{
    DEFAULT = 0x1,
    PRESENT = 0x2,
    ALLCLASSES = 0x4,
    PROFILE = 0x8,
    DEVICEINTERFACE = 0x10,
}

How to disable Django's CSRF validation?

If you want disable it in Global, you can write a custom middleware, like this

from django.utils.deprecation import MiddlewareMixin

class DisableCsrfCheck(MiddlewareMixin):

    def process_request(self, req):
        attr = '_dont_enforce_csrf_checks'
        if not getattr(req, attr, False):
            setattr(req, attr, True)

then add this class youappname.middlewarefilename.DisableCsrfCheck to MIDDLEWARE_CLASSES lists, before django.middleware.csrf.CsrfViewMiddleware