Programs & Examples On #Pager

Replace Fragment inside a ViewPager

Replacing fragments in a viewpager is quite involved but is very possible and can look super slick. First, you need to let the viewpager itself handle the removing and adding of the fragments. What is happening is when you replace the fragment inside of SearchFragment, your viewpager retains its fragment views. So you end up with a blank page because the SearchFragment gets removed when you try to replace it.

The solution is to create a listener inside of your viewpager that will handle changes made outside of it so first add this code to the bottom of your adapter.

public interface nextFragmentListener {
    public void fragment0Changed(String newFragmentIdentification);
}

Then you need to create a private class in your viewpager that becomes a listener for when you want to change your fragment. For example you could add something like this. Notice that it implements the interface that was just created. So whenever you call this method, it will run the code inside of the class below.

private final class fragmentChangeListener implements nextFragmentListener {


    @Override
    public void fragment0Changed(String fragment) {
        //I will explain the purpose of fragment0 in a moment
        fragment0 = fragment;
        manager.beginTransaction().remove(fragAt0).commit();

        switch (fragment){
            case "searchFragment":
                fragAt0 = SearchFragment.newInstance(listener);
                break;
            case "searchResultFragment":
                fragAt0 = Fragment_Table.newInstance(listener);
                break;
        }

        notifyDataSetChanged();
    }

There are two main things to point out here:

  1. fragAt0 is a "flexible" fragment. It can take on whatever fragment type you give it. This allows it to become your best friend in changing the fragment at position 0 to the fragment you desire.
  2. Notice the listeners that are placed in the 'newInstance(listener)constructor. These are how you will callfragment0Changed(String newFragmentIdentification)`. The following code shows how you create the listener inside of your fragment.

    static nextFragmentListener listenerSearch;

        public static Fragment_Journals newInstance(nextFragmentListener listener){
                listenerSearch = listener;
                return new Fragment_Journals();
            }
    

You could call the change inside of your onPostExecute

private class SearchAsyncTask extends AsyncTask<Void, Void, Void>{

    protected Void doInBackground(Void... params){
        .
        .//some more operation
        .
    }
    protected void onPostExecute(Void param){

        listenerSearch.fragment0Changed("searchResultFragment");
    }

}

This would trigger the code inside of your viewpager to switch your fragment at position zero fragAt0 to become a new searchResultFragment. There are two more small pieces you would need to add to the viewpager before it became functional.

One would be in the getItem override method of the viewpager.

@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        //this is where it will "remember" which fragment you have just selected. the key is to set a static String fragment at the top of your page that will hold the position that you had just selected.  

        if(fragAt0 == null){

            switch(fragment0){
            case "searchFragment":
                fragAt0 = FragmentSearch.newInstance(listener);
                break;
            case "searchResultsFragment":
                fragAt0 = FragmentSearchResults.newInstance(listener);
                break;
            }
        }
        return fragAt0;
    case 1:
        // Games fragment activity
        return new CreateFragment();

    }

Now without this final piece you would still get a blank page. Kind of lame, but it is an essential part of the viewPager. You must override the getItemPosition method of the viewpager. Ordinarily this method will return POSITION_UNCHANGED which tells the viewpager to keep everything the same and so getItem will never get called to place the new fragment on the page. Here's an example of something you could do

public int getItemPosition(Object object)
{
    //object is the current fragment displayed at position 0.  
    if(object instanceof SearchFragment && fragAt0 instanceof SearchResultFragment){
        return POSITION_NONE;
    //this condition is for when you press back
    }else if{(object instanceof SearchResultFragment && fragAt0 instanceof SearchFragment){
        return POSITION_NONE;
    }
        return POSITION_UNCHANGED
}

Like I said, the code gets very involved, but you basically have to create a custom adapter for your situation. The things I mentioned will make it possible to change the fragment. It will likely take a long time to soak everything in so I would be patient, but it will all make sense. It is totally worth taking the time because it can make a really slick looking application.

Here's the nugget for handling the back button. You put this inside your MainActivity

 public void onBackPressed() {
    if(mViewPager.getCurrentItem() == 0) {
        if(pagerAdapter.getItem(0) instanceof FragmentSearchResults){
            ((Fragment_Table) pagerAdapter.getItem(0)).backPressed();
        }else if (pagerAdapter.getItem(0) instanceof FragmentSearch) {
            finish();
        }
    }

You will need to create a method called backPressed() inside of FragmentSearchResults that calls fragment0changed. This in tandem with the code I showed before will handle pressing the back button. Good luck with your code to change the viewpager. It takes a lot of work, and as far as I have found, there aren't any quick adaptations. Like I said, you are basically creating a custom viewpager adapter, and letting it handle all of the necessary changes using listeners

react hooks useEffect() cleanup for only componentWillUnmount?

Since the cleanup is not dependent on the username, you could put the cleanup in a separate useEffect that is given an empty array as second argument.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
  const [name, setName] = useState("");_x000D_
  const [username, setUsername] = useState("");_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      console.log("effect");_x000D_
    },_x000D_
    [username]_x000D_
  );_x000D_
_x000D_
  useEffect(() => {_x000D_
    return () => {_x000D_
      console.log("cleaned up");_x000D_
    };_x000D_
  }, []);_x000D_
_x000D_
  const handleName = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setName(value);_x000D_
  };_x000D_
_x000D_
  const handleUsername = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setUsername(value);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <div>_x000D_
        <input value={name} onChange={handleName} />_x000D_
        <input value={username} onChange={handleUsername} />_x000D_
      </div>_x000D_
      <div>_x000D_
        <div>_x000D_
          <span>{name}</span>_x000D_
        </div>_x000D_
        <div>_x000D_
          <span>{username}</span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
function App() {_x000D_
  const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(() => {_x000D_
      setShouldRender(false);_x000D_
    }, 5000);_x000D_
  }, []);_x000D_
_x000D_
  return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

How to get just the responsive grid from Bootstrap 3?

Checkout zirafa/bootstrap-grid-only. It contains only the bootstrap grid and responsive utilities that you need (no reset or anything), and simplifies the complexity of working directly with the LESS files.

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

How do I get into a non-password protected Java keystore or change the password?

Mac Mountain Lion has the same password now it uses Oracle.

Why is it common to put CSRF prevention tokens in cookies?

Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.

The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.

The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.

Why use prefixes on member variables in C++ classes

Those conventions are just that. Most shops use code conventions to ease code readability so anyone can easily look at a piece of code and quickly decipher between things such as public and private members.

What's the difference between HEAD^ and HEAD~ in Git?

^ BRANCH Selector
git checkout HEAD^2
Selects the 2nd branch of a (merge) commit by moving onto the selected branch (one step backwards on the commit-tree)

~ COMMIT Selector
git checkout HEAD~2
Moves 2 commits backwards on the default/selected branch


Defining both ~ and ^ relative refs as PARENT selectors is far the dominant definition published everywhere on the internet I have come across so far - including the official Git Book. Yes they are PARENT selectors, but the problem with this "explanation" is that it is completely against our goal: which is how to distinguish the two... :)

The other problem is when we are encouraged to use the ^ BRANCH selector for COMMIT selection (aka HEAD^ === HEAD~).
Again, yes, you can use it this way, but this is not its designed purpose. The ^ BRANCH selector's backwards move behaviour is a side effect not its purpose.

At merged commits only, can a number be assigned to the ^ BRANCH selector. Thus its full capacity can only be utilised where there is a need for selecting among branches. And the most straightforward way to express a selection in a fork is by stepping onto the selected path / branch - that's for the one step backwards on the commit-tree. It is a side effect only, not its main purpose.

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

Nullable DateTime conversion

Cast the null literal: (DateTime?)null or (Nullable<DateTime>)null.

You can also use default(DateTime?) or default(Nullable<DateTime>)

And, as other answers have noted, you can also apply the cast to the DateTime value rather than to the null literal.

