Programs & Examples On #Nstoolbaritem

failed to open stream: No such file or directory in

It's because you have included a leading / in your file path. The / makes it start at the top of your filesystem. Note: filesystem path, not Web site path (you're not accessing it over HTTP). You can use a relative path with include_once (one that doesn't start with a leading /).

You can change it to this:

include_once 'headerSite.php';

That will look first in the same directory as the file that's including it (i.e. C:\xampp\htdocs\PoliticalForum\ in your example.

Rank function in MySQL

If you want to rank just one person you can do the following:

SELECT COUNT(Age) + 1
 FROM PERSON
WHERE(Age < age_to_rank)

This ranking corresponds to the oracle RANK function (Where if you have people with the same age they get the same rank, and the ranking after that is non-consecutive).

It's a little bit faster than using one of the above solutions in a subquery and selecting from that to get the ranking of one person.

This can be used to rank everyone but it's slower than the above solutions.

SELECT
  Age AS age_var,
(
  SELECT COUNT(Age) + 1
  FROM Person
  WHERE (Age < age_var)
 ) AS rank
 FROM Person

how do you insert null values into sql server

INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

Highlight text similar to grep, but don't filter out text

Maybe this is an XY problem, and what you are really trying to do is to highlight occurrences of words as they appear in your shell. If so, you may be able to use your terminal emulator for this. For instance, in Konsole, start Find (ctrl+shift+F) and type your word. The word will then be highlighted whenever it occurs in new or existing output until you cancel the function.

getting integer values from textfield

As You're getting values from textfield as jTextField3.getText();.

As it is a textField it will return you string format as its format says:

String getText()

      Returns the text contained in this TextComponent.

So, convert your String to Integer as:

int jml = Integer.parseInt(jTextField3.getText());

instead of directly setting

   int jml = jTextField3.getText();

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

None of the above worked for me (tomcat 7.0.62)... As Sensei_Shoh notes see the class above the message and add this to logging.properties. My logs were:

Jan 18, 2016 8:44:21 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.

so I added

org.apache.catalina.startup.TldConfig.level = FINE

in conf/logging.properties

After that I got so many "offending" files that I did not bother skipping them (and also reverted to normal logging...)

How to get random value out of an array?

A simple way to getting Randdom value form Array.

$color_array =["red","green","blue","light_orange"];
$color_array[rand(0,3)

now every time you will get different colors from Array.

Convert Uri to String and String to Uri

You can use Drawable instead of Uri.

   ImageView iv=(ImageView)findViewById(R.id.imageView1);
   String pathName = "/external/images/media/470939"; 
   Drawable image = Drawable.createFromPath(pathName);
   iv.setImageDrawable(image);

This would work.

Add an object to an Array of a custom class

If you want to create a garage and fill it up with new cars that can be accessed later, use this code:

for (int i = 0; i < garage.length; i++)
     garage[i] = new Car("argument");

Also, the cars are later accessed using:

garage[0];
garage[1];
garage[2];
etc.

Rails how to run rake task

Rake::Task['reklamer:orville'].invoke

or

Rake::Task['reklamer:orville'].invoke(args)

What is the relative performance difference of if/else versus switch statement in Java?

I remember reading that there are 2 kinds of Switch statements in Java bytecode. (I think it was in 'Java Performance Tuning' One is a very fast implementation which uses the switch statement's integer values to know the offset of the code to be executed. This would require all integers to be consecutive and in a well-defined range. I'm guessing that using all the values of an Enum would fall in that category too.

I agree with many other posters though... it may be premature to worry about this, unless this is very very hot code.

How to run only one task in ansible playbook?

There is a way, although not very elegant:

  1. ansible-playbook roles/hadoop_primary/tasks/hadoop_master.yml --step --start-at-task='start hadoop jobtracker services'
  2. You will get a prompt: Perform task: start hadoop jobtracker services (y/n/c)
  3. Answer y
  4. You will get a next prompt, press Ctrl-C

HttpRequest maximum allowable size in tomcat?

You have to modify two possible limits:

In conf\server.xml

<Connector port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
                maxPostSize="67589953" />

In webapps\manager\WEB-INF\web.xml

<multipart-config>
  <!-- 52MB max -->
  <max-file-size>52428800</max-file-size>
  <max-request-size>52428800</max-request-size>
  <file-size-threshold>0</file-size-threshold>
</multipart-config>

WCF service startup error "This collection already contains an address with scheme http"

Summary,

Code solution: Here

Configuration solutions: Here

With the help of Mike Chaliy, I found some solutions on how to do this through code. Because this issue is going to affect pretty much all projects we deploy to a live environment I held out for a purely configuration solution. I eventually found one which details how to do it in .net 3.0 and .net 3.5.

Taken from the site, below is an example of how to alter your applications web config:

<system.serviceModel>
    <serviceHostingEnvironment>
        <baseAddressPrefixFilters>
            <add prefix="net.tcp://payroll.myorg.com:8000"/>
            <add prefix="http://shipping.myorg.com:9000"/>
        </baseAddressPrefixFilters>
    </serviceHostingEnvironment>
</system.serviceModel>

In the above example, net.tcp://payroll.myorg.com:8000 and http://shipping.myorg.com:9000 are the only base addresses, for their respective schemes, which will be allowed to be passed through. The baseAddressPrefixFilter does not support any wildcards .

The baseAddresses supplied by IIS may have addresses bound to other schemes not present in baseAddressPrefixFilter list. These addresses will not be filtered out.

Dns solution (untested): I think that if you created a new dns entry specific to your web application, added a new web site, and gave it a single host header matching the dns entry, you would mitigate this issue altogether, and would not have to write custom code or add prefixes to your web.config file.

How to create/make rounded corner buttons in WPF?

You can try this...........

 <Border BorderBrush="Black" Name="MyBorder"  
            Height="78" 
            Background="Red" 
            Width="74" 
            CornerRadius="3">
        <Button Width="{Binding MyBorder.Width}" 
                Height="{Binding MyBorder.Height}" 
                Content="Hi" Background="Red"/>
    </Border>

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Implement a loading indicator for a jQuery AJAX call

I solved the same problem following this example:

This example uses the jQuery JavaScript library.

First, create an Ajax icon using the AjaxLoad site.
Then add the following to your HTML :

<img src="/images/loading.gif" id="loading-indicator" style="display:none" />

And the following to your CSS file:

#loading-indicator {
  position: absolute;
  left: 10px;
  top: 10px;
}

Lastly, you need to hook into the Ajax events that jQuery provides; one event handler for when the Ajax request begins, and one for when it ends:

$(document).ajaxSend(function(event, request, settings) {
    $('#loading-indicator').show();
});

$(document).ajaxComplete(function(event, request, settings) {
    $('#loading-indicator').hide();
});

This solution is from the following link. How to display an animated icon during Ajax request processing

How to check if an integer is in a given range?

if(i <= 0 || i >=100)

It will work.

Check date between two other dates spring data jpa

I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

I finally could figure the issue out.

To get the Key Alias: I copied the keytool.exe and my keystore file into C:\Program Files\Java\jdk1.7.0_71\bin folder. Then from command prompt I wrote: keytool -list -v -keystore <name>.keystore It will also ask for keystore password then. Then it will show you the key alias and Certificate fingerprints and other info.

Then I again tried to Generate Signed Apk for the project, I provided keystore, keystore password, key alias and provided the same password. Then it asks for master password, I tried with the same and it failed. With the reset option I reset the master password here.

How to install and run phpize

Under Redhat Enterprise / CentOS, use yum to install the php-devel module:

yum install php-devel

For PHP 7, you need:

yum install php70-php-devel

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Stored procedures can be executed like below

 string cmd = Constants.StoredProcs.usp_AddRoles.ToString() + " @userId, @roleIdList";
                        int result = db.Database
                                       .ExecuteSqlCommand
                                       (
                                          cmd,
                                           new SqlParameter("@userId", userId),
                                           new SqlParameter("@roleIdList", roleId)
                                       );

RuntimeError: module compiled against API version a but this version of numpy is 9

I ran into the same issue tonight. It turned out to be a problem where I had multiple numpy packages installed. An older version was installed in /usr/lib/python2.7 and the correct version was installed in /usr/local/lib/python2.7.

Additionally, I had PYTHONPATH=/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages. PYTHONPATH was finding the older version of numpy before the correct version, so when inside the Python interpreter, it would import the older version of numpy.

One thing which helped was opening a python session an executing the following code:

import numpy as np 
print np.__version__ 
print np.__path__

That should tell you exactly which version Python is using, and where it's installed.

To fix the issue, I changed PYTHONPATH=/usr/local/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages. And I also setup a virtual Python environment using the Hitchiker's Guide to Python, specifically the section titled "Lower level: virtualenv" . I know I should have setup a virtual environment in the first place, but I was tired and being lazy. Oh well, lesson learned!

(Update)

Just in case the docs are moved again, here are the relevant bits on...

Creating a Python Virtual Environment

Install virtualenv via pip:

$ install virtualenv

Test the installation:

$ virtualenv --version

Optionally, et the environment variable VIRTUALENVWRAPPER_PYTHON to change the default version of python used by virtual environments, for example to use Python 3:

$ export VIRTUALENVWRAPPER_PYTHON=$(which python3)

Optionally, set the environment variable WORKON_HOME to change the default directory your Python virtual environments are created in, for example to use /opt/python_envs:

$ export WORKON_HOME=/opt/python_envs

Create a virtual environment for a project:

$ cd my_project_folder
$ virtualenv my_virtual_env_name

Activate the virtual environment, you just created. Assuming you also set WORKON_HOME=/opt/python_envs:

$ source $WORKON_HOME/my_virtual_env_name/bin/activate

Install whatever Python packages your project requires, using either of the following two methods.

Method 1 - Install using pip from command line:

$ pip install python_package_name1
$ pip install python_package_name2

Method 2 - Install using a requests.txt file:

$ echo "python_package_name1" >> requests.txt
$ echo "python_package_name2" >> requests.txt
$ pip install -r ./requests.txt

Optionally, but highly recommended, install virtualenvwrapper. It contains useful commands to make working with virtual Python environments easier:

$ pip install virtualenvwrapper
$ source /usr/local/bin/virtualenvwrapper.sh

On Windows, install virtualenvwrapper using:

$ pip install virtualenvwrapper-win

Basic usage of virtualenvwrapper Create a new virtual environment:

$ mkvirtualenv my_virtual_env_name

List all virtual environments:

$ lsvirtualenv

Activate a virtual environment:

$ workon my_virtual_env_name

Delete a virtual environment (caution! this is irreversible!):

$ rmvirtualenv my_virtual_env_name

I hope this help!

How to Implement Custom Table View Section Headers and Footers with Storyboard

If you need a Swift Implementation of this follow the directions on the accepted answer and then in you UITableViewController implement the following methods:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return tableView.dequeueReusableCell(withIdentifier: "CustomHeader")
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 75
}

cc1plus: error: unrecognized command line option "-std=c++11" with g++

you should try this

g++-4.4 -std=c++0x or g++-4.7 -std=c++0x

Attach IntelliJ IDEA debugger to a running Java process

Also I use Tomcat GUI app (in my case: C:\tomcat\bin\Tomcat9w.bin).

  • Go to Java tab:

    enter image description here

  • Set your Java properties, for example:

    Java virtual machine

    C:\Program Files\Java\jre-10.0.2\bin\server\jvm.dll

    Java virtual machine

    C:\tomcat\bin\bootstrap.jar;C:\tomcat\bin\tomcat-juli.jar

    Java Options:

    -Dcatalina.home=C:\tomcat

    -Dcatalina.base=C:\tomcat

    -Djava.io.tmpdir=C:\tomcat\temp

    -Djava.util.logging.config.file=C:\tomcat\conf\logging.properties

    -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000

    Java 9 options:

    --add-opens=java.base/java.lang=ALL-UNNAMED

    --add-opens=java.base/java.io=ALL-UNNAMED

    --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED

How do I keep two side-by-side divs the same height?

You can use Jquery's Equal Heights Plugin to accomplish, this plugins makes all the div of exact same height as other. If one of them grows and other will also grow.

Here a sample of implementation

Usage: $(object).equalHeights([minHeight], [maxHeight]);

Example 1: $(".cols").equalHeights(); 
           Sets all columns to the same height.

Example 2: $(".cols").equalHeights(400); 
           Sets all cols to at least 400px tall.

Example 3: $(".cols").equalHeights(100,300); 
           Cols are at least 100 but no more than 300 pixels tall. Elements with too much content will gain a scrollbar.

Here is the link

http://www.cssnewbie.com/equalheights-jquery-plugin/

Subprocess check_output returned non-zero exit status 1

For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32

My issue was the java version 1.7 installed.

Google Chrome: This setting is enforced by your administrator

In my case, the setting was HKEY_CURRENT_USER\Software\Policies\Google\Chrome

I deleted Chrome and everything is fine now.

What does it mean by command cd /d %~dp0 in Windows

Let's dissect it. There are three parts:

  1. cd -- This is change directory command.
  2. /d -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0. (%~d0 Changs active drive, cd %~p0 change the directory).
  3. %~dp0 -- This can be dissected further into three parts:
    1. %0 -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
    2. %~0 -- The ~ there strips double quotes (") around the expanded argument.
    3. %dp0 -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.

how to call a function from another function in Jquery

I assume you don't want to rebind the event, but call the handler.

You can use trigger() to trigger events:

$('#billing_state_id').trigger('change');

If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:

function someFunction() {
    //do stuff
}

$(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', someFunction);   
    $('#click_me').live('click', function() {
       //do something
       someFunction();
    });
  });

Also note that live() is deprecated, on() is the new hotness.

The import android.support cannot be resolved

andorid-support-v4.jar is an external jar file that you have to import into your project.

This is how you do it in Android Studio:

Go to File -> Project Structure enter image description here

Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency" enter image description here

Select the support library "support-v4 (com.android.support:support-v4:23.0.1)" enter image description here

Now to go your "build.gradle" file in your app and make sure the android support library has been added to your dependencies. Alternatively, you could've also just typed compile 'com.android.support:support-v4:23.0.1' directly into your dependencies{} instead of doing it through the GUI.

enter image description here

Rebuild your project and now everything should work. enter image description here

SQL alias for SELECT statement

Not sure exactly what you try to denote with that syntax, but in almost all RDBMS-es you can use a subquery in the FROM clause (sometimes called an "inline-view"):

SELECT..
FROM (
     SELECT ...
     FROM ...
     ) my_select
WHERE ...

In advanced "enterprise" RDBMS-es (like oracle, SQL Server, postgresql) you can use common table expressions which allows you to refer to a query by name and reuse it even multiple times:

-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;

(example from http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx)

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

UITableView example for Swift

For completeness sake, and for those that do not wish to use the Interface Builder, here's a way of creating the same table as in Suragch's answer entirely programatically - albeit with a different size and position.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    var tableView: UITableView = UITableView()
    let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    let cellReuseIdentifier = "cell"

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.frame = CGRectMake(0, 50, 320, 200)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return animals.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

        cell.textLabel?.text = animals[indexPath.row]

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }

}

Make sure you have remembered to import UIKit.

JFrame in full screen Java

JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize()));

This just makes the frame the size of the screen

Javascript: Setting location.href versus location

Just to clarify, you can't do location.split('#'), location is an object, not a string. But you can do location.href.split('#'); because location.href is a string.

apache ProxyPass: how to preserve original IP address

If you have the capability to do so, I would recommend using either mod-jk or mod-proxy-ajp to pass requests from Apache to JBoss. The AJP protocol is much more efficient compared to using HTTP proxy requests and as a benefit, JBoss will see the request as coming from the original client and not Apache.