EDIT (adapted from my comment to Prutswonder's answer):

The point is that the conditional operator does not consider the type of its assignment target, so it will only compile if there is an implicit conversion from the type of its second operand to the type of its third operand, or from the type of its third operand to the type of its second operand.

For example, this won't compile:

bool b = GetSomeBooleanValue();
object o = b ? "Forty-two" : 42;

Casting either the second or third operand to object, however, fixes the problem, because there is an implicit conversion from int to object and also from string to object:

object o = b ? "Forty-two" : (object)42;

or

object o = b ? (object)"Forty-two" : 42;

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

endsWith in JavaScript

/#$/.test(str)

will work on all browsers, doesn't require monkey patching String, and doesn't require scanning the entire string as lastIndexOf does when there is no match.

If you want to match a constant string that might contain regular expression special characters, such as '$', then you can use the following:

function makeSuffixRegExp(suffix, caseInsensitive) {
  return new RegExp(
      String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
      caseInsensitive ? "i" : "");
}

and then you can use it like this

makeSuffixRegExp("a[complicated]*suffix*").test(str)

Component based game engine design

It is open-source, and available at http://codeplex.com/elephant

Some one’s made a working example of the gpg6-code, you can find it here: http://www.unseen-academy.de/componentSystem.html

or here: http://www.mcshaffry.com/GameCode/thread.php?threadid=732

regards

How to build query string with Javascript

I'm not entirely certain myself, I recall seeing jQuery did it to an extent, but it doesn't handle hierarchical records at all, let alone in a php friendly way.

One thing I do know for certain, is when building URLs and sticking the product into the dom, don't just use string-glue to do it, or you'll be opening yourself to a handy page breaker.

For instance, certain advertising software in-lines the version string from whatever runs your flash. This is fine when its adobes generic simple string, but however, that's very naive, and blows up in an embarrasing mess for people whom have installed Gnash, as gnash'es version string happens to contain a full blown GPL copyright licences, complete with URLs and <a href> tags. Using this in your string-glue advertiser generator, results in the page blowing open and having imbalanced HTML turning up in the dom.

The moral of the story:

   var foo = document.createElement("elementnamehere"); 
   foo.attribute = allUserSpecifiedDataConsideredDangerousHere; 
   somenode.appendChild(foo); 

Not:

   document.write("<elementnamehere attribute=\"" 
        + ilovebrokenwebsites 
        + "\">" 
        + stringdata 
        + "</elementnamehere>");

Google need to learn this trick. I tried to report the problem, they appear not to care.

What is the difference between a process and a thread?

Example 1: A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.

How to get label of select option with jQuery?

$("select#selectbox option:eq(0)").text()

The 0 index in the "option:eq(0)" can be exchanged for whichever indexed option you'd like to retrieve.

Best way to use multiple SSH private keys on one client

For those who are working with I would highly recommend working with EC2 Instance Connect.

Amazon EC2 Instance Connect provides a simple and secure way to connect to your instances using Secure Shell (SSH).

With EC2 Instance Connect, you use AWS Identity and Access Management (IAM) policies and principles to control SSH access to your instances, removing the need to share and manage SSH keys.

After installing the relevant packages (pip install ec2instanceconnectcli or cloning the repo directly) you can connect very easy to multiple EC2 instances by just changing the instance id:

enter image description here


What is happening behind the scenes?

When you connect to an instance using EC2 Instance Connect, the Instance Connect API pushes a one-time-use SSH public key to the instance metadata where it remains for 60 seconds. An IAM policy attached to your IAM user authorizes your IAM user to push the public key to the instance metadata.

The SSH daemon uses AuthorizedKeysCommand and AuthorizedKeysCommandUser, which are configured when Instance Connect is installed, to look up the public key from the instance metadata for authentication, and connects you to the instance.

(*) Amazon Linux 2 2.0.20190618 or later and Ubuntu 20.04 or later comes preconfigured with EC2 Instance Connect. For other supported Linux distributions, you must set up Instance Connect for every instance that will support using Instance Connect. This is a one-time requirement for each instance.


Links:

Set up EC2 Instance Connect
Connect using EC2 Instance Connect
Securing your bastion hosts with Amazon EC2 Instance Connect


The APR based Apache Tomcat Native library was not found on the java.library.path

not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

The native lib is expected in one of the following locations

/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib

and not in

tomcat/lib

The files in tomcat/lib are all jar file and are added by tomcat to the classpath so that they are available to your application.

The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar, for linux it could be a .so file, for windows it could be a .dll file.

Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.

Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.

org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms

EDIT

The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.

If you are troubling with running your servlet then after the run on sever command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.

It should be something like that

http://localhost:8080/<your-context-name>/<your-servlet-name>

EDIT 2

Try to call your servlet using the following url

http://localhost:8080/com.filecounter/FileCounter

Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF.

It is better to configure your servlets there using servlet-name servlet-class and url-mapping. It could look like that:

  <servlet>
    <description></description>
    <display-name>File counter - My first servlet</display-name>
    <servlet-name>file_counter</servlet-name>
    <servlet-class>com.filecounter.FileCounter</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>file_counter</servlet-name>
    <url-pattern>/FileFounter</url-pattern>
  </servlet-mapping>

In eclipse dynamic web project the default context name is the same as your project name.

http://localhost:8080/<your-context-name>/FileCounter

will work too.

What is "pom" packaging in maven?

POM(Project Object Model) is nothing but the automation script for building the project,we can write the automation script in XML, the building script files are named diffrenetly in different Automation tools

like we call build.xml in ANT,pom.xml in MAVEN

MAVEN can packages jars,wars, ears and POM which new thing to all of us

if you want check WHAT IS POM.XML

Can CSS force a line break after each word in an element?

I faced the same problem, and none of the options here helped me. Some mail services do not support specified styles. Here is my version, which solved the problem and works everywhere I checked:

<table>
    <tr>
        <td width="1">Gargantuan Word</td>
    </tr>
</table>

OR using CSS:

<table>
    <tr>
        <td style="width:1px">Gargantuan Word</td>
    </tr>
</table>

Invalid http_host header

The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS setting.

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']

For further reading read from here.

2 "style" inline css img tags?

You don't need 2 style attributes - just use one:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                     style="height:100px;width:100px;" alt="25"/>

Consider, however, using a CSS class instead:

CSS:

.100pxSquare
{
  width: 100px;
  height: 100px;
}

HTML:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                          class="100pxSquare" alt="25"/>

Converting Float to Dollars and Cents

you said that:

`mony = float(1234.5)
print(money)      #output is 1234.5
'${:,.2f}'.format(money)
print(money)

did not work.... Have you coded exactly that way? This should work (see the little difference):

money = float(1234.5)      #next you used format without printing, nor affecting value of "money"
amountAsFormattedString = '${:,.2f}'.format(money)
print( amountAsFormattedString )

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

If you are just interested in the use of Access-Control-Allow-Origin:*

You can do that with this .htaccess file at the site root.

Header set Access-Control-Allow-Origin "*"

Some useful information here: http://enable-cors.org/server_apache.html

How to construct a std::string from a std::vector<char>?

std::string s(v.begin(), v.end());

Where v is pretty much anything iterable. (Specifically begin() and end() must return InputIterators.)

Is Tomcat running?

$ sudo netstat -lpn |grep :8080

To check the port number

$ ps -aef|grep tomcat

Is any tomcat is running under the server.

tsssinfotech-K53U infotech # ps -aef|grep tomcat

root 9586 9567 0 11:35 pts/6 00:00:00 grep --colour=auto tomcat

The ScriptManager must appear before any controls that need it

It simply wants the ASP control on your ASPX page. I usually place mine right under the tag, or inside first Content area in the master's body (if your using a master page)

<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
        <div>
            [Content]
        </div>
    </form>
</body>

Posting array from form

You're already doing that, as a matter of fact. When the form is submitted, the data is passed through a post array ($_POST). Your process.php is receiving that array and redistributing its values as individual variables.

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

I suggest to run in two steps:

1) generate mapping A that maps A:column index->non zero objects

2) for each object i (row) with non-zero occurrences(columns) {k1,..kn} calculate cosine similarity just for elements in the union set A[k1] U A[k2] U.. A[kn]

Assuming a big sparse matrix with high sparsity this will gain a significant boost over brute force

Angular ng-click with call to a controller function not working

Use alias when defining Controller in your angular configuration. For example: NOTE: I'm using TypeScript here

Just take note of the Controller, it has an alias of homeCtrl.

module MongoAngular {
    var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);

    app.config([
        '$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
            $routeProvider
                .when('/Home', {
                    templateUrl: '/PartialViews/Home/home.html',
                    controller: 'HomeController as homeCtrl'
                })
                .otherwise({ redirectTo: '/Home' });
        }])
        .config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {
        restangularProvider.setBaseUrl('/api');
    }]);
} 

And here's the way to use it...

ng-click="homeCtrl.addCustomer(customer)"

Try it.. It might work for you as it worked for me... ;)

Node - how to run app.js?

Assuming I have node and npm properly installed on the machine, I would

  • Download the code
  • Navigate to inside the project folder on terminal, where I would hopefully see a package.json file
  • Do an npm install for installing all the project dependencies
  • Do an npm install -g nodemon for installing all the project dependencies
  • Then npm start OR node app.js OR nodemon app.js to get the app running on local host

Hope this helps someone

use nodemon app.js ( nodemon is a utility that will monitor for any changes in your source and automatically restart your server)

How to execute a stored procedure inside a select query

"Not Possible". You can use a function instead of the stored procedure.

How do you specify a debugger program in Code::Blocks 12.11?

  • In the Code::Blocks IDE, navigate Settings -> Debugger

  • In the tree control at the right, select Common -> GDB/CDB debugger -> Common.

  • Then in the dialog at the left you can enter Executable path and choose Debugger type = GDB or CDB, as well as configuring various other options.

Logical XOR operator in C++?

There is another way to do XOR:

bool XOR(bool a, bool b)
{
    return (a + b) % 2;
}

Which obviously can be demonstrated to work via:

#include <iostream>

bool XOR(bool a, bool b)
{
    return (a + b) % 2;
}

int main()
{
    using namespace std;
    cout << "XOR(true, true):\t" << XOR(true, true) << endl
         << "XOR(true, false):\t" << XOR(true, false) << endl
         << "XOR(false, true):\t" << XOR(false, true) << endl
         << "XOR(false, false):\t" << XOR(false, false) << endl
         << "XOR(0, 0):\t\t" << XOR(0, 0) << endl
         << "XOR(1, 0):\t\t" << XOR(1, 0) << endl
         << "XOR(5, 0):\t\t" << XOR(5, 0) << endl
         << "XOR(20, 0):\t\t" << XOR(20, 0) << endl
         << "XOR(6, 6):\t\t" << XOR(5, 5) << endl
         << "XOR(5, 6):\t\t" << XOR(5, 6) << endl
         << "XOR(1, 1):\t\t" << XOR(1, 1) << endl;
    return 0;
}

How to convert string to datetime format in pandas python?

Approach: 1

Given original string format: 2019/03/04 00:08:48

you can use

updated_df = df['timestamp'].astype('datetime64[ns]')

The result will be in this datetime format: 2019-03-04 00:08:48

Approach: 2

updated_df = df.astype({'timestamp':'datetime64[ns]'})

Can Flask have optional URL parameters?

@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
   #
   pass

What are the different NameID format used for?

About this I think you can reference to http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html.

Here're my understandings about this, with the Identity Federation Use Case to give a details for those concepts:

  • Persistent identifiers-

IdP provides the Persistent identifiers, they are used for linking to the local accounts in SPs, but they identify as the user profile for the specific service each alone. For example, the persistent identifiers are kind of like : johnForAir, jonhForCar, johnForHotel, they all just for one specified service, since it need to link to its local identity in the service.

  • Transient identifiers-

Transient identifiers are what IdP tell the SP that the users in the session have been granted to access the resource on SP, but the identities of users do not offer to SP actually. For example, The assertion just like “Anonymity(Idp doesn’t tell SP who he is) has the permission to access /resource on SP”. SP got it and let browser to access it, but still don’t know Anonymity' real name.

  • unspecified identifiers-

The explanation for it in the spec is "The interpretation of the content of the element is left to individual implementations". Which means IdP defines the real format for it, and it assumes that SP knows how to parse the format data respond from IdP. For example, IdP gives a format data "UserName=XXXXX Country=US", SP get the assertion, and can parse it and extract the UserName is "XXXXX".

How to create query parameters in Javascript?

I have improved the function of shog9`s to handle array values

function encodeQueryData(data) {
    const ret = [];
    for (let d in data) {
        if (typeof data[d] === 'object' || typeof data[d] === 'array') {
            for (let arrD in data[d]) {
                ret.push(`${encodeURIComponent(d)}[]=${encodeURIComponent(data[d][arrD])}`)
            }
        } else if (typeof data[d] === 'null' || typeof data[d] === 'undefined') {
            ret.push(encodeURIComponent(d))
        } else {
            ret.push(`${encodeURIComponent(d)}=${encodeURIComponent(data[d])}`)
        }

    }
    return ret.join('&');
}

Example

let data = {
  user: 'Mark'
  fruits: ['apple', 'banana']
}

encodeQueryData(data) // user=Mark&fruits[]=apple&fruits[]=banana

Why am I getting "void value not ignored as it ought to be"?

"void value not ignored as it ought to be" this error occurs when function like srand(time(NULL)) does not return something and you are treating it as it is returning something. As in case of pop() function in queue ,if you will store the popped element in a variable you will get the same error because it does not return anything.

Determining Referer in PHP

What I have found best is a CSRF token and save it in the session for links where you need to verify the referrer.

So if you are generating a FB callback then it would look something like this:

$token = uniqid(mt_rand(), TRUE);
$_SESSION['token'] = $token;
$url = "http://example.com/index.php?token={$token}";

Then the index.php will look like this:

if(empty($_GET['token']) || $_GET['token'] !== $_SESSION['token'])
{
    show_404();
} 

//Continue with the rest of code

I do know of secure sites that do the equivalent of this for all their secure pages.

Full path from file input using jQuery

You can't: It's a security feature in all modern browsers.

For IE8, it's off by default, but can be reactivated using a security setting:

When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.

The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.

In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.

More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.

How to upload a file in Django?

Extending on Henry's example:

import tempfile
import shutil

FILE_UPLOAD_DIR = '/home/imran/uploads'

def handle_uploaded_file(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=FILE_UPLOAD_DIR)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
    return filepath

You can call this handle_uploaded_file function from your view with the uploaded file object. This will save the file with a unique name (prefixed with filename of the original uploaded file) in filesystem and return the full path of saved file. You can save the path in database, and do something with the file later.

How to disable the ability to select in a DataGridView?

I'd go with this:

private void myDataGridView_SelectionChanged(Object sender, EventArgs e)
{
    dgvSomeDataGridView.ClearSelection();  
}

I don't agree with the broad assertion that no DataGridView should be unselectable. Some UIs are built for tools or touchsreens, and allowing a selection misleads the user to think that selecting will actually get them somewhere.

Setting ReadOnly = true on the control has no impact on whether a cell or row can be selected. And there are visual and functional downsides to setting Enabled = false.

Another option is to set the control selected colors to be exactly what the non-selected colors are, but if you happen to be manipulating the back color of the cell, then this method yields some nasty results as well.

window.print() not working in IE

This worked for me, it works in firefox, ie and chrome.

    var content = "This is a test Message";

    var contentHtml = [
        '<div><b>',
        'TestReport',
        '<button style="float:right; margin-right:10px;"',
        'id="printButton" onclick="printDocument()">Print</button></div>',
        content
    ].join('');

    var printWindow = window.open();

    printWindow.document.write('<!DOCTYPE HTML><html><head<title>Reports</title>',
        '<script>function printDocument() {',
        'window.focus();',
        'window.print();',
        'window.close();',
        '}',
        '</script>');

    printWindow.document.write("stylesheet link here");

    printWindow.document.write('</head><body>');
    printWindow.document.write(contentHtml);
    printWindow.document.write('</body>');
    printWindow.document.write('</html>');
    printWindow.document.close();

How to store decimal values in SQL Server?

For most of the time, I use decimal(9,2) which takes the least storage (5 bytes) in sql decimal type.


Precision => Storage bytes

  • 1 - 9 => 5
  • 10-19 => 9
  • 20-28 => 13
  • 29-38 => 17

It can store from 0 up to 9 999 999.99 (7 digit infront + 2 digit behind decimal point = total 9 digit), which is big enough for most of the values.

Can Selenium interact with an existing browser session?

I'm using Rails + Cucumber + Selenium Webdriver + PhantomJS, and I've been using a monkey-patched version of Selenium Webdriver, which keeps PhantomJS browser open between test runs. See this blog post: http://blog.sharetribe.com/2014/04/07/faster-cucumber-startup-keep-phantomjs-browser-open-between-tests/

See also my answer to this post: How do I execute a command on already opened browser from a ruby file

Is there a destructor for Java?

If it's just memory you are worried about, don't. Just trust the GC it does a decent job. I actually saw something about it being so efficient that it could be better for performance to create heaps of tiny objects than to utilize large arrays in some instances.

calling another method from the main method in java

This is a fundamental understanding in Java, but can be a little tricky to new programmers. Do a little research on the difference between a static and instance method. The basic difference is the instance method do() is only accessible to a instance of the class foo.

You must instantiate (create an instance of) the class, creating an object, that you use to call the instance method.

I have included your example with a couple comments and example.

public class SomeName {

//this is a static method and cannot call an instance method without a object
public static void main(String[] args){

    // can't do this from this static method, no object reference
    // someMethod();

    //create instance of object
    SomeName thisObj = new SomeName();
    //call instance method using object
    thisObj.someMethod();
}

//instance method
public void someMethod(){
    System.out.print("some message...");
}

}// end class SomeName

How to run two jQuery animations simultaneously?

That would run simultaneously yes. what if you wanted to run two animations on the same element simultaneously ?

$(function () {
    $('#first').animate({ width: '200px' }, 200);
    $('#first').animate({ marginTop: '50px' }, 200);
});

This ends up queuing the animations. to get to run them simultaneously you would use only one line.

$(function () {
    $('#first').animate({ width: '200px', marginTop:'50px' }, 200);
});

Is there any other way to run two different animation on the same element simultaneously ?

How to use Oracle's LISTAGG function with a unique filter?

I don't have an 11g instance available today but could you not use:

SELECT group_id,
       LISTAGG(name, ',') WITHIN GROUP (ORDER BY name) AS names
  FROM (
       SELECT UNIQUE
              group_id,
              name
         FROM demotable
       )
 GROUP BY group_id

How to install mechanize for Python 2.7?

pip install mechanize

mechanize supports only python 2.

For python3 refer https://stackoverflow.com/a/31774959/4773973 for alternatives.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

My solution:

1) create a temp ArrayList.