How do I create JavaScript array (JSON format) dynamically?

What I do is something just a little bit different from @Chase answer:

var employees = {};

// ...and then:
employees.accounting = new Array();

for (var i = 0; i < someArray.length; i++) {
    var temp_item = someArray[i];

    // Maybe, here make something like:
    // temp_item.name = 'some value'

    employees.accounting.push({
        "firstName" : temp_item.firstName,
        "lastName"  : temp_item.lastName,
        "age"       : temp_item.age
    });
}

And that work form me!

I hope it could be useful for some body else!

Is it bad practice to use break to exit a loop in Java?

There are a number of common situations for which break is the most natural way to express the algorithm. They are called "loop-and-a-half" constructs; the paradigm example is

while (true) {
    item = stream.next();
    if (item == EOF)
        break;
    process(item);
}

If you can't use break for this you have to repeat yourself instead:

item = stream.next();
while (item != EOF) {
    process(item);
    item = stream.next();
}

It is generally agreed that this is worse.

Similarly, for continue, there is a common pattern that looks like this:

for (item in list) {
    if (ignore_p(item))
        continue;
    if (trivial_p(item)) {
        process_trivial(item);
        continue;
    }
    process_complicated(item);
}

This is often more readable than the alternative with chained else if, particularly when process_complicated is more than just one function call.

Further reading: Loop Exits and Structured Programming: Reopening the Debate

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

Why dividing two integers doesn't get a float?

This is because of implicit conversion. The variables b, c, d are of float type. But the / operator sees two integers it has to divide and hence returns an integer in the result which gets implicitly converted to a float by the addition of a decimal point. If you want float divisions, try making the two operands to the / floats. Like follows.

#include <stdio.h>

int main() {
    int a;
    float b, c, d;
    a = 750;
    b = a / 350.0f;
    c = 750;
    d = c / 350;
    printf("%.2f %.2f", b, d);
    // output: 2.14 2.14
    return 0;
}

Interfaces with static fields in java for sharing 'constants'

According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM

By default, all the methods in interface is abstract even tough you didn't mention it explicitly.

Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.

javascript remove "disabled" attribute from html input

Why not just remove that attribute?

  1. vanilla JS: elem.removeAttribute('disabled')
  2. jQuery: elem.removeAttr('disabled')

How to concatenate variables into SQL strings

You can accomplish this (if I understand what you are trying to do) using dynamic SQL.

The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.

So you can use something like this approach:

SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue 
    + ' AS fld1 FROM tbl' + @KeyValue

EXEC (@stmt)

First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:

'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'

At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE (or EXEC for short).

The old-school sp_executesql procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.


FOLLOWUP

EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.

Consider what would happen if @KeyValue contained the string:

'1 AS foo; DROP TABLE students; -- '

The string we would produce as a SQL statement would be:

'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'

When we EXECUTE that string as a SQL statement:

INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...

And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)

One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'. If an illegal character is found, then reject the value, and exit without executing any SQL.

Mac install and open mysql using terminal

  1. install homebrew via terminal

  2. brew install mysql

CSS: background-color only inside the margin

I needed something similar, and came up with using the :before (or :after) pseudoclasses:

#mydiv {
   background-color: #fbb;
   margin-top: 100px;
   position: relative;
}
#mydiv:before {
   content: "";
   background-color: #bfb;
   top: -100px;
   height: 100px;
   width: 100%;
   position: absolute;
}

JSFiddle

make sounds (beep) with c++

The ASCII bell character might be what you are looking for. Number 7 in this table.

Unable to Cast from Parent Class to Child Class

The instance that your base class reference is referring to is not an instance of your child class. There's nothing wrong.

More specifically:

Base derivedInstance = new Derived();
Base baseInstance = new Base();

Derived good = (Derived)derivedInstance; // OK
Derived fail = (Derived)baseInstance; // Throws InvalidCastException

For the cast to be successful, the instance that you're downcasting must be an instance of the class that you're downcasting to (or at least, the class you're downcasting to must be within the instance's class hierarchy), otherwise the cast will fail.

AngularJS is rendering <br> as text not as a newline

You can use \n to concatenate words and then apply this style to container div.

style="white-space: pre;"

More info can be found at https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

_x000D_
_x000D_
<p style="white-space: pre;">_x000D_
    This is normal text._x000D_
</p>_x000D_
<p style="white-space: pre;">_x000D_
    This _x000D_
  text _x000D_
  contains _x000D_
  new lines._x000D_
</p>
_x000D_
_x000D_
_x000D_

How to convert image file data in a byte array to a Bitmap?

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.

What is the yield keyword used for in C#?

A list or array implementation loads all of the items immediately whereas the yield implementation provides a deferred execution solution.

In practice, it is often desirable to perform the minimum amount of work as needed in order to reduce the resource consumption of an application.

For example, we may have an application that process millions of records from a database. The following benefits can be achieved when we use IEnumerable in a deferred execution pull-based model:

  • Scalability, reliability and predictability are likely to improve since the number of records does not significantly affect the application’s resource requirements.
  • Performance and responsiveness are likely to improve since processing can start immediately instead of waiting for the entire collection to be loaded first.
  • Recoverability and utilisation are likely to improve since the application can be stopped, started, interrupted or fail. Only the items in progress will be lost compared to pre-fetching all of the data where only using a portion of the results was actually used.
  • Continuous processing is possible in environments where constant workload streams are added.

Here is a comparison between build a collection first such as a list compared to using yield.

List Example

    public class ContactListStore : IStore<ContactModel>
    {
        public IEnumerable<ContactModel> GetEnumerator()
        {
            var contacts = new List<ContactModel>();
            Console.WriteLine("ContactListStore: Creating contact 1");
            contacts.Add(new ContactModel() { FirstName = "Bob", LastName = "Blue" });
            Console.WriteLine("ContactListStore: Creating contact 2");
            contacts.Add(new ContactModel() { FirstName = "Jim", LastName = "Green" });
            Console.WriteLine("ContactListStore: Creating contact 3");
            contacts.Add(new ContactModel() { FirstName = "Susan", LastName = "Orange" });
            return contacts;
        }
    }

    static void Main(string[] args)
    {
        var store = new ContactListStore();
        var contacts = store.GetEnumerator();

        Console.WriteLine("Ready to iterate through the collection.");
        Console.ReadLine();
    }

Console Output
ContactListStore: Creating contact 1
ContactListStore: Creating contact 2
ContactListStore: Creating contact 3
Ready to iterate through the collection.

Note: The entire collection was loaded into memory without even asking for a single item in the list

Yield Example

public class ContactYieldStore : IStore<ContactModel>
{
    public IEnumerable<ContactModel> GetEnumerator()
    {
        Console.WriteLine("ContactYieldStore: Creating contact 1");
        yield return new ContactModel() { FirstName = "Bob", LastName = "Blue" };
        Console.WriteLine("ContactYieldStore: Creating contact 2");
        yield return new ContactModel() { FirstName = "Jim", LastName = "Green" };
        Console.WriteLine("ContactYieldStore: Creating contact 3");
        yield return new ContactModel() { FirstName = "Susan", LastName = "Orange" };
    }
}

static void Main(string[] args)
{
    var store = new ContactYieldStore();
    var contacts = store.GetEnumerator();

    Console.WriteLine("Ready to iterate through the collection.");
    Console.ReadLine();
}

Console Output
Ready to iterate through the collection.

Note: The collection wasn't executed at all. This is due to the "deferred execution" nature of IEnumerable. Constructing an item will only occur when it is really required.

Let's call the collection again and obverse the behaviour when we fetch the first contact in the collection.

static void Main(string[] args)
{
    var store = new ContactYieldStore();
    var contacts = store.GetEnumerator();
    Console.WriteLine("Ready to iterate through the collection");
    Console.WriteLine("Hello {0}", contacts.First().FirstName);
    Console.ReadLine();
}

Console Output
Ready to iterate through the collection
ContactYieldStore: Creating contact 1
Hello Bob

Nice! Only the first contact was constructed when the client "pulled" the item out of the collection.

HTML entity for the middle dot

The semantically correct character is the Interpunct, also known as middle dot, as HTML entity

&middot;

Example

Home · Photos · About


You could also use the bullet point character, as HTML entity

&bull;

Example

Home • Photos • About

How to get hex color value rather than RGB value?

Since the question was using JQuery, here’s a JQuery plugin based on Daniel Elliott’s code:

$.fn.cssAsHex = function(colorProp) {

    var hexDigits = '0123456789abcdef';

    function hex(x) {
        return isNaN(x) ? '00' : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
    };

    // Convert RGB color to Hex format
    function rgb2hex(rgb) {
        var rgbRegex = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        return '#' + hex(rgbRegex[1]) + hex(rgbRegex[2]) + hex(rgbRegex[3]);
    };

    return rgb2hex(this.css(colorProp));
};

Use it like:

var hexBackgroundColor = $('#myElement').cssAsHex('background-color');

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

Bookmarking this URL should give you a full-screen compose window, without any distractions:

https://mail.google.com/mail/?view=cm&fs=1&tf=1

Additionally, if you want to be future-proof (see for instance how other URLs in this question stopped working) you can bookmark a link to:

mailto:

It will open your default email client and you probably already have Gmail configured for that purpose.

Difference between Subquery and Correlated Subquery

CORRELATED SUBQUERIES: Is evaluated for each row processed by the Main query. Execute the Inner query based on the value fetched by the Outer query. Continues till all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query

Ex:

SELECT empno,fname,sal,deptid FROM emp e WHERE sal=(SELECT AVG(sal) FROM emp WHERE deptid=e.deptid)

The Correlated subquery specifically computes the AVG(sal) for each department.

SUBQUERY: Runs first,executed once,returns values to be used by the MAIN Query. The OUTER Query is driven by the INNER QUERY

VBA using ubound on a multidimensional array

You need to deal with the optional Rank parameter of UBound.

Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1)  '? returns 4
Debug.Print UBound(arr, 2)  '? returns 3

More at: UBound Function (Visual Basic)

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

convert strtotime to date time format in php

Use date() function to get the desired date

<?php
// set default timezone
date_default_timezone_set('UTC');

//define date and time
$strtotime = 1307595105;

// output
echo date('d M Y H:i:s',$strtotime);

// more formats
echo date('c',$strtotime); // ISO 8601 format
echo date('r',$strtotime); // RFC 2822 format
?>

Recommended online tool for strtotime to date conversion:

http://freeonlinetools24.com/

Datatype for storing ip address in SQL Server

The following answer is based on answers by M. Turnhout and Jerry Birchler to this question but with the following improvements:

  • Replaced the use of undocumented functions (sys.fn_varbintohexsubstring, fn_varbintohexstr) with CONVERT() for binary styles
  • Replaced XML "hacks" ( CAST('' as xml).value('xs:hexBinary()) ) with CONVERT() for binary styles
  • Fixed bug in Jerry Birchler's implementation of fn_ConvertIpAddressToBinary (as pointed out by C.Plock)
  • Add minor syntax sugar

The code has been tested in SQL Server 2014 and SQL Server 2016 (see test cases at the end)

IPAddressVarbinaryToString

Converts 4 bytes values to IPV4 and 16 byte values to IPV6 string representations. Note that this function does not shorten addresses.

ALTER FUNCTION dbo.IPAddressVarbinaryToString
(
    @varbinaryValue VARBINARY( 16 )
)
RETURNS VARCHAR(39)
AS
BEGIN
    IF @varbinaryValue IS NULL
        RETURN NULL;
    ELSE IF DATALENGTH( @varbinaryValue ) = 4
        RETURN 
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 1, 1 ))) + '.' +
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 2, 1 ))) + '.' +
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 3, 1 ))) + '.' +
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 4, 1 )));
    ELSE IF DATALENGTH( @varbinaryValue ) = 16
        RETURN 
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  1, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  3, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  5, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  7, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  9, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 11, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 13, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 15, 2 ), 2 );

    RETURN 'Invalid';
END

Test Cases:

SELECT dbo.IPAddressVarbinaryToString(0x00000000000000000000000000000000) -- 0000:0000:0000:0000:0000:0000:0000:0000 (no address shortening)
SELECT dbo.IPAddressVarbinaryToString(0x00010002000300400500060070000089) -- 0001:0002:0003:0040:0500:0600:7000:0089
SELECT dbo.IPAddressVarbinaryToString(0xC0A80148) -- 255.168.1.72
SELECT dbo.IPAddressVarbinaryToString(0x7F000001) -- 127.0.0.1 (no address shortening)
SELECT dbo.IPAddressVarbinaryToString(NULL) -- NULL

IPAddressStringToVarbinary

Converts IPV4 and IPV6 string representations to 4 byte and 16 bytes binary values respectively. Note that this function is able to parse most (all of the commonly used) of shorthand address representations (e.g. 127...1 and 2001:db8::1319:370:7348). To force this function to always return 16 byte binary values uncomment leading 0s concatenation at the end of the function.

ALTER FUNCTION [dbo].[IPAddressStringToVarbinary]
(
    @IPAddress VARCHAR( 39 )
)
RETURNS VARBINARY(16) AS
BEGIN

IF @ipAddress IS NULL
    RETURN NULL;

DECLARE @bytes VARBINARY(16), @token VARCHAR(4),
    @vbytes VARBINARY(16) = 0x, @vbzone VARBINARY(2),
    @tIPAddress VARCHAR( 40 ),
    @colIndex TINYINT,
    @delim CHAR(1) = '.',
    @prevColIndex TINYINT = 0,
    @parts TINYINT = 0, @limit TINYINT = 4;

-- Get position if IPV4 delimiter
SET @colIndex = CHARINDEX( @delim, @ipAddress );

-- If not IPV4, then assume IPV6
IF @colIndex = 0
BEGIN
    SELECT @delim = ':', @limit = 8, @colIndex = CHARINDEX( @delim, @ipAddress );

    -- Get number of parts (delimiters)
    WHILE @colIndex > 0
        SELECT @parts += 1, @colIndex = CHARINDEX( @delim, @ipAddress, @colIndex + 1 );

    SET @colIndex = CHARINDEX( @delim, @ipAddress );

    IF @colIndex = 0
        RETURN NULL;
END

-- Add trailing delimiter (need new variable of larger size)
SET @tIPAddress = @IPAddress + @delim;

WHILE @colIndex > 0
BEGIN
    SET @token = SUBSTRING( @tIPAddress, @prevColIndex + 1, @Colindex - @prevColIndex - 1 );

    IF @delim = ':'
    BEGIN
        SELECT @vbzone = CONVERT( VARBINARY(2), RIGHT( '0000' + @token, 4 ), 2 ), @vbytes += @vbzone;

        -- Handles consecutive sections of zeros representation rule (i.e. ::)(https://en.wikipedia.org/wiki/IPv6#Address_representation)
        IF @token = ''
            WHILE @parts + 1 < @limit
                SELECT @vbytes += @vbzone, @parts += 1;
    END
    ELSE
    BEGIN
        SELECT @vbzone = CONVERT( VARBINARY(1), CONVERT( TINYINT, @token )), @vbytes += @vbzone
    END

    SELECT @prevColIndex = @colIndex, @colIndex = CHARINDEX( @delim, @tIPAddress, @colIndex + 1 ) 
END

SET @bytes =
    CASE @delim
        WHEN ':' THEN @vbytes
        ELSE /*0x000000000000000000000000 +*/ @vbytes -- Return IPV4 addresses as 4 byte binary (uncomment leading 0s section to force 16 byte binary)
    END 

RETURN @bytes

END

Test Cases

Valid cases

SELECT dbo.IPAddressStringToVarbinary( '0000:0000:0000:0000:0000:0000:0000:0001' ) -- 0x0000000000000000000000000001 (check bug fix)
SELECT dbo.IPAddressStringToVarbinary( '0001:0002:0003:0040:0500:0600:7000:0089' ) -- 0x00010002000300400500060070000089
SELECT dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319::370:7348' )     -- 0x20010DB885A308D31319000003707348 (check short hand)
SELECT dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319:0000:370:7348' ) -- 0x20010DB885A308D31319000003707348
SELECT dbo.IPAddressStringToVarbinary( '192.168.1.72' ) -- 0xC0A80148
SELECT dbo.IPAddressStringToVarbinary( '127...1' ) -- 0x7F000001 (check short hand)
SELECT dbo.IPAddressStringToVarbinary( NULL ) -- NULL
SELECT dbo.IPAddressStringToVarbinary( '' ) -- NULL
-- Check that conversions return original address
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '0001:0002:0003:0040:0500:0600:7000:0089' )) -- '0001:0002:0003:0040:0500:0600:7000:0089' 
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '127...1' )) -- 127.0.0.1
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '192.168.1.72' )) -- 192.168.1.72
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319::370:7348' ))     -- 2001:0db8:85a3:08d3:1319:0000:0370:7348
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1314:0000:370:7348' )) -- 2001:0db8:85a3:08d3:1319:0000:0370:7348
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3::370:7348' )) -- 2001:0DB8:85A3:08D3:0000:0000:0370:7348
-- This is technically an invalid IPV6 (according to Wikipedia) but it parses correctly
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8::1319::370:7348' )) -- 2001:0DB8:0000:0000:1319:0000:0370:7348

Invalid cases

SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8::1319::7348' )) -- 2001:0DB8:0000:0000:0000:1319:0000:7348 (ambiguous address)
SELECT dbo.IPAddressStringToVarbinary( '127.1' ) -- 127.0.0.1 (not supported short-hand)
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '127.1' )) -- 127.0.0.1 (not supported short-hand)
SELECT dbo.IPAddressStringToVarbinary( '0300.0000.0002.0353' ) -- octal byte values
SELECT dbo.IPAddressStringToVarbinary( '0xC0.0x00.0x02.0xEB' ) -- hex values
SELECT dbo.IPAddressStringToVarbinary( 'C0.00.02.EB' ) -- hex values

get the latest fragment in backstack

you can use getBackStackEntryAt(). In order to know how many entry the activity holds in the backstack you can use getBackStackEntryCount()

int lastFragmentCount = getBackStackEntryCount() - 1;

git replacing LF with CRLF

OP's question is windows related and I could not use others without going to the directory or even running file in Notepad++ as administrator did not work.. So had to go this route:

C:\Program Files (x86)\Git\etc>git config --global core.autocrlf false

Grant Select on a view not base table when base table is in a different database

As you state in one of your comments that the table in question is in a different database, then ownership chaining applies. I suspect there is a break in the chain somewhere - check that link for full details.

How to run iPhone emulator WITHOUT starting Xcode?

There's a far easier way:

  1. Hit command + space, Spotlight Search will appear
  2. Type in iOS Simulator and hit return

Done.

----- In follow up to @E. Maggini downvote---

Yes you can still easily access iOS Simulator using Spotlight.

enter image description here

Is there a way to make npm install (the command) to work behind proxy?

when I give without http/http prefix in the proxy settings npm failed even when the proxy host and port were right values. It worked only after adding the protocol prefix.

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

data.table vs dplyr: can one do something well the other can't or does poorly?

We need to cover at least these aspects to provide a comprehensive answer/comparison (in no particular order of importance): Speed, Memory usage, Syntax and Features.

My intent is to cover each one of these as clearly as possible from data.table perspective.

Note: unless explicitly mentioned otherwise, by referring to dplyr, we refer to dplyr's data.frame interface whose internals are in C++ using Rcpp.


The data.table syntax is consistent in its form - DT[i, j, by]. To keep i, j and by together is by design. By keeping related operations together, it allows to easily optimise operations for speed and more importantly memory usage, and also provide some powerful features, all while maintaining the consistency in syntax.

1. Speed

Quite a few benchmarks (though mostly on grouping operations) have been added to the question already showing data.table gets faster than dplyr as the number of groups and/or rows to group by increase, including benchmarks by Matt on grouping from 10 million to 2 billion rows (100GB in RAM) on 100 - 10 million groups and varying grouping columns, which also compares pandas. See also updated benchmarks, which include Spark and pydatatable as well.

On benchmarks, it would be great to cover these remaining aspects as well:

  • Grouping operations involving a subset of rows - i.e., DT[x > val, sum(y), by = z] type operations.

  • Benchmark other operations such as update and joins.

  • Also benchmark memory footprint for each operation in addition to runtime.

2. Memory usage

  1. Operations involving filter() or slice() in dplyr can be memory inefficient (on both data.frames and data.tables). See this post.

    Note that Hadley's comment talks about speed (that dplyr is plentiful fast for him), whereas the major concern here is memory.

  2. data.table interface at the moment allows one to modify/update columns by reference (note that we don't need to re-assign the result back to a variable).

    # sub-assign by reference, updates 'y' in-place
    DT[x >= 1L, y := NA]
    

    But dplyr will never update by reference. The dplyr equivalent would be (note that the result needs to be re-assigned):

    # copies the entire 'y' column
    ans <- DF %>% mutate(y = replace(y, which(x >= 1L), NA))
    

    A concern for this is referential transparency. Updating a data.table object by reference, especially within a function may not be always desirable. But this is an incredibly useful feature: see this and this posts for interesting cases. And we want to keep it.

    Therefore we are working towards exporting shallow() function in data.table that will provide the user with both possibilities. For example, if it is desirable to not modify the input data.table within a function, one can then do:

    foo <- function(DT) {
        DT = shallow(DT)          ## shallow copy DT
        DT[, newcol := 1L]        ## does not affect the original DT 
        DT[x > 2L, newcol := 2L]  ## no need to copy (internally), as this column exists only in shallow copied DT
        DT[x > 2L, x := 3L]       ## have to copy (like base R / dplyr does always); otherwise original DT will 
                                  ## also get modified.
    }
    

    By not using shallow(), the old functionality is retained:

    bar <- function(DT) {
        DT[, newcol := 1L]        ## old behaviour, original DT gets updated by reference
        DT[x > 2L, x := 3L]       ## old behaviour, update column x in original DT.
    }
    

    By creating a shallow copy using shallow(), we understand that you don't want to modify the original object. We take care of everything internally to ensure that while also ensuring to copy columns you modify only when it is absolutely necessary. When implemented, this should settle the referential transparency issue altogether while providing the user with both possibilties.

    Also, once shallow() is exported dplyr's data.table interface should avoid almost all copies. So those who prefer dplyr's syntax can use it with data.tables.

    But it will still lack many features that data.table provides, including (sub)-assignment by reference.

  3. Aggregate while joining:

    Suppose you have two data.tables as follows:

    DT1 = data.table(x=c(1,1,1,1,2,2,2,2), y=c("a", "a", "b", "b"), z=1:8, key=c("x", "y"))
    #    x y z
    # 1: 1 a 1
    # 2: 1 a 2
    # 3: 1 b 3
    # 4: 1 b 4
    # 5: 2 a 5
    # 6: 2 a 6
    # 7: 2 b 7
    # 8: 2 b 8
    DT2 = data.table(x=1:2, y=c("a", "b"), mul=4:3, key=c("x", "y"))
    #    x y mul
    # 1: 1 a   4
    # 2: 2 b   3
    

    And you would like to get sum(z) * mul for each row in DT2 while joining by columns x,y. We can either:

    • 1) aggregate DT1 to get sum(z), 2) perform a join and 3) multiply (or)

      # data.table way
      DT1[, .(z = sum(z)), keyby = .(x,y)][DT2][, z := z*mul][]
      
      # dplyr equivalent
      DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>% 
          right_join(DF2) %>% mutate(z = z * mul)
      
    • 2) do it all in one go (using by = .EACHI feature):

      DT1[DT2, list(z=sum(z) * mul), by = .EACHI]
      

    What is the advantage?

    • We don't have to allocate memory for the intermediate result.

    • We don't have to group/hash twice (one for aggregation and other for joining).

    • And more importantly, the operation what we wanted to perform is clear by looking at j in (2).

    Check this post for a detailed explanation of by = .EACHI. No intermediate results are materialised, and the join+aggregate is performed all in one go.

    Have a look at this, this and this posts for real usage scenarios.

    In dplyr you would have to join and aggregate or aggregate first and then join, neither of which are as efficient, in terms of memory (which in turn translates to speed).

  4. Update and joins:

    Consider the data.table code shown below:

    DT1[DT2, col := i.mul]
    

    adds/updates DT1's column col with mul from DT2 on those rows where DT2's key column matches DT1. I don't think there is an exact equivalent of this operation in dplyr, i.e., without avoiding a *_join operation, which would have to copy the entire DT1 just to add a new column to it, which is unnecessary.

    Check this post for a real usage scenario.

To summarise, it is important to realise that every bit of optimisation matters. As Grace Hopper would say, Mind your nanoseconds!

3. Syntax

Let's now look at syntax. Hadley commented here:

Data tables are extremely fast but I think their concision makes it harder to learn and code that uses it is harder to read after you have written it ...

I find this remark pointless because it is very subjective. What we can perhaps try is to contrast consistency in syntax. We will compare data.table and dplyr syntax side-by-side.

We will work with the dummy data shown below:

DT = data.table(x=1:10, y=11:20, z=rep(1:2, each=5))
DF = as.data.frame(DT)
  1. Basic aggregation/update operations.

    # case (a)
    DT[, sum(y), by = z]                       ## data.table syntax
    DF %>% group_by(z) %>% summarise(sum(y)) ## dplyr syntax
    DT[, y := cumsum(y), by = z]
    ans <- DF %>% group_by(z) %>% mutate(y = cumsum(y))
    
    # case (b)
    DT[x > 2, sum(y), by = z]
    DF %>% filter(x>2) %>% group_by(z) %>% summarise(sum(y))
    DT[x > 2, y := cumsum(y), by = z]
    ans <- DF %>% group_by(z) %>% mutate(y = replace(y, which(x > 2), cumsum(y)))
    
    # case (c)
    DT[, if(any(x > 5L)) y[1L]-y[2L] else y[2L], by = z]
    DF %>% group_by(z) %>% summarise(if (any(x > 5L)) y[1L] - y[2L] else y[2L])
    DT[, if(any(x > 5L)) y[1L] - y[2L], by = z]
    DF %>% group_by(z) %>% filter(any(x > 5L)) %>% summarise(y[1L] - y[2L])
    
    • data.table syntax is compact and dplyr's quite verbose. Things are more or less equivalent in case (a).

    • In case (b), we had to use filter() in dplyr while summarising. But while updating, we had to move the logic inside mutate(). In data.table however, we express both operations with the same logic - operate on rows where x > 2, but in first case, get sum(y), whereas in the second case update those rows for y with its cumulative sum.

      This is what we mean when we say the DT[i, j, by] form is consistent.

    • Similarly in case (c), when we have if-else condition, we are able to express the logic "as-is" in both data.table and dplyr. However, if we would like to return just those rows where the if condition satisfies and skip otherwise, we cannot use summarise() directly (AFAICT). We have to filter() first and then summarise because summarise() always expects a single value.

      While it returns the same result, using filter() here makes the actual operation less obvious.

      It might very well be possible to use filter() in the first case as well (does not seem obvious to me), but my point is that we should not have to.

  2. Aggregation / update on multiple columns

    # case (a)
    DT[, lapply(.SD, sum), by = z]                     ## data.table syntax
    DF %>% group_by(z) %>% summarise_each(funs(sum)) ## dplyr syntax
    DT[, (cols) := lapply(.SD, sum), by = z]
    ans <- DF %>% group_by(z) %>% mutate_each(funs(sum))
    
    # case (b)
    DT[, c(lapply(.SD, sum), lapply(.SD, mean)), by = z]
    DF %>% group_by(z) %>% summarise_each(funs(sum, mean))
    
    # case (c)
    DT[, c(.N, lapply(.SD, sum)), by = z]     
    DF %>% group_by(z) %>% summarise_each(funs(n(), mean))
    
    • In case (a), the codes are more or less equivalent. data.table uses familiar base function lapply(), whereas dplyr introduces *_each() along with a bunch of functions to funs().

    • data.table's := requires column names to be provided, whereas dplyr generates it automatically.

    • In case (b), dplyr's syntax is relatively straightforward. Improving aggregations/updates on multiple functions is on data.table's list.

    • In case (c) though, dplyr would return n() as many times as many columns, instead of just once. In data.table, all we need to do is to return a list in j. Each element of the list will become a column in the result. So, we can use, once again, the familiar base function c() to concatenate .N to a list which returns a list.

    Note: Once again, in data.table, all we need to do is return a list in j. Each element of the list will become a column in result. You can use c(), as.list(), lapply(), list() etc... base functions to accomplish this, without having to learn any new functions.

    You will need to learn just the special variables - .N and .SD at least. The equivalent in dplyr are n() and .

  3. Joins

    dplyr provides separate functions for each type of join where as data.table allows joins using the same syntax DT[i, j, by] (and with reason). It also provides an equivalent merge.data.table() function as an alternative.

    setkey(DT1, x, y)
    
    # 1. normal join
    DT1[DT2]            ## data.table syntax
    left_join(DT2, DT1) ## dplyr syntax
    
    # 2. select columns while join    
    DT1[DT2, .(z, i.mul)]
    left_join(select(DT2, x, y, mul), select(DT1, x, y, z))
    
    # 3. aggregate while join
    DT1[DT2, .(sum(z) * i.mul), by = .EACHI]
    DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>% 
        inner_join(DF2) %>% mutate(z = z*mul) %>% select(-mul)
    
    # 4. update while join
    DT1[DT2, z := cumsum(z) * i.mul, by = .EACHI]
    ??
    
    # 5. rolling join
    DT1[DT2, roll = -Inf]
    ??
    
    # 6. other arguments to control output
    DT1[DT2, mult = "first"]
    ??
    
    • Some might find a separate function for each joins much nicer (left, right, inner, anti, semi etc), whereas as others might like data.table's DT[i, j, by], or merge() which is similar to base R.

    • However dplyr joins do just that. Nothing more. Nothing less.

    • data.tables can select columns while joining (2), and in dplyr you will need to select() first on both data.frames before to join as shown above. Otherwise you would materialiase the join with unnecessary columns only to remove them later and that is inefficient.

    • data.tables can aggregate while joining (3) and also update while joining (4), using by = .EACHI feature. Why materialse the entire join result to add/update just a few columns?

    • data.table is capable of rolling joins (5) - roll forward, LOCF, roll backward, NOCB, nearest.

    • data.table also has mult = argument which selects first, last or all matches (6).

    • data.table has allow.cartesian = TRUE argument to protect from accidental invalid joins.