2) do your heavy works (sqlite row fetch , ...) in doInBackground method and add items to the temp arraylist.

3) add all items from temp araylist to your listview's arraylist in onPostExecute method.

note: you may want to delete some items from listview and also delete from sqlite database and maybe delete some files related to items from sdcard , just remove items from database and remove their related files and add them to temp arraylist in background thread. then in UI thread delete items existing in temp arraylist from the listview's arraylist.

Hope this helps.

Convert seconds to HH-MM-SS with JavaScript?

Have you tried adding seconds to a Date object?

Date.prototype.addSeconds = function(seconds) {
    this.setSeconds(this.getSeconds() + seconds);
};
var dt = new Date();
dt.addSeconds(1234);

A sample: https://jsfiddle.net/j5g2p0dc/5/

Updated: Sample link was missing so I created a new one.

php static function

Entire difference is, you don't get $this supplied inside the static function. If you try to use $this, you'll get a Fatal error: Using $this when not in object context.

Well, okay, one other difference: an E_STRICT warning is generated by your first example.

PHP Composer update "cannot allocate memory" error (using Laravel 4)

Make a swap and run composer command again. I hope it'll work for you.

 $ dd if=/dev/zero of=/swapfile bs=1024 count=512k
 $ mkswap /swapfile
 $ swapon /swapfile
 $ echo "/swapfile       none    swap    sw      0       0 " >> /etc/fstab
 $ echo 0 > /proc/sys/vm/swappiness
 $ chown root:root /swapfile
 $ chmod 0600 /swapfile

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

How to properly override clone method?

There are two cases in which the CloneNotSupportedException will be thrown:

  1. The class being cloned does not implemented Cloneable (assuming that the actual cloning eventually defers to Object's clone method). If the class you are writing this method in implements Cloneable, this will never happen (since any sub-classes will inherit it appropriately).
  2. The exception is explicitly thrown by an implementation - this is the recommended way to prevent clonability in a subclass when the superclass is Cloneable.

The latter case cannot occur in your class (as you're directly calling the superclass' method in the try block, even if invoked from a subclass calling super.clone()) and the former should not since your class clearly should implement Cloneable.

Basically, you should log the error for sure, but in this particular instance it will only happen if you mess up your class' definition. Thus treat it like a checked version of NullPointerException (or similar) - it will never be thrown if your code is functional.


In other situations you would need to be prepared for this eventuality - there is no guarantee that a given object is cloneable, so when catching the exception you should take appropriate action depending on this condition (continue with the existing object, take an alternative cloning strategy e.g. serialize-deserialize, throw an IllegalParameterException if your method requires the parameter by cloneable, etc. etc.).

Edit: Though overall I should point out that yes, clone() really is difficult to implement correctly and difficult for callers to know whether the return value will be what they want, doubly so when you consider deep vs shallow clones. It's often better just to avoid the whole thing entirely and use another mechanism.

Postgresql 9.2 pg_dump version mismatch

Download the appropriate postgres version here:

https://www.postgresql.org/download/

Make sure to run the following commands (the postgresql.org/download URL will generate the specific URL for you to use; the one I use below is just an example for centos 7) as sudo:

sudo yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo yum install postgresql11-server

your pg_dump version should now be updated, verify with pg_dump -V

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SQL Management Studio you can:

  1. Right click on the result set grid, select 'Save Result As...' and save in.

  2. On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.

If you need to automate it, use bcp tool.

How to send and receive JSON data from a restful webservice using Jersey API

The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.0</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>   


    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.25</version>
    </dependency>

Finding which process was killed by Linux OOM killer

Try this out:

grep "Killed process" /var/log/syslog

Get file name from a file location in Java

Apache Commons IO provides the FilenameUtils class which gives you a pretty rich set of utility functions for easily obtaining the various components of filenames, although The java.io.File class provides the basics.

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

Error during SSL Handshake with remote server

The comment by MK pointed me in the right direction.

In the case of Apache 2.4 and up, there are different defaults and a new directive.

I am running Apache 2.4.6, and I had to add the following directives to get it working:

SSLProxyEngine on
SSLProxyVerify none 
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off

Convert array to string in NodeJS

toString is a method, so you should add parenthesis () to make the function call.

> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'

Besides, if you want to use strings as keys, then you should consider using a Object instead of Array, and use JSON.stringify to return a string.

> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'

How to include external Python code to use in other files?

If you use:

import Math

then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.

If you want to import a module's functions without having to prefix them, you must explicitly name them, like:

from Math import Calculate, Add, Subtract

Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:

from Math import *

However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.

How to remove all white spaces in java

You can use a regular expression to delete white spaces , try that snippet:

Scanner scan = new Scanner(System.in);
    System.out.println(scan.nextLine().replaceAll(" ", ""));

Open Excel file for reading with VBA without display

To open a workbook as hidden in the existing instance of Excel, use following:

    Application.ScreenUpdating = False
    Workbooks.Open Filename:=FilePath, UpdateLinks:=True, ReadOnly:=True
    ActiveWindow.Visible = False
    ThisWorkbook.Activate
    Application.ScreenUpdating = True

Write applications in C or C++ for Android?

Google has released a Native Development Kit (NDK) (according to http://www.youtube.com/watch?v=Z5whfaLH1-E at 00:07:30).

Hopefully the information will be updated on the google groups page (http://groups.google.com/group/android-ndk), as it says it hasn't been released yet.

I'm not sure where to get a simple download for it, but I've heard that you can get a copy of the NDK from Google's Git repository under the donut branch.

Capturing count from an SQL query

You'll get converting errors with:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

Use instead:

string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
    found = true; 
} else {
    found = false; 
}

Simplest two-way encryption using PHP

IMPORTANT this answer is valid only for PHP 5, in PHP 7 use built-in cryptographic functions.

Here is simple but secure enough implementation:

  • AES-256 encryption in CBC mode
  • PBKDF2 to create encryption key out of plain-text password
  • HMAC to authenticate the encrypted message.

Code and examples are here: https://stackoverflow.com/a/19445173/1387163

How to echo or print an array in PHP?

This will do

foreach($results['data'] as $result) {
    echo $result['type'], '<br>';
}

MySQL select where column is not empty

select phone, phone2 from jewishyellow.users 
where phone like '813%' and phone2 is not null

Disable pasting text into HTML form

With Jquery you can do this with one simple codeline.

HTML:

<input id="email" name="email">

Code:

$(email).on('paste', false);

JSfiddle: https://jsfiddle.net/ZjR9P/2/

How do I merge a git tag onto a branch

This is the only comprehensive and reliable way I've found to do this.

Assume you want to merge "tag_1.0" into "mybranch".

    $git checkout tag_1.0 (will create a headless branch)
    $git branch -D tagbranch (make sure this branch doesn't already exist locally)
    $git checkout -b tagbranch
    $git merge -s ours mybranch
    $git commit -am "updated mybranch with tag_1.0"
    $git checkout mybranch
    $git merge tagbranch

MySQL INSERT INTO ... VALUES and SELECT

just use a subquery right there like:

INSERT INTO table1 VALUES ("A string", 5, (SELECT ...)).

Execute SQL script from command line

Feedback Guys, first create database example live; before execute sql file below.

sqlcmd -U SA -P yourPassword -S YourHost -d live -i live.sql

Git will not init/sync/update new submodules

Sort of magically, but today I ran git submodule init followed by git submodule sync followed by git submodule update and it started pulling my submodules... Magic? Perhaps! This is truly one of the most annoying experiences with Git…

Scratch that. I actually got it working by doing git submodule update --init --recursive. Hope this helps.

PS: Make sure you are in the root git directory, not the submodule's.

How to export data as CSV format from SQL Server using sqlcmd?

This answer builds on the solution from @iain-elder, which works well except for the large database case (as pointed out in his solution). The entire table needs to fit in your system's memory, and for me this was not an option. I suspect the best solution would use the System.Data.SqlClient.SqlDataReader and a custom CSV serializer (see here for an example) or another language with an MS SQL driver and CSV serialization. In the spirit of the original question which was probably looking for a no dependency solution, the PowerShell code below worked for me. It is very slow and inefficient especially in instantiating the $data array and calling Export-Csv in append mode for every $chunk_size lines.

$chunk_size = 10000
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = "SELECT * FROM <TABLENAME>"
$command.Connection = $connection
$connection.open()
$reader = $command.ExecuteReader()

$read = $TRUE
while($read){
    $counter=0
    $DataTable = New-Object System.Data.DataTable
    $first=$TRUE;
    try {
        while($read = $reader.Read()){

            $count = $reader.FieldCount
            if ($first){
                for($i=0; $i -lt $count; $i++){
                    $col = New-Object System.Data.DataColumn $reader.GetName($i)
                    $DataTable.Columns.Add($col)
                }
                $first=$FALSE;
            }

            # Better way to do this?
            $data=@()
            $emptyObj = New-Object System.Object
            for($i=1; $i -le $count; $i++){
                $data +=  $emptyObj
            }

            $reader.GetValues($data) | out-null
            $DataRow = $DataTable.NewRow()
            $DataRow.ItemArray = $data
            $DataTable.Rows.Add($DataRow)
            $counter += 1
            if ($counter -eq $chunk_size){
                break
            }
        }
        $DataTable | Export-Csv "output.csv" -NoTypeInformation -Append
    }catch{
        $ErrorMessage = $_.Exception.Message
        Write-Output $ErrorMessage
        $read=$FALSE
        $connection.Close()
        exit
    }
}
$connection.close()

How do you enable auto-complete functionality in Visual Studio C++ express edition?

VS is kinda funny about C++ and IntelliSense. There are times it won't notice that it's supposed to be popping up something. This is due in no small part to the complexity of the language, and all the compiling (or at least parsing) that'd need to go on in order to make it better.

If it doesn't work for you at all, and it used to, and you've checked the VS options, maybe this can help.

How to parse a String containing XML in Java and retrieve the value of the root node?

There is doing XML reading right, or doing the dodgy just to get by. Doing it right would be using proper document parsing.

Or... dodgy would be using custom text parsing with either wisuzu's response or using regular expressions with matchers.

How can I get relative path of the folders in my android project?

Are you looking for the root folder of the application? Then I would use

 String path = getClass().getClassLoader().getResource(".").getPath();

to actually "find out where I am".

Can I hide/show asp:Menu items based on role?

To remove a MenuItem from an ASP.net NavigationMenu by Value:

public static void RemoveMenuItemByValue(MenuItemCollection items, String value)
{
   MenuItem itemToRemove = null;

   //Breadth first, look in the collection
   foreach (MenuItem item in items)
   {
      if (item.Value == value)
      {
          itemToRemove = item;
          break;
      }
   }

   if (itemToRemove != null)
   {
      items.Remove(itemToRemove);
      return;
   }


   //Search children
   foreach (MenuItem item in items)
   {
       RemoveMenuItemByValue(item.ChildItems, value);
   }
}

and helper extension:

public static RemoveMenuItemByValue(this NavigationMenu menu, String value)
{
   RemoveMenuItemByValue(menu.Items, value);
}

and sample usage:

navigationMenu.RemoveMenuItemByValue("UnitTests");

Note: Any code is released into the public domain. No attribution required.

Proper use of 'yield return'

As a conceptual example for understanding when you ought to use yield, let's say the method ConsumeLoop() processes the items returned/yielded by ProduceList():

void ConsumeLoop() {
    foreach (Consumable item in ProduceList())        // might have to wait here
        item.Consume();
}

IEnumerable<Consumable> ProduceList() {
    while (KeepProducing())
        yield return ProduceExpensiveConsumable();    // expensive
}

Without yield, the call to ProduceList() might take a long time because you have to complete the list before returning:

//pseudo-assembly
Produce consumable[0]                   // expensive operation, e.g. disk I/O
Produce consumable[1]                   // waiting...
Produce consumable[2]                   // waiting...
Produce consumable[3]                   // completed the consumable list
Consume consumable[0]                   // start consuming
Consume consumable[1]
Consume consumable[2]
Consume consumable[3]

Using yield, it becomes rearranged, sort of interleaved:

//pseudo-assembly
Produce consumable[0]
Consume consumable[0]                   // immediately yield & Consume
Produce consumable[1]                   // ConsumeLoop iterates, requesting next item
Consume consumable[1]                   // consume next
Produce consumable[2]
Consume consumable[2]                   // consume next
Produce consumable[3]
Consume consumable[3]                   // consume next

And lastly, as many before have already suggested, you should use Version 2 because you already have the completed list anyway.

Aggregate a dataframe on a given column and display another column

Here is a solution using the plyr package.

The following line of code essentially tells ddply to first group your data by Group, and then within each group returns a subset where the Score equals the maximum score in that group.

library(plyr)
ddply(data, .(Group), function(x)x[x$Score==max(x$Score), ])

  Group Score Info
1     1     3    c
2     2     4    d

And, as @SachaEpskamp points out, this can be further simplified to:

ddply(df, .(Group), function(x)x[which.max(x$Score), ])

(which also has the advantage that which.max will return multiple max lines, if there are any).

ImportError: No module named pythoncom

You should be using pip to install packages, since it gives you uninstall capabilities.

Also, look into virtualenv. It works well with pip and gives you a sandbox so you can explore new stuff without accidentally hosing your system-wide install.

Position Absolute + Scrolling

I ran into this situation and creating an extra div was impractical. I ended up just setting the full-height div to height: 10000%; overflow: hidden;

Clearly not the cleanest solution, but it works really fast.

Escape double quote in VB string

Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.

Option Explicit

Private Const SEE_MASK_DEFAULT = &H0

Public Enum EShellShowConstants
        essSW_HIDE = 0
        essSW_SHOWNORMAL = 1
        essSW_SHOWMINIMIZED = 2
        essSW_MAXIMIZE = 3
        essSW_SHOWMAXIMIZED = 3
        essSW_SHOWNOACTIVATE = 4
        essSW_SHOW = 5
        essSW_MINIMIZE = 6
        essSW_SHOWMINNOACTIVE = 7
        essSW_SHOWNA = 8
        essSW_RESTORE = 9
        essSW_SHOWDEFAULT = 10
End Enum

Private Type SHELLEXECUTEINFO
        cbSize        As Long
        fMask         As Long
        hwnd          As Long
        lpVerb        As String
        lpFile        As String
        lpParameters  As String
        lpDirectory   As String
        nShow         As Long
        hInstApp      As Long
        lpIDList      As Long     'Optional
        lpClass       As String   'Optional
        hkeyClass     As Long     'Optional
        dwHotKey      As Long     'Optional
        hIcon         As Long     'Optional
        hProcess      As Long     'Optional
End Type

Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long

Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
    Dim SEI As SHELLEXECUTEINFO

    On Error GoTo Err

    'Fill the SEI structure
    With SEI
        .cbSize = Len(SEI)                  ' Bytes of the structure
        .fMask = SEE_MASK_DEFAULT           ' Check MSDN for more info on Mask
        .lpFile = FilePath                  ' Program Path
        .nShow = ShellShowType              ' How the program will be displayed
        .lpDirectory = PathGetFolder(FilePath)
        .lpParameters = EXEParameters       ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
        .hwnd = hWndOwner                   ' Owner window handle

        ' Determine launch type (would recommend checking for Vista or greater here also)
        If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
            .lpVerb = "runas"
        Else
            .lpVerb = "Open"
        End If
    End With

     ExecuteProcess = ShellExecuteEx(SEI)   ' Execute the program, return success or failure

    Exit Function
Err:
    ' TODO: Log Error
    ExecuteProcess = False
End Function

Private Function PathGetFolder(psPath As String) As String
    On Error Resume Next
    Dim lPos As Long
    lPos = InStrRev(psPath, "\")
    PathGetFolder = Left$(psPath, lPos - 1)
End Function

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

Looking at the Volley perspective here are some advantages for your requirement:

Volley, on one hand, is totally focused on handling individual, small HTTP requests. So if your HTTP request handling has some quirks, Volley probably has a hook for you. If, on the other hand, you have a quirk in your image handling, the only real hook you have is ImageCache. "It’s not nothing, but it’s not a lot!, either". but it has more other advantages like Once you define your requests, using them from within a fragment or activity is painless unlike parallel AsyncTasks

Pros and cons of Volley:

So what’s nice about Volley?

  • The networking part isn’t just for images. Volley is intended to be an integral part of your back end. For a fresh project based off of a simple REST service, this could be a big win.

  • NetworkImageView is more aggressive about request cleanup than Picasso, and more conservative in its GC usage patterns. NetworkImageView relies exclusively on strong memory references, and cleans up all request data as soon as a new request is made for an ImageView, or as soon as that ImageView moves offscreen.

  • Performance. This post won’t evaluate this claim, but they’ve clearly taken some care to be judicious in their memory usage patterns. Volley also makes an effort to batch callbacks to the main thread to reduce context switching.

  • Volley apparently has futures, too. Check out RequestFuture if you’re interested.

  • If you’re dealing with high-resolution compressed images, Volley is the only solution here that works well.

  • Volley can be used with Okhttp (New version of Okhttp supports NIO for better performance )

  • Volley plays nice with the Activity life cycle.

Problems With Volley:
Since Volley is new, few things are not supported yet, but it's fixed.

  1. Multipart Requests (Solution: https://github.com/vinaysshenoy/enhanced-volley)

  2. status code 201 is taken as an error, Status code from 200 to 207 are successful responses now.(Fixed: https://github.com/Vinayrraj/CustomVolley)

    Update: in latest release of Google volley, the 2XX Status codes bug is fixed now!Thanks to Ficus Kirkpatrick!

  3. it's less documented but many of the people are supporting volley in github, java like documentation can be found here. On android developer website, you may find guide for Transmitting Network Data Using Volley. And volley source code can be found at Google Git

  4. To solve/change Redirect Policy of Volley Framework use Volley with OkHTTP (CommonsWare mentioned above)

Also you can read this Comparing Volley's image loading with Picasso

Retrofit:

It's released by Square, This offers very easy to use REST API's (Update: Voila! with NIO support)

Pros of Retrofit:

  • Compared to Volley, Retrofit's REST API code is brief and provides excellent API documentation and has good support in communities! It is very easy to add into the projects.

  • We can use it with any serialization library, with error handling.

Update: - There are plenty of very good changes in Retrofit 2.0.0-beta2

  • version 1.6 of Retrofit with OkHttp 2.0 is now dependent on Okio to support java.io and java.nio which makes it much easier to access, store and process your data using ByteString and Buffer to do some clever things to save CPU and memory. (FYI: This reminds me of the Koush's OIN library with NIO support!) We can use Retrofit together with RxJava to combine and chain REST calls using rxObservables to avoid ugly callback chains (to avoid callback hell!!).

Cons of Retrofit for version 1.6:

  • Memory related error handling functionality is not good (in older versions of Retrofit/OkHttp) not sure if it's improved with the Okio with Java NIO support.

  • Minimum threading assistance can result call back hell if we use this in an improper way.

(All above Cons have been solved in the new version of Retrofit 2.0 beta)

========================================================================

Update:

Android Async vs Volley vs Retrofit performance benchmarks (milliseconds, lower value is better):

Android Async vs Volley vs Retrofit performance benchmarks

(FYI above Retrofit Benchmarks info will improve with java NIO support because the new version of OKhttp is dependent on NIO Okio library)

In all three tests with varying repeats (1 – 25 times), Volley was anywhere from 50% to 75% faster. Retrofit clocked in at an impressive 50% to 90% faster than the AsyncTasks, hitting the same endpoint the same number of times. On the Dashboard test suite, this translated into loading/parsing the data several seconds faster. That is a massive real-world difference. In order to make the tests fair, the times for AsyncTasks/Volley included the JSON parsing as Retrofit does it for you automatically.

RetroFit Wins in benchmark test!

In the end, we decided to go with Retrofit for our application. Not only is it ridiculously fast, but it meshes quite well with our existing architecture. We were able to make a parent Callback Interface that automatically performs error handling, caching, and pagination with little to no effort for our APIs. In order to merge in Retrofit, we had to rename our variables to make our models GSON compliant, write a few simple interfaces, delete functions from the old API, and modify our fragments to not use AsyncTasks. Now that we have a few fragments completely converted, it’s pretty painless. There were some growing pains and issues that we had to overcome, but overall it went smoothly. In the beginning, we ran into a few technical issues/bugs, but Square has a fantastic Google+ community that was able to help us through it.

When to use Volley?!

We can use Volley when we need to load images as well as consuming REST APIs!, network call queuing system is needed for many n/w request at the same time! also Volley has better memory related error handling than Retrofit!

OkHttp can be used with Volley, Retrofit uses OkHttp by default! It has SPDY support, connection pooling, disk caching, transparent compression! Recently, it has got some support of java NIO with Okio library.

Source, credit: volley-vs-retrofit by Mr. Josh Ruesch

Note: About streaming it depends on what type of streaming you want like RTSP/RTCP.

Differences between key, superkey, minimal superkey, candidate key and primary key

Superkey

A superkey is a combination of attributes that can be uniquely used to identify a 
database record. A table might have many superkeys.Candidate keys are a special subset
of superkeys that do not have any extraneous information in them.

Examples: Imagine a table with the fields <Name>, <Age>, <SSN> and <Phone Extension>.
This table has many possible superkeys. Three of these are <SSN>, <Phone Extension, Name>
and <SSN, Name>.Of those listed, only <SSN> is a **candidate key**, as the others
contain information not necessary to uniquely identify records.

How to format background color using twitter bootstrap?

Bootstrap default "contextual backgrounds" helper classes to change the background color:

.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger

If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below

.bg-pink
{
  background-color: #CE6F9E;
}

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

In the first example, you are reassigning the variable a, while in the second one you are modifying the data in-place, using the += operator.

See the section about 7.2.1. Augmented assignment statements :

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

+= operator calls __iadd__. This function makes the change in-place, and only after its execution, the result is set back to the object you are "applying" the += on.

__add__ on the other hand takes the parameters and returns their sum (without modifying them).

Retrieve WordPress root directory path?

There are 2 answers for this question Url & directory. Either way, the elegant way would be to define two constants for later use.

define (ROOT_URL, get_site_url() );
define (ROOT_DIR, get_theme_root() );

Time part of a DateTime Field in SQL

This should strip away the date part:

select convert(datetime,convert(float, getdate()) - convert(int,getdate())), getdate()

and return a datetime with a default date of 1900-01-01.

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

Text Editor For Linux (Besides Vi)?

Best one besides Vi? Vim.

iterating and filtering two lists using java 8

See below, would welcome anyones feedback on the below code.

not common between two arrays:

List<String> l3 =list1.stream().filter(x -> !list2.contains(x)).collect(Collectors.toList());

Common between two arrays:

List<String> l3 =list1.stream().filter(x -> list2.contains(x)).collect(Collectors.toList());

How to add a new audio (not mixing) into a video using ffmpeg?

Nothing quite worked for me (I think it was because my input .mp4 video didn't had any audio) so I found this worked for me:

ffmpeg -i input_video.mp4 -i balipraiavid.wav -map 0:v:0 -map 1:a:0 output.mp4

How do I calculate someone's age based on a DateTime type birthday?

This is one of the most accurate answers that is able to resolve the birthday of 29th of Feb compared to any year of 28th Feb.

public int GetAge(DateTime birthDate)
{
    int age = DateTime.Now.Year - birthDate.Year;

    if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
        age--;

    return age;
}




How to include files outside of Docker's build context?

You can also create a tarball of what the image needs first and use that as your context.

https://docs.docker.com/engine/reference/commandline/build/#/tarball-contexts

Where does gcc look for C and C++ header files?

The CPP Section of the GCC Manual indicates that header files may be located in the following directories:

GCC looks in several different places for headers. On a normal Unix system, if you do not instruct it otherwise, it will look for headers requested with #include in:

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

For C++ programs, it will also look in /usr/include/g++-v3, first.

Have a variable in images path in Sass?

Have you tried the Interpolation syntax?

background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0;

WebAPI to Return XML

You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.

If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.

Accept: application/xml

You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1

EDIT: based on your edited question with code:

Simple return list of string, instead of converting it to XML. try it using Fiddler.

public List<string> Get(int tenantID, string dataType, string ActionName)
    {
       List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
       return SQLResult;
     }

For example if your list is like:

List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;

and you specify Accept: application/xml the output will be:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>Test1</string>
  <string>Test2</string>
  <string>Test3</string>
</ArrayOfstring>

and if you specify 'Accept: application/json' in the request then the output will be:

[
  "Test1",
  "Test2",
  "Test3"
]

So let the client request the content type, instead of you sending the customized xml.

Default values and initialization in Java

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

In the second code sample, a is class member variable, hence it will be initialized to the default value.

How can I delete using INNER JOIN with SQL Server?

Try this:

DELETE FROM WorkRecord2 
       FROM Employee 
Where EmployeeRun=EmployeeNo
      And Company = '1' 
      AND Date = '2013-05-06'

Sort an array of objects in React and render them

_x000D_
_x000D_
const list = [
  { qty: 10, size: 'XXL' },
  { qty: 2, size: 'XL' },
  { qty: 8, size: 'M' }
]

list.sort((a, b) => (a.qty > b.qty) ? 1 : -1)

console.log(list)
_x000D_
_x000D_
_x000D_

Out Put :

[
  {
    "qty": 2,
    "size": "XL"
  },
  {
    "qty": 8,
    "size": "M"
  },
  {
    "qty": 10,
    "size": "XXL"
  }
]

Binding a list in @RequestParam

Arrays in @RequestParam are used for binding several parameters of the same name:

myparam=myValue1&myparam=myValue2&myparam=myValue3

If you need to bind @ModelAttribute-style indexed parameters, I guess you need @ModelAttribute anyway.

jQuery check if <input> exists and has a value

The input won't have a value if it doesn't exist. Try this...

if($('.input1').val())

`ui-router` $stateParams vs. $state.params

EDIT: This answer is correct for version 0.2.10. As @Alexander Vasilyev pointed out it doesn't work in version 0.2.14.

Another reason to use $state.params is when you need to extract query parameters like this:

$stateProvider.state('a', {
  url: 'path/:id/:anotherParam/?yetAnotherParam',
  controller: 'ACtrl',
});

module.controller('ACtrl', function($stateParams, $state) {
  $state.params; // has id, anotherParam, and yetAnotherParam
  $stateParams;  // has id and anotherParam
}

How to Allow Remote Access to PostgreSQL database

You have to add this to your pg_hba.conf and restart your PostgreSQL.

host all all 192.168.56.1/24 md5

This works with VirtualBox and host-only adapter enabled. If you don't use Virtualbox you have to replace the IP address.

Is there an eval() function in Java?

Writing your own library is not that hard as u might thing. Here is link for Shunting-yard algorithm with step by step algorithm explenation. Although, you will have to parse the input for tokens first.

There are 2 other questions wich can give you some information too: Turn a String into a Math Expression? What's a good library for parsing mathematical expressions in java?

CentOS 64 bit bad ELF interpreter

You're on a 64-bit system, and don't have 32-bit library support installed.

To install (baseline) support for 32-bit executables

(if you don't use sudo in your setup read note below)

Most desktop Linux systems in the Fedora/Red Hat family:

 pkcon install glibc.i686

Possibly some desktop Debian/Ubuntu systems?:

pkcon install ia32-libs

Fedora or newer Red Hat, CentOS:

 sudo dnf install glibc.i686

Older RHEL, CentOS:

   sudo yum install glibc.i686

Even older RHEL, CentOS:

  sudo yum install glibc.i386

Debian or Ubuntu:

   sudo apt-get install ia32-libs

should grab you the (first, main) library you need.

Once you have that, you'll probably need support libs

Anyone needing to install glibc.i686 or glibc.i386 will probably run into other library dependencies, as well. To identify a package providing an arbitrary library, you can use

 ldd /usr/bin/YOURAPPHERE

if you're not sure it's in /usr/bin you can also fall back on

 ldd $(which YOURAPPNAME)

The output will look like this:

    linux-gate.so.1 =>  (0xf7760000)
    libpthread.so.0 => /lib/libpthread.so.0 (0xf773e000)
    libSM.so.6 => not found

Check for missing libraries (e.g. libSM.so.6 in the above output), and for each one you need to find the package that provides it.

Commands to find the package per distribution family

Fedora/Red Hat Enterprise/CentOS:

 dnf provides /usr/lib/libSM.so.6

or, on older RHEL/CentOS:

 yum provides /usr/lib/libSM.so.6

or, on Debian/Ubuntu:

first, install and download the database for apt-file

 sudo apt-get install apt-file && apt-file update

then search with

 apt-file find libSM.so.6

Note the prefix path /usr/lib in the (usual) case; rarely, some libraries still live under /lib for historical reasons … On typical 64-bit systems, 32-bit libraries live in /usr/lib and 64-bit libraries live in /usr/lib64.

(Debian/Ubuntu organise multi-architecture libraries differently.)

Installing packages for missing libraries

The above should give you a package name, e.g.:

libSM-1.2.0-2.fc15.i686 : X.Org X11 SM runtime library
Repo        : fedora
Matched from:
Filename    : /usr/lib/libSM.so.6

In this example the name of the package is libSM and the name of the 32bit version of the package is libSM.i686.

You can then install the package to grab the requisite library using pkcon in a GUI, or sudo dnf/yum/apt-get as appropriate…. E.g pkcon install libSM.i686. If necessary you can specify the version fully. E.g sudo dnf install ibSM-1.2.0-2.fc15.i686.

Some libraries will have an “epoch” designator before their name; this can be omitted (the curious can read the notes below).

Notes

Warning

Incidentially, the issue you are facing either implies that your RPM (resp. DPkg/DSelect) database is corrupted, or that the application you're trying to run wasn't installed through the package manager. If you're new to Linux, you probably want to avoid using software from sources other than your package manager, whenever possible...

If you don't use "sudo" in your set-up

Type

su -c

every time you see sudo, eg,

su -c dnf install glibc.i686

About the epoch designator in library names

The “epoch” designator before the name is an artifact of the way that the underlying RPM libraries handle version numbers; e.g.

2:libpng-1.2.46-1.fc16.i686 : A library of functions for manipulating PNG image format files
Repo        : fedora
Matched from:
Filename    : /usr/lib/libpng.so.3

Here, the 2: can be omitted; just pkcon install libpng.i686 or sudo dnf install libpng-1.2.46-1.fc16.i686. (It vaguely implies something like: at some point, the version number of the libpng package rolled backwards, and the “epoch” had to be incremented to make sure the newer version would be considered “newer” during updates. Or something similar happened. Twice.)


Updated to clarify and cover the various package manager options more fully (March, 2016)

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

This was my problem and how I fixed it...

I had done everything everyone had mentioned above etc. but was still getting this error. Turns out I was using the uri's of http://java.sun.com/jsp/jstl/fmt and http://java.sun.com/jsp/jstl/core which were incorrect.

Try switching the uris from above to:

http://java.sun.com/jstl/fmt
http://java.sun.com/jstl/core

Also, make sure you have the correct jars referenced in your class path.

Java JDBC connection status

Nothing. Just execute your query. If the connection has died, either your JDBC driver will reconnect (if it supports it, and you enabled it in your connection string--most don't support it) or else you'll get an exception.

If you check the connection is up, it might fall over before you actually execute your query, so you gain absolutely nothing by checking.

That said, a lot of connection pools validate a connection by doing something like SELECT 1 before handing connections out. But this is nothing more than just executing a query, so you might just as well execute your business query.

How to use filesaver.js

wll it looks like I found the answer, although I havent tested it yet

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

from this page https://github.com/eligrey/FileSaver.js

How to implement class constructor in Visual Basic?

If you mean VB 6, that would be Private Sub Class_Initialize().

http://msdn.microsoft.com/en-us/library/55yzhfb2(VS.80).aspx

If you mean VB.NET it is Public Sub New() or Shared Sub New().

Why is quicksort better than mergesort?

In c/c++ land, when not using stl containers, I tend to use quicksort, because it is built into the run time, while mergesort is not.

So I believe that in many cases, it is simply the path of least resistance.

In addition performance can be much higher with quick sort, for cases where the entire dataset does not fit into the working set.

How do you write to a folder on an SD card in Android?

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);
...

How to disable all div content

I just wanted to mention this extension method for enabling and disabling elements. I think it's a much cleaner way than adding and removing attributes directly.

Then you simply do:

$("div *").disable();

Case insensitive access for generic dictionary

For you LINQers out there that never use a regular dictionary constructor

myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)

How to change the blue highlight color of a UITableViewCell?

I have to set the selection style to UITableViewCellSelectionStyleDefault for custom background color to work. If any other style, the custom background color will be ignored. Tested on iOS 8.

The full code for the cell as follows:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"MyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // This is how you change the background color
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor redColor];
    [cell setSelectedBackgroundView:bgColorView];

    return cell;
}

Can you test google analytics on a localhost address?

Following on from Tuong Lu Kim's answer:

Assuming:

ga('create', 'UA-XXXXX-Y', 'auto');

...if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'....

Excerpt from:

Automatic cookie domain configuration sets the _ga cookie on the highest level domain it can. For example, if your website address is blog.example.co.uk, analytics.js will set the cookie domain to .example.co.uk. In addition, if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'.

The recommended JavaScript tracking snippet sets the string 'auto' for the cookieDomain field:


Source: https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#automatic_cookie_domain_configuration

Garbage collector in Android

There is no need to call the garbage collector after an OutOfMemoryError.

It's Javadoc clearly states:

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

So, the garbage collector already tried to free up memory before generating the error but was unsuccessful.

Where is the Docker daemon log?

The below solution worked for me in Ubuntu 20.04

Logs stored in: /var/lib/docker/containers/<container id>/<container id>-json.log

To know container Id: $ docker ps

Call to undefined function oci_connect()

I had the same issue, the solution on this page helped me, it's caused by using incompatible oci ddl files.

Hope it helps.

Angular2 Routing with Hashtag to page anchor

Solutions above didn't work for me... This one did it:

First, prepare MyAppComponent for automatic scrolling in ngAfterViewChecked()...

import { Component, OnInit, AfterViewChecked } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component( {
   [...]
} )
export class MyAppComponent implements OnInit, AfterViewChecked {

  private scrollExecuted: boolean = false;

  constructor( private activatedRoute: ActivatedRoute ) {}

  ngAfterViewChecked() {

    if ( !this.scrollExecuted ) {
      let routeFragmentSubscription: Subscription;

      // Automatic scroll
      routeFragmentSubscription =
        this.activatedRoute.fragment
          .subscribe( fragment => {
            if ( fragment ) {
              let element = document.getElementById( fragment );
              if ( element ) {
                element.scrollIntoView();

                this.scrollExecuted = true;

                // Free resources
                setTimeout(
                  () => {
                    console.log( 'routeFragmentSubscription unsubscribe' );
                    routeFragmentSubscription.unsubscribe();
                }, 1000 );

              }
            }
          } );
    }

  }

}

Then, navigate to my-app-route sending prodID hashtag

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component( {
   [...]
} )
export class MyOtherComponent {

  constructor( private router: Router ) {}

  gotoHashtag( prodID: string ) {
    this.router.navigate( [ '/my-app-route' ], { fragment: prodID } );
  }

}

twitter bootstrap typeahead ajax example

when using ajax, try $.getJSON() instead of $.get() if you have trouble with the correct display of the results.

In my case i got only the first character of every result when i used $.get(), although i used json_encode() server-side.

What is causing the error `string.split is not a function`?

run this

// you'll see that it prints Object
console.log(typeof document.location);

you want document.location.toString() or document.location.href

Temporarily switch working copy to a specific Git commit

If you are at a certain branch mybranch, just go ahead and git checkout commit_hash. Then you can return to your branch by git checkout mybranch. I had the same game bisecting a bug today :) Also, you should know about git bisect.

Find maximum value of a column and return the corresponding row values using Pandas

In order to print the Country and Place with maximum value, use the following line of code.

print(df[['Country', 'Place']][df.Value == df.Value.max()])

How to get rid of the "No bootable medium found!" error in Virtual Box?

Try this:

Go to virtual box > right click the OS > settings > under one of the many tab that I don't remember(sorry for this, i dont have vbox installed)> locate the VDI (virtual box disk image) file..

and save the settings.. then try to start the OS..

Doctrine - How to print out the real sql, not just the prepared statement?

Solution:1
====================================================================================

function showQuery($query)
{
    return sprintf(str_replace('?', '%s', $query->getSql()), $query->getParams());
}

// call function  
echo showQuery($doctrineQuery);

Solution:2
====================================================================================

function showQuery($query)
{
    // define vars              
    $output    = NULL;
    $out_query = $query->getSql();
    $out_param = $query->getParams();

    // replace params
   for($i=0; $i<strlen($out_query); $i++) {
       $output .= ( strpos($out_query[$i], '?') !== FALSE ) ? "'" .str_replace('?', array_shift($out_param), $out_query[$i]). "'" : $out_query[$i];
   }

   // output
   return sprintf("%s", $output);
}

// call function  
echo showQuery($doctrineQueryObject);

How to push both value and key into PHP array

This is the solution that may useful for u

Class Form {
# Declare the input as property
private $Input = [];

# Then push the array to it
public function addTextField($class,$id){
    $this->Input ['type'][] = 'text';
    $this->Input ['class'][] = $class;
    $this->Input ['id'][] = $id;
}

}

$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');

When you dump it. The result like this

array (size=3)
  'type' => 
    array (size=3)
      0 => string 'text' (length=4)
      1 => string 'text' (length=4)
      2 => string 'text' (length=4)
  'class' => 
    array (size=3)
      0 => string 'myclass1' (length=8)
      1 => string 'myclass2' (length=8)
      2 => string 'myclass3' (length=8)
  'id' => 
    array (size=3)
      0 => string 'myid1' (length=5)
      1 => string 'myid2' (length=5)
      2 => string 'myid3' (length=5)

how to cancel/abort ajax request in axios

https://github.com/axios/axios#cancellation

const CancelToken = axios.CancelToken;
                const source = CancelToken.source();
                let url = 'www.url.com'


                axios.get(url, {
                    progress: false,
                    cancelToken: source.token
                })
                    .then(resp => {

                        alert('done')

                    })

                setTimeout(() => {
                    source.cancel('Operation canceled by the user.');
                },'1000')

how to remove the bold from a headline?

style is accordingly vis css. An example

<h1 class="mynotsoboldtitle">Im not bold</h1>
<style>
.mynotsoboldtitle { font-weight:normal; }
</style>

How to fill in form field, and submit, using javascript?

You can try something like this:

    <script type="text/javascript">
        function simulateLogin(userName)
        {
            var userNameField = document.getElementById("username");
            userNameField.value = userName;
            var goButton = document.getElementById("go");
            goButton.click();
        }

        simulateLogin("testUser");
</script>

Drop all duplicate rows across multiple columns in Python Pandas

Try these various things

df = pd.DataFrame({"A":["foo", "foo", "foo", "bar","foo"], "B":[0,1,1,1,1], "C":["A","A","B","A","A"]})

>>>df.drop_duplicates( "A" , keep='first')

or

>>>df.drop_duplicates( keep='first')

or

>>>df.drop_duplicates( keep='last')

Only local connections are allowed Chrome and Selenium webdriver

  1. Check the version of your installed Chrome browser.

  2. Download the compatible version of ChromeDriver from

    https://sites.google.com/a/chromium.org/chromedriver/

  3. Set the location of the compatible ChromeDriver to:

     System.setProperty("webdriver.chrome.driver", "C:\\Users\\your_path\\chromedriver.exe");
    
  4. Run the Test again.

It should be good now.

oracle sql: update if exists else insert

The way I always do it (assuming the data is never to be deleted, only inserted) is to

  • Firstly do an insert, if this fails with a unique constraint violation then you know the row is there,
  • Then do an update

Unfortunately many frameworks such as Hibernate treat all database errors (e.g. unique constraint violation) as unrecoverable conditions, so it isn't always easy. (In Hibernate the solution is to open a new session/transaction just to execute this one insert command.)

You can't just do a select count(*) .. where .. as even if that returns zero, and therefore you choose to do an insert, between the time you do the select and the insert someone else might have inserted the row and therefore your insert will fail.

document.getElementByID is not a function

In my case, I was using it on an element instead of document, and according to MDN:

Unlike some other element-lookup methods such as Document.querySelector() and Document.querySelectorAll(), getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.

php string to int

What do you even want the result to be? 888888? If so, just remove the spaces with str_replace, then convert.

How can I replace newlines using PowerShell?

With -Raw you should get what you expect

Add views in UIStackView programmatically

Instead of coding all the constrains you could use a subclass that handles .intrinsicContentSize of UIView class in a simpler way. This solution improves also Interface Builder a little in a way to support with "intrinsicWidth" and "intrinsicHeight" of views. While you could extend UIView's and have those properties available on all UIViews in IB its cleaner to subclass.

// IntrinsicView.h
@import UIKit

IB_DESIGNABLE
@interface IntrinsicView : UIView
-(instancetype)initWithFrame:(CGRect)rect;
@property IBInspectable CGSize intrinsic;
@end
// IntrinsicView.m
#import "IntrinsicView.h"

@implementation IntrinsicView {
    CGSize _intrinsic;
}
- (instancetype)initWithFrame:(CGRect)frame {
    _intrinsic = frame.size;
    if ( !(self = [super initWithFrame:frame]) ) return nil;
    // your stuff here..
    return self;
}
-(CGSize)intrinsicContentSize {
    return _intrinsic;
}
-(void)prepareForInterfaceBuilder {
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, _intrinsic.width,_intrinsic.height);
}
@end

Which means you can just allocate those IntrinsicView's and the self.frame.size is taken as intrinsicContentSize. That way it does not disturb the normal layout and you dont need to set constraint relations that don't even apply in full with UIStackViews

#import "IntrinsicView.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIStackView *column = [[UIStackView alloc] initWithFrame:self.view.frame];
    column.spacing = 2;
    column.alignment = UIStackViewAlignmentFill;
    column.axis = UILayoutConstraintAxisVertical; //Up-Down
    column.distribution = UIStackViewDistributionFillEqually;
    
    for (int row=0; row<5; row++) {
        //..frame:(CGRect) defines here proportions and
        //relation to axis of StackView
        IntrinsicView *intrinsicView = [[IntrinsicView alloc] initWithFrame:CGRectMake(0, 0, 30.0, 30.0)];
        
        [column addArrangedSubview:intrinsicView];
    }
    [self.view addSubview:column];
}

now you can go crazy with UIStackView's enter image description here

or in swift + encoding, decoding, IB support, Objective-C support

@IBDesignable @objc class IntrinsicView : UIView {
    @IBInspectable var intrinsic : CGSize
    @objc override init(frame: CGRect) {
        intrinsic = frame.size
        super.init(frame: frame)
    }
    required init?(coder: NSCoder) {
        intrinsic = coder.decodeCGSize(forKey: "intrinsic")
        super.init(coder: coder)
    }
    override func encode(with coder: NSCoder) {
        coder.encode(intrinsic, forKey: "intrinsic")
        super.encode(with: coder)
    }
    override var intrinsicContentSize: CGSize {
        return intrinsic
    }
    override func prepareForInterfaceBuilder() {
        frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: intrinsic.width, height: intrinsic.height)
    }
}

Calling an API from SQL Server stored procedure

Screams in to the void - just "no" don't do it. This is a dumb idea.

Integrating with external data sources is what SSIS is for, or write a dot net application/service which queries the box and makes the API calls.

Writing CLR code to enable a SQL process to call web-services is the sort of thing that can bring a SQL box to its knees if done badly - imagine putting the the CLR function in a view somewhere - later someone else comes along not knowing what you've donem and joins on that view with a million row table - suddenly your SQL box is making a million individual webapi calls.

The whole idea is insane.

This doing sort of thing is the reason that enterprise DBAs dont' trust developers.

CLR is the kind of great power, which brings great responsibility, and the above is an abuse of it.

HTTP Basic Authentication credentials passed in URL and encryption

Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text

Is there a way to programmatically scroll a scroll view to a specific edit text?

 scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.smoothScrollTo(0, myTextView.getTop());

                    }
                });