Once again, the syntax is consistent with DT[i, j, by] with additional arguments allowing for controlling the output further.

  1. do()...

    dplyr's summarise is specially designed for functions that return a single value. If your function returns multiple/unequal values, you will have to resort to do(). You have to know beforehand about all your functions return value.

    DT[, list(x[1], y[1]), by = z]                 ## data.table syntax
    DF %>% group_by(z) %>% summarise(x[1], y[1]) ## dplyr syntax
    DT[, list(x[1:2], y[1]), by = z]
    DF %>% group_by(z) %>% do(data.frame(.$x[1:2], .$y[1]))
    
    DT[, quantile(x, 0.25), by = z]
    DF %>% group_by(z) %>% summarise(quantile(x, 0.25))
    DT[, quantile(x, c(0.25, 0.75)), by = z]
    DF %>% group_by(z) %>% do(data.frame(quantile(.$x, c(0.25, 0.75))))
    
    DT[, as.list(summary(x)), by = z]
    DF %>% group_by(z) %>% do(data.frame(as.list(summary(.$x))))
    
    • .SD's equivalent is .

    • In data.table, you can throw pretty much anything in j - the only thing to remember is for it to return a list so that each element of the list gets converted to a column.

    • In dplyr, cannot do that. Have to resort to do() depending on how sure you are as to whether your function would always return a single value. And it is quite slow.

Once again, data.table's syntax is consistent with DT[i, j, by]. We can just keep throwing expressions in j without having to worry about these things.

Have a look at this SO question and this one. I wonder if it would be possible to express the answer as straightforward using dplyr's syntax...

To summarise, I have particularly highlighted several instances where dplyr's syntax is either inefficient, limited or fails to make operations straightforward. This is particularly because data.table gets quite a bit of backlash about "harder to read/learn" syntax (like the one pasted/linked above). Most posts that cover dplyr talk about most straightforward operations. And that is great. But it is important to realise its syntax and feature limitations as well, and I am yet to see a post on it.

data.table has its quirks as well (some of which I have pointed out that we are attempting to fix). We are also attempting to improve data.table's joins as I have highlighted here.

But one should also consider the number of features that dplyr lacks in comparison to data.table.

4. Features

I have pointed out most of the features here and also in this post. In addition:

  • fread - fast file reader has been available for a long time now.

  • fwrite - a parallelised fast file writer is now available. See this post for a detailed explanation on the implementation and #1664 for keeping track of further developments.

  • Automatic indexing - another handy feature to optimise base R syntax as is, internally.

  • Ad-hoc grouping: dplyr automatically sorts the results by grouping variables during summarise(), which may not be always desirable.

  • Numerous advantages in data.table joins (for speed / memory efficiency and syntax) mentioned above.

  • Non-equi joins: Allows joins using other operators <=, <, >, >= along with all other advantages of data.table joins.

  • Overlapping range joins was implemented in data.table recently. Check this post for an overview with benchmarks.

  • setorder() function in data.table that allows really fast reordering of data.tables by reference.

  • dplyr provides interface to databases using the same syntax, which data.table does not at the moment.

  • data.table provides faster equivalents of set operations (written by Jan Gorecki) - fsetdiff, fintersect, funion and fsetequal with additional all argument (as in SQL).

  • data.table loads cleanly with no masking warnings and has a mechanism described here for [.data.frame compatibility when passed to any R package. dplyr changes base functions filter, lag and [ which can cause problems; e.g. here and here.


Finally:

  • On databases - there is no reason why data.table cannot provide similar interface, but this is not a priority now. It might get bumped up if users would very much like that feature.. not sure.

  • On parallelism - Everything is difficult, until someone goes ahead and does it. Of course it will take effort (being thread safe).

    • Progress is being made currently (in v1.9.7 devel) towards parallelising known time consuming parts for incremental performance gains using OpenMP.

what's data-reactid attribute in html?

The data-reactid attribute is a custom attribute used so that React can uniquely identify its components within the DOM.

This is important because React applications can be rendered at the server as well as the client. Internally React builds up a representation of references to the DOM nodes that make up your application (simplified version is below).

{
  id: '.1oqi7occu80',
  node: DivRef,
  children: [
    {
      id: '.1oqi7occu80.0',
      node: SpanRef,
      children: [
        {
          id: '.1oqi7occu80.0.0',
          node: InputRef,
          children: []
        }
      ]
    }
  ]
}

There's no way to share the actual object references between the server and the client and sending a serialized version of the entire component tree is potentially expensive. When the application is rendered at the server and React is loaded at the client, the only data it has are the data-reactid attributes.

<div data-reactid='.loqi70ccu80'>
  <span data-reactid='.loqi70ccu80.0'>
    <input data-reactid='.loqi70ccu80.0' />
  </span>
</div>

It needs to be able to convert that back into the data structure above. The way it does that is with the unique data-reactid attributes. This is called inflating the component tree.

You might also notice that if React renders at the client-side, it uses the data-reactid attribute, even though it doesn't need to lose its references. In some browsers, it inserts your application into the DOM using .innerHTML then it inflates the component tree straight away, as a performance boost.

The other interesting difference is that client-side rendered React ids will have an incremental integer format (like .0.1.4.3), whereas server-rendered ones will be prefixed with a random string (such as .loqi70ccu80.1.4.3). This is because the application might be rendered across multiple servers and it's important that there are no collisions. At the client-side, there is only one rendering process, which means counters can be used to ensure unique ids.

React 15 uses document.createElement instead, so client rendered markup won't include these attributes anymore.

Add a UIView above all, even the navigation bar

There is more than one way to do it:

1- Add your UIView on UIWindow instead of adding it on UIViewController. This way it will be on top of everything.

   [[(AppDelegate *)[UIApplication sharedApplication].delegate window] addSubview:view];

2- Use custom transition that will keep your UIViewController showing in the back with a 0.5 alpha

For that I recommend you look at this: https://github.com/Citrrus/BlurryModalSegue

What is the difference between React Native and React?

ReactJS is a core framework, meant to build component isolated based on reactive pattern, you can think of it as the V from MVC, although I would like to state that react does brings a different feel, specially if you are less familiar with reactive concept.

ReactNative is another layer that is meant to have a set component for Android and iOS platform that are common. So the code looks basically the same as ReactJS because is ReactJS, but it load natively in mobile platforms. You can also bridge more complex and platform relative API with Java/Objective-C/Swift depending on the OS and use it within React.

Has Windows 7 Fixed the 255 Character File Path Limit?

See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx

This explains that Unicode versions of Windows APIs have higher limits, and how to enable that.

How to pass parameters or arguments into a gradle task

I think you probably want to view the minification of each set of css as a separate task

task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
     source = "src/main/webapp/css/brandA/styles.css"
     dest = "${buildDir}/brandA/styles.css"
}

etc etc

BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?

How can I enable the Windows Server Task Scheduler History recording?

As noted earlier, there is an option to turn on or off History provided you open up task manager under the elevated "Administrator" mode (right click on the Task Scheduler program/shortcut and choose "Run As Administrator"). Then under "Tasks" is your spot to stop or start History.

How can I split and parse a string in Python?

If it's always going to be an even LHS/RHS split, you can also use the partition method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS) if the separator is found, and (original_string, '', '') if the separator wasn't present:

>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')

>>> "shazam".partition("_")
('shazam', '', '')

Merge unequal dataframes and replace missing rows with 0

Another alternative with data.table.

EXAMPLE DATA

dt1 <- data.table(df1)
dt2 <- data.table(df2)
setkey(dt1,x)
setkey(dt2,x)

CODE

dt2[dt1,list(y=ifelse(is.na(y),0,y))]

android: how to align image in the horizontal center of an imageview?

For me android:gravity="center" did the trick in the parent layout element.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/fullImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/fullImageView"
        android:layout_gravity="center" />

</LinearLayout>

HTML: how to make 2 tables with different CSS

In your html

<table class="table1">
<tr>
<td>
...
</table>

<table class="table2">

<tr>
<td>
...
</table>

In your css:

table.table1 {...}
table.table1 tr {...}
table.table1 td {...}

table.table2 {...}
table.table2 tr {...}
table.table2 td {...}

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

My issue was that my method was missing the @RequestBody annotation. After adding the annotation I no longer received the 404 exception.

C# refresh DataGridView when updating or inserted on another form

my datagridview is editonEnter mode . so it refresh only after i leave cell or after i revisit and exit cell twice.

to trigger this iimedately . i unfocus from datagridview . then refocus it.

 this.SelectNextControl(dgv1,true,true,false,true);    
 Application.DoEvents();    //this does magic
 dgv1.Focus();

'NOT LIKE' in an SQL query

You've missed the id out before the NOT; it needs to be specified.

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

Is it possible to remove inline styles with jQuery?

$("#element").css({ display: "none" });

At first I tried to remove inline style in css, but it does not work and new style like display: none will be overwritten. But in JQuery it works like this.

How to prevent text in a table cell from wrapping

I came to this question needing to prevent text wrapping at the hyphen.

This is how I did it:

<td><nobr>Table Text</nobr></td>

Reference:

How to prevent line break at hyphens on all browsers

How do I print colored output with Python 3?

# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS

fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"

def print_six(row, format):
    for col in range(6):
        color = row*6 + col + 4
        if color>=0:
            text = "{:3d}".format(color)
            print (format(text,color), end=" ")
        else:
            print("   ", end=" ")

for row in range(-1,42):
    print_six(row, fg)
    print("",end=" ")
    print_six(row, bg)
    print()

# Simple usage: print(fg("text", 160))

Text with altering foreground and background, colors 0..141 Text with altering foreground and background, colors 142..255

Adding two Java 8 streams, or an extra element to a stream

At the end of the day I'm not interested in combining streams, but in obtaining the combined result of processing each element of all those streams.

While combining streams might prove to be cumbersome (thus this thread), combining their processing results is fairly easy.

The key to solve is to create your own collector and ensure that the supplier function for the new collector returns the same collection every time (not a new one), the code below illustrates this approach.

package scratchpad;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Stream;

public class CombineStreams {
    public CombineStreams() {
        super();
    }

    public static void main(String[] args) {
        List<String> resultList = new ArrayList<>();
        Collector<String, List<String>, List<String>> collector = Collector.of(
                () -> resultList,
                (list, item) -> {
                    list.add(item);
                },
                (llist, rlist) -> {
                    llist.addAll(rlist);
                    return llist;
                }
        );
        String searchString = "Wil";

        System.out.println("After processing first stream\n"
                + createFirstStream().filter(name -> name.contains(searchString)).collect(collector));
        System.out.println();

        System.out.println("After processing second stream\n"
                + createSecondStream().filter(name -> name.contains(searchString)).collect(collector));
        System.out.println();

        System.out.println("After processing third stream\n"
                + createThirdStream().filter(name -> name.contains(searchString)).collect(collector));
        System.out.println();

    }

    private static Stream<String> createFirstStream() {
        return Arrays.asList(
                "William Shakespeare",
                "Emily Dickinson",
                "H. P. Lovecraft",
                "Arthur Conan Doyle",
                "Leo Tolstoy",
                "Edgar Allan Poe",
                "Robert Ervin Howard",
                "Rabindranath Tagore",
                "Rudyard Kipling",
                "Seneca",
                "John Donne",
                "Sarah Williams",
                "Oscar Wilde",
                "Catullus",
                "Alfred Tennyson",
                "William Blake",
                "Charles Dickens",
                "John Keats",
                "Theodor Herzl"
        ).stream();
    }

    private static Stream<String> createSecondStream() {
        return Arrays.asList(
                "Percy Bysshe Shelley",
                "Ernest Hemingway",
                "Barack Obama",
                "Anton Chekhov",
                "Henry Wadsworth Longfellow",
                "Arthur Schopenhauer",
                "Jacob De Haas",
                "George Gordon Byron",
                "Jack London",
                "Robert Frost",
                "Abraham Lincoln",
                "O. Henry",
                "Ovid",
                "Robert Louis Stevenson",
                "John Masefield",
                "James Joyce",
                "Clark Ashton Smith",
                "Aristotle",
                "William Wordsworth",
                "Jane Austen"
        ).stream();
    }

    private static Stream<String> createThirdStream() {
        return Arrays.asList(
                "Niccolò Machiavelli",
                "Lewis Carroll",
                "Robert Burns",
                "Edgar Rice Burroughs",
                "Plato",
                "John Milton",
                "Ralph Waldo Emerson",
                "Margaret Thatcher",
                "Sylvie d'Avigdor",
                "Marcus Tullius Cicero",
                "Banjo Paterson",
                "Woodrow Wilson",
                "Walt Whitman",
                "Theodore Roosevelt",
                "Agatha Christie",
                "Ambrose Bierce",
                "Nikola Tesla",
                "Franz Kafka"
        ).stream();
    }
}

How to select bottom most rows?

The problem with ordering the other way is that it often does not make good use of indices. It is also not very extendable if you ever need to select a number of rows that are not at the start or the end. An alternative way is as follows.

DECLARE @NumberOfRows int;
SET @NumberOfRows = (SELECT COUNT(*) FROM TheTable);

SELECT col1, col2,...
FROM (
    SELECT col1, col2,..., ROW_NUMBER() OVER (ORDER BY col1) AS intRow
    FROM TheTable
) AS T
WHERE intRow > @NumberOfRows - 20;

What is :: (double colon) in Python when subscripting sequences?

it means 'nothing for the first argument, nothing for the second, and jump by three'. It gets every third item of the sequence sliced. Extended slices is what you want. New in Python 2.3

Angular 2 - NgFor using numbers instead collections

A simplest way that i have tried

You can also create an array in your component file and you can call it with *ngFor directive by returning as an array .

Something like this ....

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-morning',
  templateUrl: './morning.component.html',
  styleUrls: ['./morning.component.css']
})
export class MorningComponent implements OnInit {

  arr = [];
  i: number = 0;
  arra() {
    for (this.i = 0; this.i < 20; this.i++) {
      this.arr[this.i]=this.i;
    }
    return this.arr;
  }

  constructor() { }

  ngOnInit() {
  }

}

And this function can be used in your html template file

<p *ngFor="let a of arra(); let i= index">
value:{{a}} position:{{i}}
</p>

How do relative file paths work in Eclipse?

You need "src/Hankees.txt"

Your file is in the source folder which is not counted as the working directory.\

Or you can move the file up to the root directory of your project and just use "Hankees.txt"

Get min and max value in PHP Array

For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.

How to get a max value:

$highest_weight = max(array_column($details, 'Weight'));

How to get the min value

$lowest_weight = min(array_column($details, 'Weight'));

Build error: You must add a reference to System.Runtime

The only way that worked for me - add the assembly to web.config

<compilation debug="true" targetFramework="4.5">
  <assemblies>     
    <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />   
  </assemblies>
</compilation>

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

The general rule-of-thumb is, if you can do it using a single SQL statement instead of using PL/SQL, you should. It will usually be more efficient.

However, if you need to add more procedural logic (for some reason), you might need to use PL/SQL, but you should use bulk operations instead of row-by-row processing. (Note: in Oracle 10g and later, your FOR loop will automatically use BULK COLLECT to fetch 100 rows at a time; however your insert statement will still be done row-by-row).

e.g.

DECLARE
   TYPE tA IS TABLE OF FOO.A%TYPE INDEX BY PLS_INTEGER;
   TYPE tB IS TABLE OF FOO.B%TYPE INDEX BY PLS_INTEGER;
   TYPE tC IS TABLE OF FOO.C%TYPE INDEX BY PLS_INTEGER;
   rA tA;
   rB tB;
   rC tC;
BEGIN
   SELECT * BULK COLLECT INTO rA, rB, rC FROM FOO;
   -- (do some procedural logic on the data?)
   FORALL i IN rA.FIRST..rA.LAST
      INSERT INTO BAR(A,
                      B,
                      C)
      VALUES(rA(i),
             rB(i),
             rC(i));
END;

The above has the benefit of minimising context switches between SQL and PL/SQL. Oracle 11g also has better support for tables of records so that you don't have to have a separate PL/SQL table for each column.

Also, if the volume of data is very great, it is possible to change the code to process the data in batches.