Answering from my practical project.

enter image description here

Printing hexadecimal characters in C

Indeed, there is type conversion to int. Also you can force type to char by using %hhx specifier.

printf("%hhX", a);

In most cases you will want to set the minimum length as well to fill the second character with zeroes:

printf("%02hhX", a);

ISO/IEC 9899:201x says:

7 The length modifiers and their meanings are: hh Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following

Missing Maven dependencies in Eclipse project

So I'm about 4 or 5 years late to this party, but I had this issue after pulling from our repo, and none of the other solutions from this thread worked out in my case to get rid of these warnings/errors.

This worked for me:

From Eclipse go to to Window -> Preferences -> Maven (expand) -> Errors/Warnings. The last option reads "Plugin execution not covered by lifecycle configuration" - use the drop-down menu for this option and toggle "Ignore", then Apply, then OK. (At "Requires updating Maven Projects" prompt say OK).

Further Info:

This may not necessarily "fix" the underlying issue(s), and may not qualify as "best practice" by some, however it should remove/supress these warnings from appearing in Eclipse and let you move forward at least. Specifically - I was working with Eclipse Luna Service Release 1 (4.4.1) w/ Spring Dashboard & Spring IDE Core (3.6.3), and m2e (1.5) installed, running on Arch Linux and OpenJDK 1.7. I imported my project as an existing maven project and selected OK when warned about existing warnings/errors (to deal with them later).