HTTP POST using JSON in Java

For Java 11 you can use new HTTP client:

 HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost/api"))
        .header("Content-Type", "application/json")
        .POST(ofInputStream(() -> getClass().getResourceAsStream(
            "/some-data.json")))
        .build();

    client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println)
        .join();

You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.

Fix footer to bottom of page

Set

html, body {
    height: 100%;
}

Wrap the entire content before the footer in a div.

.wrapper {
    height:auto !important;
    min-height:100%;
}

You can adjust min-height as you like based on how much of the footer you want to show in the bottom of the browser window. If set it to 90%, 10% of the footer will show before scrolling.

Java 8: merge lists with stream API

I think flatMap() is what you're looking for.

For example:

 List<AClass> allTheObjects = map.values()
         .stream()
         .flatMap(listContainer -> listContainer.lst.stream())
         .collect(Collectors.toList());

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

Tensorflow 2.0 Compatible Answer: In Tensorflow Version >= 2.0, the command for Initializing all the Variables if we use Graph Mode, to fix the FailedPreconditionError is shown below:

tf.compat.v1.global_variables_initializer

This is just a shortcut for variables_initializer(global_variables())

It returns an Op that initializes global variables in the graph.

json call with C#

In your code you don't get the HttpResponse, so you won't see what the server side sends you back.

you need to get the Response similar to the way you get (make) the Request. So

public static bool SendAnSMSMessage(string message)
{
  var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
  httpWebRequest.ContentType = "text/json";
  httpWebRequest.Method = "POST";

  using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
  {
    string json = "{ \"method\": \"send\", " +
                      "  \"params\": [ " +
                      "             \"IPutAGuidHere\", " +
                      "             \"[email protected]\", " +
                      "             \"MyTenDigitNumberWasHere\", " +
                      "             \"" + message + "\" " +
                      "             ] " +
                      "}";

    streamWriter.Write(json);
  }
  var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  {
    var responseText = streamReader.ReadToEnd();
    //Now you have your response.
    //or false depending on information in the response
    return true;        
  }
}

I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

How to add empty spaces into MD markdown readme on GitHub?

Instead of using HTML entities like &nbsp; and &emsp; (as others have suggested), you can use the Unicode em space (8195 in UTF-8) directly. Try copy-pasting the following into your README.md. The spaces at the start of the lines are em spaces.

The action of every agent <br />
  into the world <br />
starts <br />
  from their physical selves. <br />

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

We have come across this issue in desktop app.

Dev Environment: Windows 7 Ultimate - 64 bit .Net Framework 4.5 Provider=Microsoft.Jet.OLEDB.4.0

It has been resolved by changing Platform target to X86 from Any CPU. Project Properties >> Build >> Platform Target.

enter image description here

How to read file using NPOI

I find NPOI very usefull for working with Excel Files, here is my implementation (Comments are in Spanish, sorry for that):

This Method Opens an Excel (both xls or xlsx) file and converts it into a DataTable.

        /// <summary>Abre un archivo de Excel (xls o xlsx) y lo convierte en un DataTable.
    /// LA PRIMERA FILA DEBE CONTENER LOS NOMBRES DE LOS CAMPOS.</summary>
    /// <param name="pRutaArchivo">Ruta completa del archivo a abrir.</param>
    /// <param name="pHojaIndex">Número (basado en cero) de la hoja que se desea abrir. 0 es la primera hoja.</param>
    private DataTable Excel_To_DataTable(string pRutaArchivo, int pHojaIndex)
    {
        // --------------------------------- //
        /* REFERENCIAS:
         * NPOI.dll
         * NPOI.OOXML.dll
         * NPOI.OpenXml4Net.dll */
        // --------------------------------- //
        /* USING:
         * using NPOI.SS.UserModel;
         * using NPOI.HSSF.UserModel;
         * using NPOI.XSSF.UserModel; */
        // AUTOR: Ing. Jhollman Chacon R. 2015
        // --------------------------------- //
        DataTable Tabla = null;
        try
        {
            if (System.IO.File.Exists(pRutaArchivo))
            {

                IWorkbook workbook = null;  //IWorkbook determina si es xls o xlsx              
                ISheet worksheet = null;
                string first_sheet_name = "";

                using (FileStream FS = new FileStream(pRutaArchivo, FileMode.Open, FileAccess.Read))
                {
                    workbook = WorkbookFactory.Create(FS);          //Abre tanto XLS como XLSX
                    worksheet = workbook.GetSheetAt(pHojaIndex);    //Obtener Hoja por indice
                    first_sheet_name = worksheet.SheetName;         //Obtener el nombre de la Hoja

                    Tabla = new DataTable(first_sheet_name);
                    Tabla.Rows.Clear();
                    Tabla.Columns.Clear();

                    // Leer Fila por fila desde la primera
                    for (int rowIndex = 0; rowIndex <= worksheet.LastRowNum; rowIndex++)
                    {
                        DataRow NewReg = null;
                        IRow row = worksheet.GetRow(rowIndex);
                        IRow row2 = null;
                        IRow row3 = null;

                        if (rowIndex == 0)
                        {
                            row2 = worksheet.GetRow(rowIndex + 1); //Si es la Primera fila, obtengo tambien la segunda para saber el tipo de datos
                            row3 = worksheet.GetRow(rowIndex + 2); //Y la tercera tambien por las dudas
                        }

                        if (row != null) //null is when the row only contains empty cells 
                        {
                            if (rowIndex > 0) NewReg = Tabla.NewRow();

                            int colIndex = 0;
                            //Leer cada Columna de la fila
                            foreach (ICell cell in row.Cells)
                            {
                                object valorCell = null;
                                string cellType = "";
                                string[] cellType2 = new string[2];

                                if (rowIndex == 0) //Asumo que la primera fila contiene los titlos:
                                {
                                    for (int i = 0; i < 2; i++)
                                    {
                                        ICell cell2 = null;
                                        if (i == 0) { cell2 = row2.GetCell(cell.ColumnIndex); }
                                        else { cell2 = row3.GetCell(cell.ColumnIndex); }

                                        if (cell2 != null)
                                        {
                                            switch (cell2.CellType)
                                            {
                                                case CellType.Blank: break;
                                                case CellType.Boolean: cellType2[i] = "System.Boolean"; break;
                                                case CellType.String: cellType2[i] = "System.String"; break;
                                                case CellType.Numeric:
                                                    if (HSSFDateUtil.IsCellDateFormatted(cell2)) { cellType2[i] = "System.DateTime"; }
                                                    else
                                                    {
                                                        cellType2[i] = "System.Double";  //valorCell = cell2.NumericCellValue;
                                                    }
                                                    break;

                                                case CellType.Formula:                                                      
                                                    bool continuar = true;
                                                    switch (cell2.CachedFormulaResultType)
                                                    {
                                                        case CellType.Boolean: cellType2[i] = "System.Boolean"; break;
                                                        case CellType.String: cellType2[i] = "System.String"; break;
                                                        case CellType.Numeric:
                                                            if (HSSFDateUtil.IsCellDateFormatted(cell2)) { cellType2[i] = "System.DateTime"; }
                                                            else
                                                            {
                                                                try
                                                                {
                                                                    //DETERMINAR SI ES BOOLEANO
                                                                    if (cell2.CellFormula == "TRUE()") { cellType2[i] = "System.Boolean"; continuar = false; }
                                                                    if (continuar && cell2.CellFormula == "FALSE()") { cellType2[i] = "System.Boolean"; continuar = false; }
                                                                    if (continuar) { cellType2[i] = "System.Double"; continuar = false; }
                                                                }
                                                                catch { }
                                                            } break;
                                                    }
                                                    break;
                                                default:
                                                    cellType2[i] = "System.String"; break;
                                            }
                                        }
                                    }

                                    //Resolver las diferencias de Tipos
                                    if (cellType2[0] == cellType2[1]) { cellType = cellType2[0]; }
                                    else
                                    {
                                        if (cellType2[0] == null) cellType = cellType2[1];
                                        if (cellType2[1] == null) cellType = cellType2[0];
                                        if (cellType == "") cellType = "System.String";
                                    }

                                    //Obtener el nombre de la Columna
                                    string colName = "Column_{0}";
                                    try { colName = cell.StringCellValue; }
                                    catch { colName = string.Format(colName, colIndex); }

                                    //Verificar que NO se repita el Nombre de la Columna
                                    foreach (DataColumn col in Tabla.Columns)
                                    {
                                        if (col.ColumnName == colName) colName = string.Format("{0}_{1}", colName, colIndex);
                                    }

                                    //Agregar el campos de la tabla:
                                    DataColumn codigo = new DataColumn(colName, System.Type.GetType(cellType));
                                    Tabla.Columns.Add(codigo); colIndex++;
                                }
                                else
                                {
                                    //Las demas filas son registros:
                                    switch (cell.CellType)
                                    {
                                        case CellType.Blank: valorCell = DBNull.Value; break;
                                        case CellType.Boolean: valorCell = cell.BooleanCellValue; break;
                                        case CellType.String: valorCell = cell.StringCellValue; break;
                                        case CellType.Numeric:
                                            if (HSSFDateUtil.IsCellDateFormatted(cell)) { valorCell = cell.DateCellValue; }
                                            else { valorCell = cell.NumericCellValue; } break;
                                        case CellType.Formula:
                                            switch (cell.CachedFormulaResultType)
                                            {
                                                case CellType.Blank: valorCell = DBNull.Value; break;
                                                case CellType.String: valorCell = cell.StringCellValue; break;
                                                case CellType.Boolean: valorCell = cell.BooleanCellValue; break;
                                                case CellType.Numeric:
                                                    if (HSSFDateUtil.IsCellDateFormatted(cell)) { valorCell = cell.DateCellValue; }
                                                    else { valorCell = cell.NumericCellValue; }
                                                    break;
                                            }
                                            break;
                                        default: valorCell = cell.StringCellValue; break;
                                    }
                                    //Agregar el nuevo Registro
                                    if (cell.ColumnIndex <= Tabla.Columns.Count - 1) NewReg[cell.ColumnIndex] = valorCell;
                                }
                            }
                        }
                        if (rowIndex > 0) Tabla.Rows.Add(NewReg);
                    }
                    Tabla.AcceptChanges();
                }
            }
            else
            {
                throw new Exception("ERROR 404: El archivo especificado NO existe.");
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return Tabla;
    }

This Second method does the oposite, saves a DataTable into an Excel File, yeah it can either be xls or the new xlsx, your choise!

        /// <summary>Convierte un DataTable en un archivo de Excel (xls o Xlsx) y lo guarda en disco.</summary>
    /// <param name="pDatos">Datos de la Tabla a guardar. Usa el nombre de la tabla como nombre de la Hoja</param>
    /// <param name="pFilePath">Ruta del archivo donde se guarda.</param>
    private void DataTable_To_Excel(DataTable pDatos, string pFilePath)
    {
        try
        {
            if (pDatos != null && pDatos.Rows.Count > 0)
            {
                IWorkbook workbook = null;
                ISheet worksheet = null;

                using (FileStream stream = new FileStream(pFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    string Ext = System.IO.Path.GetExtension(pFilePath); //<-Extension del archivo
                    switch (Ext.ToLower())
                    {
                        case ".xls":
                            HSSFWorkbook workbookH = new HSSFWorkbook();
                            NPOI.HPSF.DocumentSummaryInformation dsi = NPOI.HPSF.PropertySetFactory.CreateDocumentSummaryInformation();
                            dsi.Company = "Cutcsa"; dsi.Manager = "Departamento Informatico";
                            workbookH.DocumentSummaryInformation = dsi;
                            workbook = workbookH;
                            break;

                        case ".xlsx": workbook = new XSSFWorkbook(); break;
                    }

                    worksheet = workbook.CreateSheet(pDatos.TableName); //<-Usa el nombre de la tabla como nombre de la Hoja

                    //CREAR EN LA PRIMERA FILA LOS TITULOS DE LAS COLUMNAS
                    int iRow = 0;
                    if (pDatos.Columns.Count > 0)
                    {
                        int iCol = 0;
                        IRow fila = worksheet.CreateRow(iRow);
                        foreach (DataColumn columna in pDatos.Columns)
                        {
                            ICell cell = fila.CreateCell(iCol, CellType.String);
                            cell.SetCellValue(columna.ColumnName);
                            iCol++;
                        }
                        iRow++;
                    }

                    //FORMATOS PARA CIERTOS TIPOS DE DATOS
                    ICellStyle _doubleCellStyle = workbook.CreateCellStyle();
                    _doubleCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("#,##0.###");

                    ICellStyle _intCellStyle = workbook.CreateCellStyle();
                    _intCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("#,##0");

                    ICellStyle _boolCellStyle = workbook.CreateCellStyle();
                    _boolCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("BOOLEAN");

                    ICellStyle _dateCellStyle = workbook.CreateCellStyle();
                    _dateCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("dd-MM-yyyy");

                    ICellStyle _dateTimeCellStyle = workbook.CreateCellStyle();
                    _dateTimeCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("dd-MM-yyyy HH:mm:ss");

                    //AHORA CREAR UNA FILA POR CADA REGISTRO DE LA TABLA
                    foreach (DataRow row in pDatos.Rows)
                    {
                        IRow fila = worksheet.CreateRow(iRow);
                        int iCol = 0;
                        foreach (DataColumn column in pDatos.Columns)
                        {
                            ICell cell = null; //<-Representa la celda actual                               
                            object cellValue = row[iCol]; //<- El valor actual de la celda

                            switch (column.DataType.ToString())
                            {
                                case "System.Boolean":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = fila.CreateCell(iCol, CellType.Boolean);

                                        if (Convert.ToBoolean(cellValue)) { cell.SetCellFormula("TRUE()"); }
                                        else { cell.SetCellFormula("FALSE()"); }

                                        cell.CellStyle = _boolCellStyle;
                                    }
                                    break;

                                case "System.String":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = fila.CreateCell(iCol, CellType.String);
                                        cell.SetCellValue(Convert.ToString(cellValue));
                                    }
                                    break;

                                case "System.Int32":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = fila.CreateCell(iCol, CellType.Numeric);
                                        cell.SetCellValue(Convert.ToInt32(cellValue));
                                        cell.CellStyle = _intCellStyle;
                                    }
                                    break;
                                case "System.Int64":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = fila.CreateCell(iCol, CellType.Numeric);
                                        cell.SetCellValue(Convert.ToInt64(cellValue));
                                        cell.CellStyle = _intCellStyle;
                                    }
                                    break;
                                case "System.Decimal":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = fila.CreateCell(iCol, CellType.Numeric);
                                        cell.SetCellValue(Convert.ToDouble(cellValue));
                                        cell.CellStyle = _doubleCellStyle;
                                    }
                                    break;
                                case "System.Double":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = fila.CreateCell(iCol, CellType.Numeric);
                                        cell.SetCellValue(Convert.ToDouble(cellValue));
                                        cell.CellStyle = _doubleCellStyle;
                                    }
                                    break;

                                case "System.DateTime":
                                    if (cellValue != DBNull.Value)
                                    {
                                        cell = fila.CreateCell(iCol, CellType.Numeric);
                                        cell.SetCellValue(Convert.ToDateTime(cellValue));

                                        //Si No tiene valor de Hora, usar formato dd-MM-yyyy
                                        DateTime cDate = Convert.ToDateTime(cellValue);
                                        if (cDate != null && cDate.Hour > 0) { cell.CellStyle = _dateTimeCellStyle; }
                                        else { cell.CellStyle = _dateCellStyle; }
                                    }
                                    break;
                                default:
                                    break;
                            }
                            iCol++;
                        }
                        iRow++;
                    }

                    workbook.Write(stream);
                    stream.Close();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

With this 2 methods you can Open an Excel file, load it into a DataTable, do your modifications and save it back into an Excel file.

Hope you guys find this usefull.

Show special characters in Unix while using 'less' Command

For less use -u to display carriage returns (^M) and backspaces (^H), or -U to show the previous and tabs (^I) for example:

$ awk 'BEGIN{print "foo\bbar\tbaz\r\n"}' | less -U 
foo^Hbar^Ibaz^M

(END)

Without the -U switch the output would be:

fobar   baz

(END)

See man less for more exact description on the features.

Sequence contains no matching element

Maybe using Where() before First() can help you, as my problem has been solved in this case.

var documentRow = _dsACL.Documents.Where(o => o.ID == id).FirstOrDefault();

Unable to run Java GUI programs with Ubuntu

Check your X Window environment variables using the "env" command.

Separating class code into a header and cpp file

I won't refer too your example as it is quite simple for a general answer (for example it doesn't contain templated functions ,which force you to implement them on the header) , what I follow as a rule of thumb is the pimpl idiom