Suppress/Remove "Plugin Execution not covered..." warnings Eclipse-Maven

(Sorry, I'm not a designer, but added picture for clarity.)

Python: TypeError: object of type 'NoneType' has no len()

I was faces this issue but after change object into str, problem solved. str(fname).isalpha():

Does Spring Data JPA have any way to count entites using method name resolving?

I have only been working with it for a few weeks but I don't believe that this is strictly possible however you should be able to get the same effect with a little more effort; just write the query yourself and annotate the method name. It's probably not much simpler than writing the method yourself but it is cleaner in my opinion.

Edit: it is now possible according to DATAJPA-231

Oracle Convert Seconds to Hours:Minutes:Seconds

Assuming your time is called st.etime below and stored in seconds, here is what I use. This handles times where the seconds are greater than 86399 seconds (which is 11:59:59 pm)

case when st.etime > 86399 then to_char(to_date(st.etime - 86400,'sssss'),'HH24:MI:SS') else to_char(to_date(st.etime,'sssss'),'HH24:MI:SS') end readable_time

Allow user to select camera or gallery for image

How to launch a single Intent to select images from either the Gallery or the Camera, or any application registered to browse the filesystem.

Rather than creating a Dialog with a list of Intent options, it is much better to use Intent.createChooser in order to get access to the graphical icons and short names of the various 'Camera', 'Gallery' and even Third Party filesystem browser apps such as 'Astro', etc.

This describes how to use the standard chooser-intent and add additional intents to that.

private Uri outputFileUri;

private void openImageIntent() {

    // Determine Uri of camera image to save.
    final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
    root.mkdirs();
    final String fname = Utils.getUniqueImageFilename();
    final File sdImageMainDirectory = new File(root, fname);
    outputFileUri = Uri.fromFile(sdImageMainDirectory);

    // Camera.
    final List<Intent> cameraIntents = new ArrayList<Intent>();
    final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    final PackageManager packageManager = getPackageManager();
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for(ResolveInfo res : listCam) {
        final String packageName = res.activityInfo.packageName;
        final Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        cameraIntents.add(intent);
    }

    // Filesystem.
    final Intent galleryIntent = new Intent();
    galleryIntent.setType("image/*");
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

    // Chooser of filesystem options.
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

    // Add the camera options.
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));

    startActivityForResult(chooserIntent, YOUR_SELECT_PICTURE_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == YOUR_SELECT_PICTURE_REQUEST_CODE) {
            final boolean isCamera;
            if (data == null) {
                isCamera = true;
            } else {
                final String action = data.getAction();
                if (action == null) {
                    isCamera = false;
                } else {
                    isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                }
            }

            Uri selectedImageUri;
            if (isCamera) {
                selectedImageUri = outputFileUri;
            } else {
                selectedImageUri = data == null ? null : data.getData();
            }
        }
    }
}

C++ static virtual members?

Well , quite a late answer but it is possible using the curiously recurring template pattern. This wikipedia article has the info you need and also the example under static polymorphism is what you are asked for.

How to make android listview scrollable?

I know this question is 4-5 years old, but still, this might be useful:

Sometimes, if you have only a few elements that "exit the screen", the list might not scroll. That's because the operating system doesn't view it as actually exceeding the screen.

I'm saying this because I ran into this problem today - I only had 2 or 3 elements that were exceeding the screen limits, and my list wasn't scrollable. And it was a real mystery. As soon as I added a few more, it started to scroll.

So you have to make sure it's not a design problem at first, like the list appearing to go beyond the borders of the screen but in reality, "it doesn't", and adjust its dimensions and margin values and see if it's starting to "become scrollable". It did, for me.

Connecting to local SQL Server database using C#

If you're using SQL Server express, change

SqlConnection conn = new SqlConnection("Server=localhost;" 
       + "Database=Database1;");

to

SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;" 
       + "Database=Database1;");

That, and hundreds more connection strings can be found at http://www.connectionstrings.com/

Add hover text without javascript like we hover on a user's reputation

This can also be done in CSS, for more customisability:

_x000D_
_x000D_
.hoverable {
  position: relative;
}

.hoverable>.hoverable__tooltip {
  display: none;
}

.hoverable:hover>.hoverable__tooltip {
  display: inline;
  position: absolute;
  top: 1em;
  left: 1em;
  background: #888;
  border: 1px solid black;
}
_x000D_
<div class="hoverable">
  <span class="hoverable__main">Main text</span>
  <span class="hoverable__tooltip">Hover text</span>
</div>
_x000D_
_x000D_
_x000D_

(Obviously, styling can be improved)

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

What does the CSS rule "clear: both" do?

I won't be explaining how the floats work here (in detail), as this question generally focuses on Why use clear: both; OR what does clear: both; exactly do...

I'll keep this answer simple, and to the point, and will explain to you graphically why clear: both; is required or what it does...

Generally designers float the elements, left or to the right, which creates an empty space on the other side which allows other elements to take up the remaining space.

Why do they float elements?

Elements are floated when the designer needs 2 block level elements side by side. For example say we want to design a basic website which has a layout like below...

enter image description here

Live Example of the demo image.

Code For Demo

_x000D_
_x000D_
/*  CSS:  */_x000D_
_x000D_
* { /* Not related to floats / clear both, used it for demo purpose only */_x000D_
    box-sizing: border-box;_x000D_
    -moz-box-sizing: border-box;_x000D_
    -webkit-box-sizing: border-box;_x000D_
}_x000D_
_x000D_
header, footer {_x000D_
    border: 5px solid #000;_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
aside {_x000D_
    float: left;_x000D_
    width: 30%;_x000D_
    border: 5px solid #000;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
section {_x000D_
    float: left;_x000D_
    width: 70%;_x000D_
    border: 5px solid #000;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
.clear {_x000D_
    clear: both;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<header>_x000D_
    Header_x000D_
</header>_x000D_
<aside>_x000D_
    Aside (Floated Left)_x000D_
</aside>_x000D_
<section>_x000D_
    Content (Floated Left, Can Be Floated To Right As Well)_x000D_
</section>_x000D_
<!-- Clearing Floating Elements-->_x000D_
<div class="clear"></div>_x000D_
<footer>_x000D_
    Footer_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Note: You might have to add header, footer, aside, section (and other HTML5 elements) as display: block; in your stylesheet for explicitly mentioning that the elements are block level elements.

Explanation:

I have a basic layout, 1 header, 1 side bar, 1 content area and 1 footer.

No floats for header, next comes the aside tag which I'll be using for my website sidebar, so I'll be floating the element to left.

Note: By default, block level element takes up document 100% width, but when floated left or right, it will resize according to the content it holds.

  1. Normal Behavior Of Block Level Element
  2. Floated Behavior Of Block Level Element

So as you note, the left floated div leaves the space to its right unused, which will allow the div after it to shift in the remaining space.

  1. div's will render one after the other if they are NOT floated
  2. div will shift beside each other if floated left or right

Ok, so this is how block level elements behave when floated left or right, so now why is clear: both; required and why?

So if you note in the layout demo - in case you forgot, here it is..

I am using a class called .clear and it holds a property called clear with a value of both. So lets see why it needs both.

I've floated aside and section elements to the left, so assume a scenario, where we have a pool, where header is solid land, aside and section are floating in the pool and footer is solid land again, something like this..

Floated View

So the blue water has no idea what the area of the floated elements are, they can be bigger than the pool or smaller, so here comes a common issue which troubles 90% of CSS beginners: why the background of a container element is not stretched when it holds floated elements. It's because the container element is a POOL here and the POOL has no idea how many objects are floating, or what the length or breadth of the floated elements are, so it simply won't stretch.

  1. Normal Flow Of The Document
  2. Sections Floated To Left
  3. Cleared Floated Elements To Stretch Background Color Of The Container

(Refer [Clearfix] section of this answer for neat way to do this. I am using an empty div example intentionally for explanation purpose)

I've provided 3 examples above, 1st is the normal document flow where red background will just render as expected since the container doesn't hold any floated objects.

In the second example, when the object is floated to left, the container element (POOL) won't know the dimensions of the floated elements and hence it won't stretch to the floated elements height.

enter image description here

After using clear: both;, the container element will be stretched to its floated element dimensions.

enter image description here

Another reason the clear: both; is used is to prevent the element to shift up in the remaining space.

Say you want 2 elements side by side and another element below them... So you will float 2 elements to left and you want the other below them.

  1. div Floated left resulting in section moving into remaining space
  2. Floated div cleared so that the section tag will render below the floated divs

1st Example

enter image description here


2nd Example

enter image description here

Last but not the least, the footer tag will be rendered after floated elements as I've used the clear class before declaring my footer tags, which ensures that all the floated elements (left/right) are cleared up to that point.


Clearfix

Coming to clearfix which is related to floats. As already specified by @Elky, the way we are clearing these floats is not a clean way to do it as we are using an empty div element which is not a div element is meant for. Hence here comes the clearfix.

Think of it as a virtual element which will create an empty element for you before your parent element ends. This will self clear your wrapper element holding floated elements. This element won't exist in your DOM literally but will do the job.

To self clear any wrapper element having floated elements, we can use

.wrapper_having_floated_elements:after {  /* Imaginary class name */
  content: "";
  clear: both;
  display: table;
}

Note the :after pseudo element used by me for that class. That will create a virtual element for the wrapper element just before it closes itself. If we look in the dom you can see how it shows up in the Document tree.

Clearfix

So if you see, it is rendered after the floated child div where we clear the floats which is nothing but equivalent to have an empty div element with clear: both; property which we are using for this too. Now why display: table; and content is out of this answers scope but you can learn more about pseudo element here.

Note that this will also work in IE8 as IE8 supports :after pseudo.


Original Answer:

Most of the developers float their content left or right on their pages, probably divs holding logo, sidebar, content etc., these divs are floated left or right, leaving the rest of the space unused and hence if you place other containers, it will float too in the remaining space, so in order to prevent that clear: both; is used, it clears all the elements floated left or right.

Demonstration:

------------------ ----------------------------------
div1(Floated Left) Other div takes up the space here
------------------ ----------------------------------

Now what if you want to make the other div render below div1, so you'll use clear: both; so it will ensure you clear all floats, left or right

------------------
div1(Floated Left)
------------------
<div style="clear: both;"><!--This <div> acts as a separator--></div>
----------------------------------
Other div renders here now
----------------------------------

JQUERY ajax passing value from MVC View to Controller

Try using the data option of the $.ajax function. More info here.

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatus) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Intro to GPU programming

I think the others have answered your second question. As for the first, the "Hello World" of CUDA, I don't think there is a set standard, but personally, I'd recommend a parallel adder (i.e. a programme that sums N integers).

If you look the "reduction" example in the NVIDIA SDK, the superficially simple task can be extended to demonstrate numerous CUDA considerations such as coalesced reads, memory bank conflicts and loop unrolling.

See this presentation for more info:

http://www.gpgpu.org/sc2007/SC07_CUDA_5_Optimization_Harris.pdf

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

.Net framework of the referencing dll should be same as the .Net framework version of the Project in which dll is referred

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

You can use:

Bulk collect along with FOR ALL that is called Bulk binding.

Because PL/SQL forall operator speeds 30x faster for simple table inserts.

BULK_COLLECT and Oracle FORALL together these two features are known as Bulk Binding. Bulk Binds are a PL/SQL technique where, instead of multiple individual SELECT, INSERT, UPDATE or DELETE statements are executed to retrieve from, or store data in, at table, all of the operations are carried out at once, in bulk. This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL engine, then back to the PL/SQL engine, and so on, when you individually access rows one at a time. To do bulk binds with INSERT, UPDATE, and DELETE statements, you enclose the SQL statement within a PL/SQL FORALL statement. To do bulk binds with SELECT statements, you include the BULK COLLECT clause in the SELECT statement instead of using INTO.

It improves performance.

How to get current SIM card number in Android?

Getting the Phone Number, IMEI, and SIM Card ID

TelephonyManager tm = (TelephonyManager) 
            getSystemService(Context.TELEPHONY_SERVICE);        

For SIM card, use the getSimSerialNumber()

    //---get the SIM card ID---
    String simID = tm.getSimSerialNumber();
    if (simID != null)
        Toast.makeText(this, "SIM card ID: " + simID, 
        Toast.LENGTH_LONG).show();

Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)

    //---get the phone number---
    String telNumber = tm.getLine1Number();
    if (telNumber != null)        
        Toast.makeText(this, "Phone number: " + telNumber, 
        Toast.LENGTH_LONG).show();

IMEI number of the phone, use the getDeviceId()

    //---get the IMEI number---
    String IMEI = tm.getDeviceId();
    if (IMEI != null)        
        Toast.makeText(this, "IMEI number: " + IMEI, 
        Toast.LENGTH_LONG).show();

Permissions needed

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

Difference between two lists

Following helper can be usefull if for such task:

There are 2 collections local collection called oldValues and remote called newValues From time to time you get notification bout some elements on remote collection have changed and you want to know which elements were added, removed and updated. Remote collection always returns ALL elements that it has.

    public class ChangesTracker<T1, T2>
{
    private readonly IEnumerable<T1> oldValues;
    private readonly IEnumerable<T2> newValues;
    private readonly Func<T1, T2, bool> areEqual;

    public ChangesTracker(IEnumerable<T1> oldValues, IEnumerable<T2> newValues, Func<T1, T2, bool> areEqual)
    {
        this.oldValues = oldValues;
        this.newValues = newValues;
        this.areEqual = areEqual;
    }

    public IEnumerable<T2> AddedItems
    {
        get => newValues.Where(n => oldValues.All(o => !areEqual(o, n)));
    }

    public IEnumerable<T1> RemovedItems
    {
        get => oldValues.Where(n => newValues.All(o => !areEqual(n, o)));
    }

    public IEnumerable<T1> UpdatedItems
    {
        get => oldValues.Where(n => newValues.Any(o => areEqual(n, o)));
    }
}

Usage

        [Test]
    public void AddRemoveAndUpdate()
    {
        // Arrange
        var listA = ChangesTrackerMockups.GetAList(10); // ids 1-10
        var listB = ChangesTrackerMockups.GetBList(11)  // ids 1-11
            .Where(b => b.Iddd != 7); // Exclude element means it will be delete
        var changesTracker = new ChangesTracker<A, B>(listA, listB, AreEqual);

        // Assert
        Assert.AreEqual(1, changesTracker.AddedItems.Count()); // b.id = 11
        Assert.AreEqual(1, changesTracker.RemovedItems.Count()); // b.id = 7
        Assert.AreEqual(9, changesTracker.UpdatedItems.Count()); // all a.id == b.iddd
    }

    private bool AreEqual(A a, B b)
    {
        if (a == null && b == null)
            return true;
        if (a == null || b == null)
            return false;
        return a.Id == b.Iddd;
    }

How to create a collapsing tree table in html/css/js?

In modern browsers, you need only very little to code to create a collapsible tree :

_x000D_
_x000D_
var tree = document.querySelectorAll('ul.tree a:not(:last-child)');_x000D_
for(var i = 0; i < tree.length; i++){_x000D_
    tree[i].addEventListener('click', function(e) {_x000D_
        var parent = e.target.parentElement;_x000D_
        var classList = parent.classList;_x000D_
        if(classList.contains("open")) {_x000D_
            classList.remove('open');_x000D_
            var opensubs = parent.querySelectorAll(':scope .open');_x000D_
            for(var i = 0; i < opensubs.length; i++){_x000D_
                opensubs[i].classList.remove('open');_x000D_
            }_x000D_
        } else {_x000D_
            classList.add('open');_x000D_
        }_x000D_
        e.preventDefault();_x000D_
    });_x000D_
}
_x000D_
body {_x000D_
    font-family: Arial;_x000D_
}_x000D_
_x000D_
ul.tree li {_x000D_
    list-style-type: none;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
ul.tree li ul {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
ul.tree li.open > ul {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
ul.tree li a {_x000D_
    color: black;_x000D_
    text-decoration: none;_x000D_
}_x000D_
_x000D_
ul.tree li a:before {_x000D_
    height: 1em;_x000D_
    padding:0 .1em;_x000D_
    font-size: .8em;_x000D_
    display: block;_x000D_
    position: absolute;_x000D_
    left: -1.3em;_x000D_
    top: .2em;_x000D_
}_x000D_
_x000D_
ul.tree li > a:not(:last-child):before {_x000D_
    content: '+';_x000D_
}_x000D_
_x000D_
ul.tree li.open > a:not(:last-child):before {_x000D_
    content: '-';_x000D_
}
_x000D_
<ul class="tree">_x000D_
  <li><a href="#">Part 1</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 2</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 3</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

(see also this Fiddle)

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

What is the difference between AF_INET and PF_INET in socket programming?

I found in Linux kernel source code that PF_INET and AF_INET are the same. The following code is from file include/linux/socket.h, line 204 of Linux kernel 3.2.21 tree.

/* Protocol families, same as address families. */
...
#define PF_INET     AF_INET

How to get the nth occurrence in a string?

Here's my solution, which just iterates over the string until n matches have been found:

String.prototype.nthIndexOf = function(searchElement, n, fromElement) {
    n = n || 0;
    fromElement = fromElement || 0;
    while (n > 0) {
        fromElement = this.indexOf(searchElement, fromElement);
        if (fromElement < 0) {
            return -1;
        }
        --n;
        ++fromElement;
    }
    return fromElement - 1;
};

var string = "XYZ 123 ABC 456 ABC 789 ABC";
console.log(string.nthIndexOf('ABC', 2));

>> 16

Try-Catch-End Try in VBScript doesn't seem to work

Sometimes, especially when you work with VB, you can miss obvious solutions. Like I was doing last 2 days.

the code, which generates error needs to be moved to a separate function. And in the beginning of the function you write On Error Resume Next. This is how an error can be "swallowed", without swallowing any other errors. Dividing code into small separate functions also improves readability, refactoring & makes it easier to add some new functionality.

wget ssl alert handshake failure

Basically your OpenSSL uses SSLv3 and the site you are accessing does not support that protocol.

Just update your wget:

sudo apt-get install wget

Or if it is already supporting another secure protocol, just add it as argument:

wget https://example.com --secure-protocol=PROTOCOL_v1

Pretty printing XML in Python

As of Python 3.9 (still a release candidate as of 12 Aug 2020), there is a new xml.etree.ElementTree.indent() function for pretty-printing XML trees.

Sample usage:

import xml.etree.ElementTree as ET

element = ET.XML("<html><body>text</body></html>")
ET.indent(element)
print(ET.tostring(element, encoding='unicode'))

The upside is that it does not require any additional libraries. For more information check https://bugs.python.org/issue14465 and https://github.com/python/cpython/pull/15200

Set height 100% on absolute div

Few answers have given a solution with height and width 100% but I recommend you to not use percentage in css, use top/bottom and left/right positionning.

This is a better approach that allow you to control margin.

Here is the code :

body {
    position: relative;
    height: 3000px;
}
body div {

    top:0px;
    bottom: 0px;
    right: 0px;
    left:0px;
    background-color: yellow;
    position: absolute;
}

How to watch for form changes in Angular

To complete a bit more previous great answers, you need to be aware that forms leverage observables to detect and handle value changes. It's something really important and powerful. Both Mark and dfsq described this aspect in their answers.

Observables allow not only to use the subscribe method (something similar to the then method of promises in Angular 1). You can go further if needed to implement some processing chains for updated data in forms.

I mean you can specify at this level the debounce time with the debounceTime method. This allows you to wait for an amount of time before handling the change and correctly handle several inputs:

this.form.valueChanges
    .debounceTime(500)
    .subscribe(data => console.log('form changes', data));

You can also directly plug the processing you want to trigger (some asynchronous one for example) when values are updated. For example, if you want to handle a text value to filter a list based on an AJAX request, you can leverage the switchMap method:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

You even go further by linking the returned observable directly to a property of your component:

this.list = this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

and display it using the async pipe:

<ul>
  <li *ngFor="#elt of (list | async)">{{elt.name}}</li>
</ul>

Just to say that you need to think the way to handle forms differently in Angular2 (a much more powerful way ;-)).

Hope it helps you, Thierry

How to create nested directories using Mkdir in Golang?

This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.

package main

import (
    "fmt"
    "os"
)

func main()  {
    if err := ensureDir("/test-dir"); err != nil {
        fmt.Println("Directory creation failed with error: " + err.Error())
        os.Exit(1)
    }
    // Proceed forward
}

func ensureDir(dirName string) error {

    err := os.MkdirAll(dirName, os.ModeDir)

    if err == nil || os.IsExist(err) {
        return nil
    } else {
        return err
    }
}

What Language is Used To Develop Using Unity

When you build for iPhone in Unity it does Ahead of Time (AOT) compilation of your mono assembly (written in C# or JavaScript) to native ARM code.

The authoring tool also creates a stub xcode project and references that compiled lib. You can add objective C code to this xcode project if there is native stuff you want to do that isn't exposed in Unity's environment yet (e.g. accessing the compass and/or gyroscope).

Why does background-color have no effect on this DIV?

This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer element in my case didn't show. I added a position: relative which worked.

Get AVG ignoring Null or Zero values

worked for me:

AVG(CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)

How to suppress warnings globally in an R Script

You want options(warn=-1). However, note that warn=0 is not the safest warning level and it should not be assumed as the current one, particularly within scripts or functions. Thus the safest way to temporary turn off warnings is:

oldw <- getOption("warn")
options(warn = -1)

[your "silenced" code]

options(warn = oldw)

String formatting in Python 3

I like this approach

my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)

Note the appended d and s to the brackets respectively.

output will be:

I scored 3 goals and took 5 penalties

Printing long int value in C

To take input " long int " and output " long int " in C is :

long int n;
scanf("%ld", &n);
printf("%ld", n);

To take input " long long int " and output " long long int " in C is :

long long int n;
scanf("%lld", &n);
printf("%lld", n);

Hope you've cleared..

bower proxy configuration

add in .bowerrc

{SET HTTP_PROXY= http://HOST:PORT,SET HTTPS_PROXY=http://HOST:PORT}

In NPM, you must to execute in console this:

npm --proxy http://Host:Port install

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

Swift 5 version

The answers given here are either outdated or incorrect because they don't take into account the following:

  1. The pixel size of the image can differ from its point size that is returned by image.size.width/image.size.height.
  2. There can be various layouts used by pixel components in the image, such as BGRA, ABGR, ARGB etc. or may not have an alpha component at all, such as BGR and RGB. For example, UIView.drawHierarchy(in:afterScreenUpdates:) method can produce BGRA images.
  3. Color components can be premultiplied by the alpha for all pixels in the image and need to be divided by alpha in order to restore the original color.
  4. For memory optimization used by CGImage, the size of a pixel row in bytes can be greater than the mere multiplication of the pixel width by 4.

The code below is to provide a universal Swift 5 solution to get the UIColor of a pixel for all such special cases. The code is optimized for usability and clarity, not for performance.

public extension UIImage {

    var pixelWidth: Int {
        return cgImage?.width ?? 0
    }

    var pixelHeight: Int {
        return cgImage?.height ?? 0
    }

    func pixelColor(x: Int, y: Int) -> UIColor {
        assert(
            0..<pixelWidth ~= x && 0..<pixelHeight ~= y,
            "Pixel coordinates are out of bounds")

        guard
            let cgImage = cgImage,
            let data = cgImage.dataProvider?.data,
            let dataPtr = CFDataGetBytePtr(data),
            let colorSpaceModel = cgImage.colorSpace?.model,
            let componentLayout = cgImage.bitmapInfo.componentLayout
        else {
            assertionFailure("Could not get a pixel of an image")
            return .clear
        }

        assert(
            colorSpaceModel == .rgb,
            "The only supported color space model is RGB")
        assert(
            cgImage.bitsPerPixel == 32 || cgImage.bitsPerPixel == 24,
            "A pixel is expected to be either 4 or 3 bytes in size")

        let bytesPerRow = cgImage.bytesPerRow
        let bytesPerPixel = cgImage.bitsPerPixel/8
        let pixelOffset = y*bytesPerRow + x*bytesPerPixel

        if componentLayout.count == 4 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2],
                dataPtr[pixelOffset + 3]
            )

            var alpha: UInt8 = 0
            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgra:
                alpha = components.3
                red = components.2
                green = components.1
                blue = components.0
            case .abgr:
                alpha = components.0
                red = components.3
                green = components.2
                blue = components.1
            case .argb:
                alpha = components.0
                red = components.1
                green = components.2
                blue = components.3
            case .rgba:
                alpha = components.3
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            // If chroma components are premultiplied by alpha and the alpha is `0`,
            // keep the chroma components to their current values.
            if cgImage.bitmapInfo.chromaIsPremultipliedByAlpha && alpha != 0 {
                let invUnitAlpha = 255/CGFloat(alpha)
                red = UInt8((CGFloat(red)*invUnitAlpha).rounded())
                green = UInt8((CGFloat(green)*invUnitAlpha).rounded())
                blue = UInt8((CGFloat(blue)*invUnitAlpha).rounded())
            }

            return .init(red: red, green: green, blue: blue, alpha: alpha)

        } else if componentLayout.count == 3 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2]
            )

            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgr:
                red = components.2
                green = components.1
                blue = components.0
            case .rgb:
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            return .init(red: red, green: green, blue: blue, alpha: UInt8(255))

        } else {
            assertionFailure("Unsupported number of pixel components")
            return .clear
        }
    }

}