It has quite some benefits as you get faster compilation times and the syntactic sugar :

class->member instead of class.member

The only drawback is the extra pointer you pay.

Executing Shell Scripts from the OS X Dock?

As long as your script is executable and doesn't have any extension you can drag it as-is to the right side (Document side) of the Dock and it will run in a terminal window when clicked instead of opening an editor.

If you want to have an extension (like foo.sh), you can go to the file info window in Finder and change the default application for that particular script from whatever it is (TextEdit, TextMate, whatever default is set on your computer for .sh files) to Terminal. It will then just execute instead of opening in a text editor. Again, you will have to drag it to the right side of the Dock.

How to run Selenium WebDriver test cases in Chrome

You can use the below code to run test cases in Chrome using Selenium WebDriver:

import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ChromeTest {

    /**
     * @param args
     * @throws InterruptedException
     * @throws IOException
     */
    public static void main(String[] args) throws InterruptedException, IOException {
        // Telling the system where to find the Chrome driver
        System.setProperty(
                "webdriver.chrome.driver",
                "E:/chromedriver_win32/chromedriver.exe");

        WebDriver webDriver = new ChromeDriver();

        // Open google.com
        webDriver.navigate().to("http://www.google.com");

        String html = webDriver.getPageSource();

        // Printing result here.
        System.out.println(html);

        webDriver.close();
        webDriver.quit();
    }
}

How to set focus on an input field after rendering?

The React docs now have a section for this. https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute

 render: function() {
  return (
    <TextInput
      ref={function(input) {
        if (input != null) {
          input.focus();
        }
      }} />
    );
  },

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

It seems daft, but I think when you use the same bind variable twice you have to set it twice:

cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");

Certainly that's true with Native Dynamic SQL in PL/SQL:

SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name'
  3     using 'KING';
  4  end;
  5  /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound


SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name' 
  3     using 'KING', 'KING';
  4  end;
  5  /

PL/SQL procedure successfully completed.

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

cd /home/<user_name>/
sudo vi .bash_profile

add these lines at the end

LD_LIBRARY_PATH=/usr/local/lib:<any other paths you want>
export LD_LIBRARY_PATH

Using the RUN instruction in a Dockerfile with 'source' does not work

Here is an example Dockerfile leveraging several clever techniques to all you to run a full conda environment for every RUN stanza. You can use a similar approach to execute any arbitrary prep in a script file.

Note: there is a lot of nuance when it comes to login/interactive vs nonlogin/noninteractive shells, signals, exec, the way multiple args are handled, quoting, how CMD and ENTRYPOINT interact, and a million other things, so don't be discouraged if when hacking around with these things, stuff goes sideways. I've spent many frustrating hours digging through all manner of literature and I still don't quite get how it all clicks.

## Conda with custom entrypoint from base ubuntu image
## Build with e.g. `docker build -t monoconda .`
## Run with `docker run --rm -it monoconda bash` to drop right into
## the environment `foo` !
FROM ubuntu:18.04

## Install things we need to install more things
RUN apt-get update -qq &&\
    apt-get install -qq curl wget git &&\
    apt-get install -qq --no-install-recommends \
        libssl-dev \
        software-properties-common \
    && rm -rf /var/lib/apt/lists/*

## Install miniconda
RUN wget -nv https://repo.anaconda.com/miniconda/Miniconda3-4.7.12-Linux-x86_64.sh -O ~/miniconda.sh && \
    /bin/bash ~/miniconda.sh -b -p /opt/conda && \
    rm ~/miniconda.sh && \
    /opt/conda/bin/conda clean -tipsy && \
    ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh

## add conda to the path so we can execute it by name
ENV PATH=/opt/conda/bin:$PATH

## Create /entry.sh which will be our new shell entry point. This performs actions to configure the environment
## before starting a new shell (which inherits the env).
## The exec is important! This allows signals to pass
RUN     (echo '#!/bin/bash' \
    &&   echo '__conda_setup="$(/opt/conda/bin/conda shell.bash hook 2> /dev/null)"' \
    &&   echo 'eval "$__conda_setup"' \
    &&   echo 'conda activate "${CONDA_TARGET_ENV:-base}"' \
    &&   echo '>&2 echo "ENTRYPOINT: CONDA_DEFAULT_ENV=${CONDA_DEFAULT_ENV}"' \
    &&   echo 'exec "$@"'\
        ) >> /entry.sh && chmod +x /entry.sh

## Tell the docker build process to use this for RUN.
## The default shell on Linux is ["/bin/sh", "-c"], and on Windows is ["cmd", "/S", "/C"]
SHELL ["/entry.sh", "/bin/bash", "-c"]
## Now, every following invocation of RUN will start with the entry script
RUN     conda update conda -y

## Create a dummy env
RUN     conda create --name foo

## I added this variable such that I have the entry script activate a specific env
ENV CONDA_TARGET_ENV=foo

## This will get installed in the env foo since it gets activated at the start of the RUN stanza
RUN  conda install pip

## Configure .bashrc to drop into a conda env and immediately activate our TARGET env
RUN conda init && echo 'conda activate "${CONDA_TARGET_ENV:-base}"' >>  ~/.bashrc
ENTRYPOINT ["/entry.sh"]

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

Removing pip's cache?

(pip maintainer here!)

The specific issue of "installing the wrong version due to caching" issue mentioned in the question was fixed in pip 1.4 (back in 2013!):

Fix a number of issues related to cleaning up and not reusing build directories. (#413, #709, #634, #602, #939, #865, #948)

Since pip 6.0 (back in 2014!), pip install, pip download and pip wheel commands can be told to avoid using the cache with the --no-cache-dir option. (eg: pip install --no-cache-dir <package>)

Since pip 10.0 (back in 2018!), a pip config command was added, which can be used to configure pip to always ignore the cache -- pip config set global.cache-dir false configures pip to not use the cache "globally" (i.e. in all commands).

Since pip 20.1, pip has a pip cache command to manage the contents of pip's cache.

  • pip cache purge removes all the wheel files in the cache.
  • pip cache remove matplotlib selectively removes files related to a matplotlib from the cache.

In summary, pip provides a lot of ways to tweak how it uses the cache:

  • pip install --no-cache-dir <package>: install a package without using the cache, for just this run.
  • pip config set global.cache-dir false: configure pip to not use the cache "globally" (in all commands)
  • pip cache remove matplotlib: removes all wheel files related to matplotlib from pip's cache.
  • pip cache purge: to clear all files from pip's cache.

Convert Java string to Time, NOT Date

You might want to take a look at this example:

public static void main(String[] args) {

    String myTime = "10:30:54";
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    Date date = null;
    try {
        date = sdf.parse(myTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formattedTime = sdf.format(date);

    System.out.println(formattedTime);

}

Global variables in AngularJS

You can also do something like this ..

function MyCtrl1($scope) {
    $rootScope.$root.name = 'anonymous'; 
}

function MyCtrl2($scope) {
    var name = $rootScope.$root.name;
}

A KeyValuePair in Java

Android programmers could use BasicNameValuePair

Update:

BasicNameValuePair is now deprecated (API 22). Use Pair instead.

Example usage:

Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"

How do I select an entire row which has the largest ID in the table?

SELECT * 
FROM table 
WHERE id = (SELECT MAX(id) FROM TABLE)

How to Convert JSON object to Custom C# object?

JavaScript Serializer: requires using System.Web.Script.Serialization;

public class JavaScriptSerializerDeSerializer<T>
{
    private readonly JavaScriptSerializer serializer;

    public JavaScriptSerializerDeSerializer()
    {
        this.serializer = new JavaScriptSerializer();
    }

    public string Serialize(T t)
    {
        return this.serializer.Serialize(t);
    }

    public T Deseralize(string stringObject)
    {
        return this.serializer.Deserialize<T>(stringObject);
    }
}

Data Contract Serializer: requires using System.Runtime.Serialization.Json; - The generic type T should be serializable more on Data Contract

public class JsonSerializerDeserializer<T> where T : class
{
    private readonly DataContractJsonSerializer jsonSerializer;

    public JsonSerializerDeserializer()
    {
        this.jsonSerializer = new DataContractJsonSerializer(typeof(T));
    }

    public string Serialize(T t)
    {
        using (var memoryStream = new MemoryStream())
        {
            this.jsonSerializer.WriteObject(memoryStream, t);
            memoryStream.Position = 0;
            using (var sr = new StreamReader(memoryStream))
            {
                return sr.ReadToEnd();
            }
        }
    }

    public T Deserialize(string objectString)
    {
        using (var ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes((objectString))))
        {
            return (T)this.jsonSerializer.ReadObject(ms);
        }
    }
}

java.net.URL read stream to byte[]

Here's a clean solution:

private byte[] downloadUrl(URL toDownload) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        byte[] chunk = new byte[4096];
        int bytesRead;
        InputStream stream = toDownload.openStream();

        while ((bytesRead = stream.read(chunk)) > 0) {
            outputStream.write(chunk, 0, bytesRead);
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return outputStream.toByteArray();
}

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Convert a positive number to negative in C#

Maybe this?

int n;

.... some coding....

n = n<=0? n:0-n;

How to use .htaccess in WAMP Server?

Open the httpd.conf file and search for

"rewrite"

, then remove

"#"

at the starting of the line,so the line looks like.

LoadModule rewrite_module modules/mod_rewrite.so

then restart the wamp.

HTML5 Video tag not working in Safari , iPhone and iPad

I had same problem - make sure the url for video asset is coming from secure domain. Our dev environment is http while production is secure. Due to the video being referenced via relative path, it wasn't working on development. Seems to be an issue that apple requires video to be secure...

Deleting Objects in JavaScript

"variables declared implicitly" are properties of the global object, so delete works on them like it works on any property. Variables declared with var are indestructible.

What is the significance of url-pattern in web.xml and how to configure servlet?

Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

First specification of url-pattern a web.xml file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern> as follows:

http://server.com/server/status/synopsis               = Matches
http://server.com/server/status/complete?date=today    = Matches
http://server.com/server/status                        = Matches
http://server.com/server/server1/status                = Does not match

Second specification of url-pattern A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern> as follows:

 http://server.com/server/US/Oregon/Portland.map    = Matches
 http://server.com/server/US/server/Seattle.map     = Matches
 http://server.com/server/Paris.France.map          = Matches
 http://server.com/server/US/Oregon/Portland.MAP    = Does not match, the extension is uppercase
 http://example.com/examples/interface/description/mail.mapi  =Does not match, the extension is mapi rather than map`

Third specification of url-mapping,A mapping that contains the pattern <url-pattern>/</url-pattern> matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.

The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.

The servlet-mapping element below maps the server servlet instance to the default mapping.

<servlet-mapping>
  <servlet-name>server</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

For the context that contains this element, any request that is not handled by another mapping is forwarded to the server servlet.

And Most importantly we should Know about Rule for URL path mapping

  1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
  2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
  3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
  4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

Reference URL Pattern

How to call a View Controller programmatically?

Swift

This gets a view controller from the storyboard and presents it.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewControllerId") as! SecondViewController
self.present(secondViewController, animated: true, completion: nil)

Change the storyboard name, view controller name, and view controller id as appropriate.

How do I make a composite key with SQL Server Management Studio?

create table myTable 
(
    Column1 int not null,
    Column2 int not null
)
GO


ALTER TABLE myTable
    ADD  PRIMARY KEY (Column1,Column2)
GO

TCPDF output without saving file

Print the PDF header (using header() function) like: header("Content-type: application/pdf");

and then just echo the content of the PDF file you created (instead of writing it to disk).

how to use php DateTime() function in Laravel 5

If you just want to get the current UNIX timestamp I'd just use time()

$timestamp = time(); 

Media query to detect if device is touchscreen

This solution will work until CSS4 is globally supported by all browsers. When that day comes just use CSS4. but until then, this works for current browsers.

browser-util.js

export const isMobile = {
  android: () => navigator.userAgent.match(/Android/i),
  blackberry: () => navigator.userAgent.match(/BlackBerry/i),
  ios: () => navigator.userAgent.match(/iPhone|iPad|iPod/i),
  opera: () => navigator.userAgent.match(/Opera Mini/i),
  windows: () => navigator.userAgent.match(/IEMobile/i),
  any: () => (isMobile.android() || isMobile.blackberry() || 
  isMobile.ios() || isMobile.opera() || isMobile.windows())
};

onload:

old way:

isMobile.any() ? document.getElementsByTagName("body")[0].className += 'is-touch' : null;

newer way:

isMobile.any() ? document.body.classList.add('is-touch') : null;

The above code will add the "is-touch" class to the body tag if the device has a touch screen. Now any location in your web application where you would have css for :hover you can call body:not(.is-touch) the_rest_of_my_css:hover

for example:

button:hover

becomes:

body:not(.is-touch) button:hover

This solution avoids using modernizer as the modernizer lib is a very big library. If all you're trying to do is detect touch screens, This will be best when the size of the final compiled source is a requirement.

font-weight is not working properly?

Most browsers don't fully support the numerical values for font-weight. Here's a good article about the problem, and even tough it's a little old, it does seem to be correct.

If you need something bolder then you might want to try using a different font that's bolder than your existing one. Naturally, you could probably adjust the font size for a similar effect.

How to create helper file full of functions in react native?

An alternative is to create a helper file where you have a const object with functions as properties of the object. This way you only export and import one object.

helpers.js

const helpers = {
    helper1: function(){

    },
    helper2: function(param1){

    },
    helper3: function(param1, param2){

    }
}

export default helpers;

Then, import like this:

import helpers from './helpers';

and use like this:

helpers.helper1();
helpers.helper2('value1');
helpers.helper3('value1', 'value2');

Is unsigned integer subtraction defined behavior?

With unsigned numbers of type unsigned int or larger, in the absence of type conversions, a-b is defined as yielding the unsigned number which, when added to b, will yield a. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).

Note that unsigned numbers smaller than unsigned int may get promoted to type int before the subtraction, the behavior of a-b will depend upon the size of int.

How do I integrate Ajax with Django applications?

Simple and Nice. You don't have to change your views. Bjax handles all your links. Check this out: Bjax

Usage:

<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />

Finally, include this in the HEAD of your html:

$('a').bjax();

For more settings, checkout demo here: Bjax Demo

How can you dynamically create variables via a while loop?

NOTE: This should be considered a discussion rather than an actual answer.

An approximate approach is to operate __main__ in the module you want to create variables. For example there's a b.py:

#!/usr/bin/env python
# coding: utf-8


def set_vars():
    import __main__
    print '__main__', __main__
    __main__.B = 1

try:
    print B
except NameError as e:
    print e

set_vars()

print 'B: %s' % B

Running it would output

$ python b.py
name 'B' is not defined
__main__ <module '__main__' from 'b.py'>
B: 1

But this approach only works in a single module script, because the __main__ it import will always represent the module of the entry script being executed by python, this means that if b.py is involved by other code, the B variable will be created in the scope of the entry script instead of in b.py itself. Assume there is a script a.py:

#!/usr/bin/env python
# coding: utf-8

try:
    import b
except NameError as e:
    print e

print 'in a.py: B', B

Running it would output

$ python a.py
name 'B' is not defined
__main__ <module '__main__' from 'a.py'>
name 'B' is not defined
in a.py: B 1

Note that the __main__ is changed to 'a.py'.

MySQL joins and COUNT(*) from another table

Your groups_main table has a key column named id. I believe you can only use the USING syntax for the join if the groups_fans table has a key column with the same name, which it probably does not. So instead, try this:

LEFT JOIN groups_fans AS m ON m.group_id = g.id

Or replace group_id with whatever the appropriate column name is in the groups_fans table.

ASP.NET Core - Swashbuckle not creating swagger.json file

I was able to fix and understand my issue when I tried to go to the swagger.json URL location:

https://localhost:XXXXX/swagger/v1/swagger.json

The page will show the error and reason why it is not found.

In my case, I saw that there was a misconfigured XML definition of one of my methods based on the error it returned:

NotSupportedException: HTTP method "GET" & path "api/Values/{id}" overloaded by actions - ...
...
...

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

Numpy - add row to array

If no calculations are necessary after every row, it's much quicker to add rows in python, then convert to numpy. Here are timing tests using python 3.6 vs. numpy 1.14, adding 100 rows, one at a time:

import numpy as np 
from time import perf_counter, sleep

def time_it():
    # Compare performance of two methods for adding rows to numpy array
    py_array = [[0, 1, 2], [0, 2, 0]]
    py_row = [4, 5, 6]
    numpy_array = np.array(py_array)
    numpy_row = np.array([4,5,6])
    n_loops = 100

    start_clock = perf_counter()
    for count in range(0, n_loops):
       numpy_array = np.vstack([numpy_array, numpy_row]) # 5.8 micros
    duration = perf_counter() - start_clock
    print('numpy 1.14 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))

    start_clock = perf_counter()
    for count in range(0, n_loops):
        py_array.append(py_row) # .15 micros
    numpy_array = np.array(py_array) # 43.9 micros       
    duration = perf_counter() - start_clock
    print('python 3.6 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
    sleep(15)

#time_it() prints:

numpy 1.14 takes 5.971 micros per row
python 3.6 takes 0.694 micros per row

So, the simple solution to the original question, from seven years ago, is to use vstack() to add a new row after converting the row to a numpy array. But a more realistic solution should consider vstack's poor performance under those circumstances. If you don't need to run data analysis on the array after every addition, it is better to buffer the new rows to a python list of rows (a list of lists, really), and add them as a group to the numpy array using vstack() before doing any data analysis.

How to clear an EditText on click?

that is called hint in android use android:hint="Enter Name"

What is the best comment in source code you have ever encountered?

/////////////////////////////////////// this is a well commented line

Remove last character from C++ string

With C++11, you don't even need the length/size. As long as the string is not empty, you can do the following:

if (!st.empty())
  st.erase(std::prev(st.end())); // Erase element referred to by iterator one
                                 // before the end

How to increase the gap between text and underlining in CSS

Getting into the details of the visual style of text-decoration:underline is pretty much futile, so you're going to have to go with some kind of hack the removes text-decoration:underline and replaces it with something else until a magical far-distant future version of CSS gives us more control.

This worked for me:

_x000D_
_x000D_
   a {_x000D_
    background-image: linear-gradient(_x000D_
        180deg, rgba(0,0,0,0),_x000D_
        rgba(0,0,0,0) 81%, _x000D_
        #222222 81.1%,_x000D_
        #222222 85%,_x000D_
        rgba(0,0,0,0) 85.1%,_x000D_
        rgba(0,0,0,0)_x000D_
    );_x000D_
    text-decoration: none;_x000D_
}
_x000D_
<a href="#">Lorem ipsum</a> dolor sit amet, <a href="#">consetetur sadipscing</a> elitr, sed diam nonumy eirmod tempor <a href="#">invidunt ut labore.</a>
_x000D_
_x000D_
_x000D_

  • Adjust the % values (81% and 85%) to change how far the line is from the text
  • Adjust the difference between the two % values to change the line thickness
  • adjust the color values (#222222) to change the underline color
  • works with multiple line inline elements
  • works with any background

Here's a version with all the proprietary properties for some backwards compatibility:

a {     
    /* This code generated from: http://colorzilla.com/gradient-editor/ */
    background: -moz-linear-gradient(top,  rgba(0,0,0,0) 0%, rgba(0,0,0,0) 81%, rgba(0,0,0,1) 81.1%, rgba(0,0,0,1) 85%, rgba(0,0,0,0) 85.1%, rgba(0,0,0,0) 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(0,0,0,0)), color-stop(81%,rgba(0,0,0,0)), color-stop(81.1%,rgba(0,0,0,1)), color-stop(85%,rgba(0,0,0,1)), color-stop(85.1%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,0))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* IE10+ */
    background: linear-gradient(to bottom,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* W3C */

    text-decoration: none;
}