public extension UIColor {

    convenience init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
        self.init(
            red: CGFloat(red)/255,
            green: CGFloat(green)/255,
            blue: CGFloat(blue)/255,
            alpha: CGFloat(alpha)/255)
    }

}

public extension CGBitmapInfo {

    enum ComponentLayout {

        case bgra
        case abgr
        case argb
        case rgba
        case bgr
        case rgb

        var count: Int {
            switch self {
            case .bgr, .rgb: return 3
            default: return 4
            }
        }

    }

    var componentLayout: ComponentLayout? {
        guard let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue) else { return nil }
        let isLittleEndian = contains(.byteOrder32Little)

        if alphaInfo == .none {
            return isLittleEndian ? .bgr : .rgb
        }
        let alphaIsFirst = alphaInfo == .premultipliedFirst || alphaInfo == .first || alphaInfo == .noneSkipFirst

        if isLittleEndian {
            return alphaIsFirst ? .bgra : .abgr
        } else {
            return alphaIsFirst ? .argb : .rgba
        }
    }

    var chromaIsPremultipliedByAlpha: Bool {
        let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue)
        return alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast
    }

}

Understanding Spring @Autowired usage

TL;DR

The @Autowired annotation spares you the need to do the wiring by yourself in the XML file (or any other way) and just finds for you what needs to be injected where and does that for you.

Full explanation

The @Autowired annotation allows you to skip configurations elsewhere of what to inject and just does it for you. Assuming your package is com.mycompany.movies you have to put this tag in your XML (application context file):

<context:component-scan base-package="com.mycompany.movies" />

This tag will do an auto-scanning. Assuming each class that has to become a bean is annotated with a correct annotation like @Component (for simple bean) or @Controller (for a servlet control) or @Repository (for DAO classes) and these classes are somewhere under the package com.mycompany.movies, Spring will find all of these and create a bean for each one. This is done in 2 scans of the classes - the first time it just searches for classes that need to become a bean and maps the injections it needs to be doing, and on the second scan it injects the beans. Of course, you can define your beans in the more traditional XML file or with an @Configuration class (or any combination of the three).

The @Autowired annotation tells Spring where an injection needs to occur. If you put it on a method setMovieFinder it understands (by the prefix set + the @Autowired annotation) that a bean needs to be injected. In the second scan, Spring searches for a bean of type MovieFinder, and if it finds such bean, it injects it to this method. If it finds two such beans you will get an Exception. To avoid the Exception, you can use the @Qualifier annotation and tell it which of the two beans to inject in the following manner:

@Qualifier("redBean")
class Red implements Color {
   // Class code here
}

@Qualifier("blueBean")
class Blue implements Color {
   // Class code here
}

Or if you prefer to declare the beans in your XML, it would look something like this:

<bean id="redBean" class="com.mycompany.movies.Red"/>

<bean id="blueBean" class="com.mycompany.movies.Blue"/>

In the @Autowired declaration, you need to also add the @Qualifier to tell which of the two color beans to inject:

@Autowired
@Qualifier("redBean")
public void setColor(Color color) {
  this.color = color;
}

If you don't want to use two annotations (the @Autowired and @Qualifier) you can use @Resource to combine these two:

@Resource(name="redBean")
public void setColor(Color color) {
  this.color = color;
}

The @Resource (you can read some extra data about it in the first comment on this answer) spares you the use of two annotations and instead, you only use one.

I'll just add two more comments:

  1. Good practice would be to use @Inject instead of @Autowired because it is not Spring-specific and is part of the JSR-330 standard.
  2. Another good practice would be to put the @Inject / @Autowired on a constructor instead of a method. If you put it on a constructor, you can validate that the injected beans are not null and fail fast when you try to start the application and avoid a NullPointerException when you need to actually use the bean.

Update: To complete the picture, I created a new question about the @Configuration class.

postgresql COUNT(DISTINCT ...) very slow

I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.

Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -

SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;

Query performance is also high.

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

I don't think you need the trailing slash in the URL entry. Ie, put this instead:

(r'^led-tv$', filter_by_led ),

This is assuming you have trailing slashes enabled, which is the default.

Define a struct inside a class in C++

Something like this:

class Class {
    // visibility will default to private unless you specify it
    struct Struct {
        //specify members here;
    };
};

Remap values in pandas column with a dict

Given map is faster than replace (@JohnE's solution) you need to be careful with Non-Exhaustive mappings where you intend to map specific values to NaN. The proper method in this case requires that you mask the Series when you .fillna, else you undo the mapping to NaN.

import pandas as pd
import numpy as np

d = {'m': 'Male', 'f': 'Female', 'missing': np.NaN}
df = pd.DataFrame({'gender': ['m', 'f', 'missing', 'Male', 'U']})

keep_nan = [k for k,v in d.items() if pd.isnull(v)]
s = df['gender']

df['mapped'] = s.map(d).fillna(s.mask(s.isin(keep_nan)))

    gender  mapped
0        m    Male
1        f  Female
2  missing     NaN
3     Male    Male
4        U       U

"Unable to launch the IIS Express Web server" error

Try this:

  1. Open Properties of your solution
  2. Go to web
  3. under LOCAL IIS, Change written port number to any other port number and create a new virtual directory.

Eliminating duplicate values based on only one column of the table

From your example it seems reasonable to assume that the siteIP column is determined by the siteName column (that is, each site has only one siteIP). If this is indeed the case, then there is a simple solution using group by:

select
  sites.siteName,
  sites.siteIP,
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName,
  sites.siteIP
order by
  sites.siteName;

However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP), then it is not clear from you question which siteIP you want the query to return in the second column. If just any siteIP, then the following query will do:

select
  sites.siteName,
  min(sites.siteIP),
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName
order by
  sites.siteName;

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

Maximum call stack size exceeded on npm install

rm -rf node_modules

and then reinstall worked for me.

note: probably don't need to rip out your lock files

Java word count program

import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;

String str="Simple Java Word Count count Count Program";
Iterable<String> words = Splitter.on(" ").trimResults().split(str);


//google word counter       
Multiset<String> wordsMultiset = HashMultiset.create();
for (String string : words) {   
    wordsMultiset.add(string.toLowerCase());
}

Set<String> result = wordsMultiset.elementSet();
for (String string : result) {
    System.out.println(string+" X "+wordsMultiset.count(string));
}

How to obtain the number of CPUs/cores in Linux from the command line?

Using getconf is indeed the most portable way, however the variable has different names in BSD and Linux to getconf, so you have to test both, as this gist suggests: https://gist.github.com/jj1bdx/5746298 (also includes a Solaris fix using ksh)

I personally use:

$ getconf _NPROCESSORS_ONLN 2>/dev/null || getconf NPROCESSORS_ONLN 2>/dev/null || echo 1

And if you want this in python you can just use the syscall getconf uses by importing the os module:

$ python -c 'import os; print os.sysconf(os.sysconf_names["SC_NPROCESSORS_ONLN"]);'

As for nproc, it's part of GNU Coreutils, so not available in BSD by default. It uses sysconf() as well after some other methods.

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

Josh says: "....Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h."

I'm a native Spanish Speaker and "ch" is not a letter but two "c" and "h" and the Spanish alphabet is like: abcdefghijklmn ñ opqrstuvwxyz We don't expect "ch" after "h" but "i" The alphabet is the same as in English except for the ñ or in HTML "&ntilde ;"

Alex