Update: SASSY version

I made a scss mixin for this. If you don't use SASS, the regular version above still works great...

@mixin fake-underline($color: #666, $top: 84%, $bottom: 90%) {
    background-image: linear-gradient(
        180deg, rgba(0,0,0,0),
        rgba(0,0,0,0) $top,
        $color $top + 0.1%,
        $color $bottom,
        rgba(0,0,0,0) $bottom + 0.1%,
        rgba(0,0,0,0)
    );
    text-decoration: none;
}

then use it like so:

$blue = #0054a6;
a {
    color: $blue;
    @include fake-underline(lighten($blue,20%));
}
a.thick {
    color: $blue;
    @include fake-underline(lighten($blue,40%), 86%, 99%);
}

Update 2: Descenders Tip

If you have a solid background color, try adding a thin text-stroke or text-shadow in the same color as your background to make the descenders look nice.

Credit

This is simplified version of the technique I originally found at https://eager.io/app/smartunderline, but the article has since been taken down.

Why can't I push to this bare repository?

If you:

 git push origin master

it will push to the bare repo.

It sounds like your alice repo isn't tracking correctly.

cat .git/config

This will show the default remote and branch.

If you

 git push -u origin master

You should start tracking that remote and branch. I'm not sure if that option has always been in git.

Python: Ignore 'Incorrect padding' error when base64 decoding

Just add padding as required. Heed Michael's warning, however.

b64_string += "=" * ((4 - len(b64_string) % 4) % 4) #ugh

Error in Python script "Expected 2D array, got 1D array instead:"?

With one feature my Dataframe list converts to a Series. I had to convert it back to a Dataframe list and it worked.

if type(X) is Series:
    X = X.to_frame()

How to export SQL Server 2005 query to CSV

In management studio, set query options to output to file, and in options->query results set output to file to output using comma as delimiter.

Android disable screen timeout while app is running

Simple add below line into your MainActivity and your App never turn lights off.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

How to JOIN three tables in Codeigniter

   Check bellow code it`s working fine and  common model function also 
    supported more then one join and also supported  multiple where condition
 order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.

   ================================================================
    *Album.php
   //put bellow code in your controller
   =================================================================

    $album_id='';//album id 

   //pass join table value in bellow format
    $join_str[0]['table'] = 'Category';
    $join_str[0]['join_table_id'] = 'Category.cat_id';
    $join_str[0]['from_table_id'] = 'Album.cat_id';
    $join_str[0]['join_type'] = 'left';

    $join_str[1]['table'] = 'Soundtrack';
    $join_str[1]['join_table_id'] = 'Soundtrack.album_id';
    $join_str[1]['from_table_id'] = 'Album.album_id';
    $join_str[1]['join_type'] = 'left';


    $selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";

   $albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
                               //call common model function

    if (!empty($albumData)) {
        print_r($albumData); // print album data
    } 

 =========================================================================
   Common.php
    //put bellow code in your common model file
 ========================================================================

   function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
    $this->db->select($data);
    //if join_str array is not empty then implement the join query
    if (!empty($join_str)) {
        foreach ($join_str as $join) {
            if ($join['join_type'] == '') {
                $this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
            } else {
                $this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
            }
        }
    }

    //condition array pass to where condition
    $this->db->where($condition_array);


    //Setting Limit for Paging
    if ($limit != '' && $offset == 0) {
        $this->db->limit($limit);
    } else if ($limit != '' && $offset != 0) {
        $this->db->limit($limit, $offset);
    }
    //order by query
    if ($sortby != '' && $orderby != '') {
        $this->db->order_by($sortby, $orderby);
    }

    $query = $this->db->get($tablename);
    //if limit is empty then returns total count
    if ($limit == '') {
        $query->num_rows();
    }
    //if limit is not empty then return result array
    return $query->result_array();
}

How to solve a pair of nonlinear equations using Python?

An alternative to fsolve is root:

import numpy as np
from scipy.optimize import root    

def your_funcs(X):

    x, y = X
    # all RHS have to be 0
    f = [x + y**2 - 4,
         np.exp(x) + x * y - 3]

    return f

sol = root(your_funcs, [1.0, 1.0])
print(sol.x)

This will print

[0.62034452 1.83838393]

If you then check

print(your_funcs(sol.x))

you obtain

[4.4508396968012676e-11, -1.0512035686360832e-11]

confirming that the solution is correct.

Sending an HTTP POST request on iOS

Sending an HTTP POST request on iOS (Objective c):

-(NSString *)postexample{

// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

//RESPONDE DATA 
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];

return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}

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

I know this is old post . But I would suggest a bit logical and simpler answer.

for(unsigned int i=0; i < 50; i++)
    {
        for(unsigned int j=0; j < conditionj; j++)
        {
            for(unsigned int k=0; k< conditionk ; k++)
            {
                // If condition is true

                j= conditionj;
               break;
            }
        }
    }

utf-8 special characters not displaying

This is really annoying problem to fix but you can try these.

First of all, make sure the file is actually saved in UTF-8 format.

Then check that you have <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> in your HTML header.

You can also try calling header('Content-Type: text/html; charset=utf-8'); at the beginning of your PHP script or adding AddDefaultCharset UTF-8 to your .htaccess file.

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

How to use: while not in

while not any( x in ('AND','OR','NOT') for x in list)

EDIT:

thank you for the upvotes , but etarion's solution is better since it tests if the words AND, OR, NOT are in the list, that is to say 3 tests.

Mine does as many tests as there are words in list.

EDIT2:

Also there is

while not ('AND' in list,'OR' in list,'NOT' in list)==(False,False,False)

How to send data with angularjs $http.delete() request?

You can do an http DELETE via a URL like /users/1/roles/2. That would be the most RESTful way to do it.

Otherwise I guess you can just pass the user id as part of the query params? Something like

$http.delete('/roles/' + roleid, {params: {userId: userID}}).then...

Execution time of C program

A lot of answers have been suggesting clock() and then CLOCKS_PER_SEC from time.h. This is probably a bad idea, because this is what my /bits/time.h file says:

/* ISO/IEC 9899:1990 7.12.1: <time.h>
The macro `CLOCKS_PER_SEC' is the number per second of the value
returned by the `clock' function. */
/* CAE XSH, Issue 4, Version 2: <time.h>
The value of CLOCKS_PER_SEC is required to be 1 million on all
XSI-conformant systems. */
#  define CLOCKS_PER_SEC  1000000l

#  if !defined __STRICT_ANSI__ && !defined __USE_XOPEN2K
/* Even though CLOCKS_PER_SEC has such a strange value CLK_TCK
presents the real value for clock ticks per second for the system.  */
#   include <bits/types.h>
extern long int __sysconf (int);
#   define CLK_TCK ((__clock_t) __sysconf (2))  /* 2 is _SC_CLK_TCK */
#  endif

So CLOCKS_PER_SEC might be defined as 1000000, depending on what options you use to compile, and thus it does not seem like a good solution.

Access POST values in Symfony2 request object

If you are newbie, welcome to Symfony2, an open-source project so if you want to learn a lot, you can open the source !

From "Form.php" :

getData() getNormData() getViewData()

You can find more details in this file.

Convert String[] to comma separated string in java

Either write a simple method yourself, or use one of the various utilities out there.

Personally I use apache StringUtils (StringUtils.join)

edit: in Java 8, you don't need this at all anymore:

String joined = String.join(",", name);

What's the difference between & and && in MATLAB?

&& and || take scalar inputs and short-circuit always. | and & take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.

See these doc pages for more information.

Temporarily disable all foreign key constraints

Use the built-in sp_msforeachtable stored procedure.

To disable all constraints:

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL";

To enable all constraints:

EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL";

To drop all the tables:

EXEC sp_msforeachtable "DROP TABLE ?";

document.getElementById replacement in angular4 / typescript?

Try this:

TypeScript file code:

(<HTMLInputElement>document.getElementById("name")).value

HTML code:

 <input id="name" type="text" #name /> 

Oracle PL/SQL string compare issue

To the first question:

Probably the message wasn't print out because you have the output turned off. Use these commands to turn it back on:

set serveroutput on
exec dbms_output.enable(1000000);

On the second question:

My PLSQL is quite rusty so I can't give you a full snippet, but you'll need to loop over the result set of the SQL query and CONCAT all the strings together.

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.

sudo apt-get install openjfx

How can I suppress all output from a command using Bash?

In your script you can add the following to the lines that you know are going to give an output:

some_code 2>>/dev/null

Or else you can also try

some_code >>/dev/null

Git diff between current branch and master but not including unmerged master commits

git diff `git merge-base master branch`..branch

Merge base is the point where branch diverged from master.

Git diff supports a special syntax for this:

git diff master...branch

You must not swap the sides because then you would get the other branch. You want to know what changed in branch since it diverged from master, not the other way round.

Loosely related:


Note that .. and ... syntax does not have the same semantics as in other Git tools. It differs from the meaning specified in man gitrevisions.

Quoting man git-diff:

  • git diff [--options] <commit> <commit> [--] [<path>…]

    This is to view the changes between two arbitrary <commit>.

  • git diff [--options] <commit>..<commit> [--] [<path>…]

    This is synonymous to the previous form. If <commit> on one side is omitted, it will have the same effect as using HEAD instead.

  • git diff [--options] <commit>...<commit> [--] [<path>…]

    This form is to view the changes on the branch containing and up to the second <commit>, starting at a common ancestor of both <commit>. "git diff A...B" is equivalent to "git diff $(git-merge-base A B) B". You can omit any one of <commit>, which has the same effect as using HEAD instead.

Just in case you are doing something exotic, it should be noted that all of the <commit> in the above description, except in the last two forms that use ".." notations, can be any <tree>.

For a more complete list of ways to spell <commit>, see "SPECIFYING REVISIONS" section in gitrevisions[7]. However, "diff" is about comparing two endpoints, not ranges, and the range notations ("<commit>..<commit>" and "<commit>...<commit>") do not mean a range as defined in the "SPECIFYING RANGES" section in gitrevisions[7].

GitHub: invalid username or password

When using the https:// URL to connect to your remote repository, then Git will not use SSH as authentication but will instead try a basic authentication over HTTPS. Usually, you would just use the URL without a username, e.g. https://github.com/username/repository.git, and Git would then prompt you to enter both a username (your GitHub username) and your password.

If you use https://[email protected]/username/repository.git, then you have preset the username Git will use for authentication: something. Since you used https://[email protected], Git will try to log in using the git username for which your password of course doesn’t work. So you will have to use your username instead.

The alternative is actually to use SSH for authentication. That way you will avoid having to type your password all the time; and since it already seems to work, that’s what you should be using.

To do that, you need to change your remote URL though, so Git knows that it needs to connect via SSH. The format is then this: [email protected]:username/repository. To update your URL use this command:

git remote set-url origin [email protected]:username/repository

Get changes from master into branch in Git

EDIT:

My answer below documents a way to merge master into aq, where if you view the details of the merge it lists the changes made on aq prior to the merge, not the changes made on master. I've realised that that probably isn't what you want, even if you think it is!

Just:

git checkout aq
git merge master

is fine.

Yes, this simple merge will show that the changes from master were made to aq at that point, not the other way round; but that is okay – since that is what did happen! Later on, when you finally merge your branch into master, that is when a merge will finally show all your changes as made to master (which is exactly what you want, and is the commit where people are going to expect to find that info anyway).

I've checked and the approach below also shows exactly the same changes (all the changes made on aq since the original split between aq and master) as the normal approach above, when you finally merge everything back to master. So I think its only real disadvantage (apart from being over-complex and non-standard... :-/ ) is that if you wind back n recent changes with git reset --hard HEAD~<n> and this goes past the merge, then the version below rolls back down the 'wrong' branch, which you have to fix up by hand (e.g. with git reflog & git reset --hard [sha]).


[So, what I previously thought was that:]

There is a problem with:

git checkout aq
git merge master

because the changes shown in the merge commit (e.g. if you look now or later in Github, Bitbucket or your favourite local git history viewer) are the changes made on master, which may well not be what you want.

On the other hand

git checkout master
git merge aq

shows the changes made in aq, which probably is what you want. (Or, at least, it's often what I want!) But the merge showing the right changes is on the wrong branch!

How to cope?!

The full process, ending up with a merge commit showing the changes made on aq (as per the second merge above), but with the merge affecting the aq branch, is:

git checkout master
git merge aq
git checkout aq
git merge master
git checkout master
git reset --hard HEAD~1
git checkout aq

This: merges aq onto master, fast-forwards that same merge onto aq, undoes it on master, and puts you back on aq again!

I feel like I'm missing something - this seems to be something you'd obviously want, and something that's hard to do.

Also, rebase is NOT equivalent. It loses the timestamps and identity of the commits made on aq, which is also not what I want.

How to get last inserted row ID from WordPress database?

just like this :

global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);

simply your selecting all the rows then order them DESC by id , and displaying only the first

Python 3: EOF when reading a line (Sublime Text 2 is angry)

try:
    value = raw_input()
    do_stuff(value) # next line was found 
except (EOFError):
   break #end of file reached

This seems to be proper usage of raw_input when dealing with the end of the stream of input from piped input. [Refer this post][1]

How should I remove all the leading spaces from a string? - swift

Yet another answer, sometimes the input string can contain more than one space between words. If you need to standardize to have only 1 space between words, try this (Swift 4/5)

let inputString = "  a very     strange   text !    "
let validInput = inputString.components(separatedBy:.whitespacesAndNewlines).filter { $0.count > 0 }.joined(separator: " ")

print(validInput) // "a very strange text !"

Set a default parameter value for a JavaScript function

I find something simple like this to be much more concise and readable personally.

function pick(arg, def) {
   return (typeof arg == 'undefined' ? def : arg);
}

function myFunc(x) {
  x = pick(x, 'my default');
} 

AngularJS sorting by property

It's pretty easy, just do it like this

$scope.props = [{order:"1"},{order:"5"},{order:"2"}]

ng-repeat="prop in props | orderBy:'order'"

JavaScript - Get Browser Height

I prefer the way I just figured out... No JS... 100% HTML & CSS:

(Will center it perfectly in the middle, regardless of the content size.

HTML FILE

<html><head>
<link href="jane.css" rel="stylesheet" />
</head>
<body>
<table id="container">
<tr>
<td id="centerpiece">
123
</td></tr></table>
</body></html>

CSS FILE

#container{
    border:0;
    width:100%;
    height:100%;
}
#centerpiece{
    vertical-align:middle;
    text-align:center;
}

for centering images / div's held within the td, you may wish to try margin:auto; and specify a div dimension instead. -Though, saying that... the 'text-align' property will align much more than just a simple text element.

How to print out more than 20 items (documents) in MongoDB's shell?

You can use it inside of the shell to iterate over the next 20 results. Just type it if you see "has more" and you will see the next 20 items.

Instantly detect client disconnection from server socket

Can't you just use Select?

Use select on a connected socket. If the select returns with your socket as Ready but the subsequent Receive returns 0 bytes that means the client disconnected the connection. AFAIK, that is the fastest way to determine if the client disconnected.

I do not know C# so just ignore if my solution does not fit in C# (C# does provide select though) or if I had misunderstood the context.

How can I listen to the form submit event in javascript?

Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?

var ele = /*Your Form Element*/;
if(ele.addEventListener){
    ele.addEventListener("submit", callback, false);  //Modern browsers
}else if(ele.attachEvent){
    ele.attachEvent('onsubmit', callback);            //Old IE
}

callback is a function that you want to call when the form is being submitted.

About EventTarget.addEventListener, check out this documentation on MDN.

To cancel the native submit event (prevent the form from being submitted), use .preventDefault() in your callback function,

document.querySelector("#myForm").addEventListener("submit", function(e){
    if(!isValid){
        e.preventDefault();    //stop form from submitting
    }
});

Listening to the submit event with libraries

If for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:

  1. jQuery

    $(ele).submit(callback);
    

    Where ele is the form element reference, and callback being the callback function reference. Reference

_x000D_
_x000D_
    <iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>
_x000D_
_x000D_
_x000D_

  1. AngularJS (1.x)

    <form ng-submit="callback()">
    
    $scope.callback = function(){ /*...*/ };
    

    Very straightforward, where $scope is the scope provided by the framework inside your controller. Reference

  2. React

    <form onSubmit={this.handleSubmit}>
    
    class YourComponent extends Component {
        // stuff
    
        handleSubmit(event) {
            // do whatever you need here
    
            // if you need to stop the submit event and 
            // perform/dispatch your own actions
            event.preventDefault();
        }
    
        // more stuff
    }
    

    Simply pass in a handler to the onSubmit prop. Reference

  3. Other frameworks/libraries

    Refer to the documentation of your framework.


Validation

You can always do your validation in JavaScript, but with HTML5 we also have native validation.

<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">

You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.

Demo: http://jsfiddle.net/DerekL/L23wmo1L/

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

In my case I was running under a different user than the one I was expecting.

I had 'DRIVER={SQL Server};SERVER=...;DATABASE=...;Trusted_Connection=false;User Id=XXX;Password=YYY' as the connection string I passed to pypyodbc.connect(), but the connection was still using the credentials of the Windows user that ran the script (I verified this using the SQL Server Profiler and by trying an invalid uid/password combination - which didn't result in an expected error).

I decided not to dig into this further, since switching to this better way of connecting fixed the issue:

conn = pypyodbc.connect(driver='{SQL Server}', server='servername', database='dbname', uid='userName', pwd='Password')

Debug JavaScript in Eclipse

Use the debugging tools supported by the browser. As mentioned above Firebug for Firefox Chrome Developer Tools from Chrome IE Developer for IE.

That way you can detect cross-browser issues. To help reduce the cross-browser issues, use a javascript framework ie jQuery, YUI, moo tools, etc.

Below is a screenshot (javascript-debug.png) of what it looks lime in Firebug.
1) hit 'F12'
2) click the 'Script' tab and 'enable it' (if you are already on your page - hit 'F5' to re-load)
3) next to the 'All' drop down, there will be another dropdown to the right. Select your javascript file from that dropdown.
In the screenshot, I've set a break-point at line 42 by 'left-mouse-click'. This will enable you to break, inspect, watch, etc.

enter image description here

What is the difference between & and && in Java?

It depends on the type of the arguments...

For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.

For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.

For all other argument types and combinations, a compile-time error should occur.

Making an asynchronous task in Flask

You can also try using multiprocessing.Process with daemon=True; the process.start() method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.

I experienced similar problem while working with falcon framework and using daemon process helped.

You'd need to do the following:

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
        target=my_func,
        daemon=True
    )
    heavy_process.start()
    return Response(
        mimetype='application/json',
        status=200
    )

# Define some heavy function
def my_func():
    time.sleep(10)
    print("Process finished")

You should get a response immediately and, after 10s you should see a printed message in the console.

NOTE: Keep in mind that daemonic processes are not allowed to spawn any child processes.

Javascript to sort contents of select element

This will do the trick. Just pass it your select element a la: document.getElementById('lstALL') when you need your list sorted.

function sortSelect(selElem) {
    var tmpAry = new Array();
    for (var i=0;i<selElem.options.length;i++) {
        tmpAry[i] = new Array();
        tmpAry[i][0] = selElem.options[i].text;
        tmpAry[i][1] = selElem.options[i].value;
    }
    tmpAry.sort();
    while (selElem.options.length > 0) {
        selElem.options[0] = null;
    }
    for (var i=0;i<tmpAry.length;i++) {
        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
        selElem.options[i] = op;
    }
    return;
}

How can I use Bash syntax in Makefile targets?

If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

Declaration of Methods should be Compatible with Parent Methods in PHP

I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.

What I though

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

What I've finally done

namespace mycompany\CutreApi;

use \vendor\AwesomeApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new \mycompany\CutreApi\ClassOfVendor();
   }
}

So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.

One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.

Currently done

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function getWhatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.

Hope this can help someone.

How to configure the web.config to allow requests of any length

I had a similar issue trying to deploy an ASP Web Application to IIS 8. To fix it I did as Matt and Leniel suggested above. But also had to configure the Authentication setting of my site to enable Anonymous Authentication. And that Worked for me.

How do I overload the [] operator in C#

The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.

For example, in your case where an int is the key or index:

public int this[int index]
{
    get => GetValue(index);
}

You can also add a set accessor so that the indexer becomes read and write rather than just read-only.

public int this[int index]
{
    get => GetValue(index);
    set => SetValue(index, value);
}

If you want to index using a different type, you just change the signature of the indexer.

public int this[string index]
...

What is the difference between HTML tags and elements?

HTML tags vs. elements vs. attributes

HTML elements

An element in HTML represents some kind of structure or semantics and generally consists of a start tag, content, and an end tag. The following is a paragraph element:

<p>
This is the content of the paragraph element.
</p>

HTML tags

Tags are used to mark up the start and end of an HTML element.

<p></p>

HTML attributes

An attribute defines a property for an element, consists of an attribute/value pair, and appears within the element’s start tag. An element’s start tag may contain any number of space separated attribute/value pairs.

The most popular misuse of the term “tag” is referring to alt attributes as “alt tags”. There is no such thing in HTML. Alt is an attribute, not a tag.

<img src="foobar.gif" alt="A foo can be balanced on a bar by placing its fubar on the bar's foobar.">

Source: 456bereastreet.com: HTML tags vs. elements vs. attributes

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

IE.Document.getElementById("dgTime").getElementsByTagName("a")(0).Click

EDIT: to loop through the collection (items should appear in the same order as they are in the source document)

Dim links, link 

Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")

'For Each loop
For Each link in links
    link.Click
Next link

'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
    links(i).click
Next I

How to query the permissions on an Oracle directory?

With Oracle 11g R2 (at least with 11.2.02) there is a view named datapump_dir_objs.

SELECT * FROM datapump_dir_objs;

The view shows the NAME of the directory object, the PATH as well as READ and WRITE permissions for the currently connected user. It does not show any directory objects which the current user has no permission to read from or write to, though.

Why isn't textarea an input[type="textarea"]?

I realize this is an older post, but thought this might be helpful to anyone wondering the same question:

While the previous answers are no doubt valid, there is a more simple reason for the distinction between textarea and input.

As mentioned previously, HTML is used to describe and give as much semantic structure to web content as possible, including input forms. A textarea may be used for input, however a textarea can also be marked as read only via the readonly attribute. The existence of such an attribute would not make any sense for an input type, and thus the distinction.

Python unittest passing arguments

If you want to use steffens21's approach with unittest.TestLoader, you can modify the original test loader (see unittest.py):

import unittest
from unittest import suite

class TestLoaderWithKwargs(unittest.TestLoader):
    """A test loader which allows to parse keyword arguments to the
       test case class."""
    def loadTestsFromTestCase(self, testCaseClass, **kwargs):
        """Return a suite of all tests cases contained in 
           testCaseClass."""
        if issubclass(testCaseClass, suite.TestSuite):
            raise TypeError("Test cases should not be derived from "\
                            "TestSuite. Maybe you meant to derive from"\ 
                            " TestCase?")
        testCaseNames = self.getTestCaseNames(testCaseClass)
        if not testCaseNames and hasattr(testCaseClass, 'runTest'):
            testCaseNames = ['runTest']

        # Modification here: parse keyword arguments to testCaseClass.
        test_cases = []
        for test_case_name in testCaseNames:
            test_cases.append(testCaseClass(test_case_name, **kwargs))
        loaded_suite = self.suiteClass(test_cases)

        return loaded_suite 

# call your test
loader = TestLoaderWithKwargs()
suite = loader.loadTestsFromTestCase(MyTest, extraArg=extraArg)
unittest.TextTestRunner(verbosity=2).run(suite)

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

In my case I have change the Target name in my Podfile So it's create the same Error for me.

Solution

Just go project-> Build Phase->Link Binary with libraries Remove the old FrameWorks by click on minus button(-) And clean and Run again. It's work me.

enter image description here

Remove Unwanted .framework.

What does "control reaches end of non-void function" mean?

It means it's searching for a function that needs to be completed.

else if(val == sorted[mid]) return mid;

so, remove the if() part and modify the code or add an else() at the end which returns an int.

Django 1.7 - makemigrations not detecting changes

People like me who don't like migrations can use steps below.

  1. Remove changes what you want to sync.
  2. Run python manage.py makemigrations app_label for the initial migration.
  3. Run python manage.py migrate for creating tables before you make changes.
  4. Paste changes which you remove at first step.
  5. Run 2. and 3. steps.

If you confused any of these steps, read the migration files. Change them to correct your schema or remove unwanted files but don't forget to change next migration file's dependencies part ;)

I hope this will help someone in future.

Printing reverse of any String without using any predefined function?

ReverseString.java

public class ReverseString {
    public static void main(String[] args) {
        String str = "Ranga Reddy";
        String revStr = reverseStr(str);
        System.out.println(revStr);     
    }

    // Way1 - Recursive
    public static String reverseStr(String str) {
        char arrStr[] = reverseString(0, str.toCharArray());
        return new String(arrStr);
    }

    private static char[] reverseString(int charIndex, char[] arr) {     
        if (charIndex > arr.length - (charIndex+1)) {
          return arr;
        }

        int startIndex = charIndex;
        int endIndex = arr.length - (charIndex+1);

        char temp = arr[startIndex];        
        arr[startIndex] = arr[endIndex];
        arr[endIndex] = temp;      
        charIndex++;       
        return reverseString(charIndex++, arr);
    }

    // Way2
    private static String strReverse(String str) {
        char ch[] = new char[str.length()];
        for (int i = str.length() - 1, j = 0; i >= 0; i--) {
            ch[j++] = str.charAt(i);
        }
        return new String(ch);
    }
}