Programs & Examples On #Satellite navigation

How to generate xsd from wsdl

(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :

Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.

This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).

Best C++ IDE or Editor for Windows

There are the free "Express" versions of Visual Studio. Given that you like Visual Studio and that the "Express" editions are free, there is no reason to use any other editor.

How to get the python.exe location programmatically?

This works in Linux & Windows:

Python 3.x

>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe

Python 2.x

>>> import sys
>>> print sys.executable
/usr/bin/python

HTML tag inside JavaScript

<div id="demo"></div>

<script type="text/javascript">
    if(document.getElementById('number1').checked) {
        var demo = document.getElementById("demo");    
        demo.innerHtml='<h1>Hello member</h1>';
    } else {
        demo.innerHtml='';
    }
</script>

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

  1. Using html5 doctype at the beginning of the page.

    <!DOCTYPE html>

  2. Force IE to use the latest render mode

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

  3. If your target browser is ie8, then check your compatible settings in IE8

I blog this in details

Select first 10 distinct rows in mysql

Try this SELECT DISTINCT 10 * ...

Play infinitely looping video on-load in HTML5

You can do this the following two ways:

1) Using loop attribute in video element (mentioned in the first answer):

2) and you can use the ended media event:

window.addEventListener('load', function(){
    var newVideo = document.getElementById('videoElementId');
    newVideo.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);

    newVideo.play();

});

How to restore the menu bar in Visual Studio Code

Press Ctrl + Shift + P to open the Command Palette.

Enter image description here

Enter image description here

After that, you write menu
Option is enabled

rails 3 validation on uniqueness on multiple attributes

Dont work for me, need to put scope in plural

validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]

SQL datetime format to date only

After perusing your previous questions I eventually determined you are probably on SQL Server 2005. For US format you would use style 101

select Subject, 
       CONVERT(varchar,DeliveryDate,101) as DeliveryDate
from Email_Administration 
where MerchantId =@MerchantID 

Simple CSS: Text won't center in a button

Usualy, your code should work...

But here is a way to center text in css:

.text
{
    margin-left: auto;
    margin-right: auto;
}

This has proved to be bulletproof to me whenever I want to center text with css.

Android SDK installation doesn't find JDK

WORKING SOLUTION AND NO REGISTRY MODIFY NEEDED

Simply put your java bin path in front of your PATH environment.

PATH before

C:\Windows\system32;C:\Windows\%^^&^&^............(old path setting)

PATH after

C:\Program Files\Java\jdk1.6.0_18\bin;C:\Windows\system32;C:\Windows\%^^&^&^............(old path setting)

And now the Android SDK installer is working.

BTW, I'm running Win7 x64.

Concept behind putting wait(),notify() methods in Object class

Wait and notify method always called on object so whether it may be Thread object or simple object (which does not extends Thread class) Given Example will clear your all the doubts.

I have called wait and notify on class ObjB and that is the Thread class so we can say that wait and notify are called on any object.

public class ThreadA {
    public static void main(String[] args){
        ObjB b = new ObjB();
        Threadc c = new Threadc(b); 
        ThreadD d = new ThreadD(b);
        d.setPriority(5);
        c.setPriority(1);
        d.start();
        c.start();
    }
}

class ObjB {
    int total;
    int count(){
        for(int i=0; i<100 ; i++){
            total += i;
        }
        return total;
    }}


class Threadc extends Thread{
    ObjB b;
    Threadc(ObjB objB){
        b= objB;
    }
    int total;
    @Override
    public void run(){
        System.out.print("Thread C run method");
        synchronized(b){
            total = b.count();
            System.out.print("Thread C notified called ");
            b.notify();
        }
    }
}

class ThreadD extends Thread{
    ObjB b;
    ThreadD(ObjB objB){
        b= objB;
    }
    int total;
    @Override
    public void run(){
        System.out.print("Thread D run method");
        synchronized(b){
            System.out.println("Waiting for b to complete...");
            try {
                b.wait();
                System.out.print("Thread C B value is" + b.total);
                } 
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
    }
}

Angularjs autocomplete from $http

I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.

Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete

So basically you have to return a promise when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $qservice/directive/controller where you issue your HTTP Request.

Example:

function getMyHttpData(){
  var deferred = $q.defer();
  $http.jsonp(request).success(function(data){
    // the promise gets resolved with the data from HTTP
    deferred.resolve(data);
  });
  // return the promise
  return deferred.promise;
}

I hope this helps.

What is the best way to connect and use a sqlite database from C#

I'm with, Bruce. I AM using http://system.data.sqlite.org/ with great success as well. Here's a simple class example that I created:

using System;
using System.Text;
using System.Data;
using System.Data.SQLite;

namespace MySqlLite
{
      class DataClass
      {
        private SQLiteConnection sqlite;

        public DataClass()
        {
              //This part killed me in the beginning.  I was specifying "DataSource"
              //instead of "Data Source"
              sqlite = new SQLiteConnection("Data Source=/path/to/file.db");

        }

        public DataTable selectQuery(string query)
        {
              SQLiteDataAdapter ad;
              DataTable dt = new DataTable();

              try
              {
                    SQLiteCommand cmd;
                    sqlite.Open();  //Initiate connection to the db
                    cmd = sqlite.CreateCommand();
                    cmd.CommandText = query;  //set the passed query
                    ad = new SQLiteDataAdapter(cmd);
                    ad.Fill(dt); //fill the datasource
              }
              catch(SQLiteException ex)
              {
                    //Add your exception code here.
              }
              sqlite.Close();
              return dt;
  }
}

There is also an NuGet package: System.Data.SQLite available.

Can Mysql Split a column?

Usually substring_index does what you want:

mysql> select substring_index("[email protected]","@",-1);
+-----------------------------------------+
| substring_index("[email protected]","@",-1) |
+-----------------------------------------+
| gmail.com                               |
+-----------------------------------------+
1 row in set (0.00 sec)

TypeError: $ is not a function when calling jQuery function

var $=jQuery.noConflict();

$(document).ready(function(){
    // jQuery code is in here
});

Credit to Ashwani Panwar and Cyssoo answer: https://stackoverflow.com/a/29341144/3010027

How to start Activity in adapter?

First Solution:

You can call start activity inside your adapter like this:

public class YourAdapter extends Adapter {
     private Context context;

     public YourAdapter(Context context) {
          this.context = context;     
     }

     public View getView(...){
         View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 context.startActivity(...);
             }
         });
     }
}

Second Solution:

You can call onClickListener of your button out of the YourAdapter class. Follow these steps:

Craete an interface like this:

public YourInterface{
         public void  yourMethod(args...);
}

Then inside your adapter:

    public YourAdapter extends BaseAdapter{
               private YourInterface listener;

           public YourAdapter (Context context, YourInterface listener){
                    this.listener = listener;
                    this.context = context;
           }

           public View getView(...){
                View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 listener.yourMethod(args);
             }
         });
}

And where you initiate yourAdapter will be like this:

YourAdapter adapter = new YourAdapter(getContext(), (args) -> {
            startActivity(...);
        });

This link can be useful for you.

Redirect from a view to another view

Purpose of view is displaying model. You should use controller to redirect request before creating model and passing it to view. Use Controller.RedirectToAction method for this.

Execute a file with arguments in Python shell

Actually, wouldn't we want to do this?

import sys
sys.argv = ['abc.py','arg1', 'arg2']
execfile('abc.py')

How to make my layout able to scroll down?

For using scroll view along with Relative layout :

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"> <!--IMPORTANT otherwise backgrnd img. will not fill the whole screen -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@drawable/background_image"
    >

    <!-- Bla Bla Bla i.e. Your Textviews/Buttons etc. -->
    </RelativeLayout>
</ScrollView>

How to run a script at a certain time on Linux?

Usually in Linux you use crontab for this kind of scduled tasks. But you have to specify the time when you "setup the timer" - so if you want it to be configurable in the file itself, you will have to create some mechanism to do that.

But in general, you would use for example:

30 1 * * 5 /path/to/script/script.sh

Would execute the script every Friday at 1:30 (AM) Here:

30 is minutes

1 is hour

next 2 *'s are day of month and month (in that order) and 5 is weekday

Difference between hamiltonian path and euler path

They are related but are neither dependent nor mutually exclusive. If a graph has an Eurler cycle, it may or may not also have a Hamiltonian cyle and vice versa.


Euler cycles visit every edge in the graph exactly once. If there are vertices in the graph with more than two edges, then by definition, the cycle will pass through those vertices more than once. As a result, vertices can be repeated but edges cannot.

Hamiltonian cycles visit every vertex in the graph exactly once (similar to the travelling salesman problem). As a result, neither edges nor vertices can be repeated.

base64 encode in MySQL

Looks like no, though it was requested, and there’s a UDF for it.

Edit: Or there’s… this. Ugh.

Adding hours to JavaScript Date object?

This is a easy way to get incremented or decremented data value.

const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour

const _date = new Date(date)
return new Date( _date.getTime() + inc )
return new Date( _date.getTime() + dec )

Format numbers in thousands (K) in Excel

[>=1000]#,##0,"K";[<=-1000]-#,##0,"K";0

teylyn's answer is great. This just adds negatives beyond -1000 following the same format.

Regular Expression with wildcards to match any character

The following should work:

ABC: *\([a-zA-Z]+\) *(.+)

Explanation:

ABC:            # match literal characters 'ABC:'
 *              # zero or more spaces
\([a-zA-Z]+\)   # one or more letters inside of parentheses
 *              # zero or more spaces
(.+)            # capture one or more of any character (except newlines)

To get your desired grouping based on the comments below, you can use the following:

(ABC:) *(\([a-zA-Z]+\).+)

How to get primary key column in Oracle?

Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;

(This will list the primary key and then)

Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’; 

(This will give you the column, here PK_XYZ is the primay key name)

How to update cursor limit for ORA-01000: maximum open cursors exceed

RUn the following query to find if you are running spfile or not:

SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type" 
       FROM sys.v_$parameter WHERE name = 'spfile';

If the result is "SPFILE", then use the following command:

alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor

if the result is "PFILE", then use the following command:

alter system set open_cursors = 1000 ;

You can read about SPFILE vs PFILE here,

http://www.orafaq.com/node/5

Get Return Value from Stored procedure in asp.net

If you want to to know how to return a value from stored procedure to Visual Basic.NET. Please read this tutorial: How to return a value from stored procedure

I used the following stored procedure to return the value.

CREATE PROCEDURE usp_get_count

AS
BEGIN
 DECLARE @VALUE int;

 SET @VALUE=(SELECT COUNT(*) FROM tblCar);

 RETURN @VALUE;

END
GO

Difference between [routerLink] and routerLink

You'll see this in all the directives:

When you use brackets, it means you're passing a bindable property (a variable).

  <a [routerLink]="routerLinkVariable"></a>

So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below:

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!

But with variables, you have the opportunity to make it dynamic right?

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!


    updateRouterLinkVariable(){

        this.routerLinkVariable = '/about';
    }

Where as without brackets you're passing string only and you can't change it, it's hard coded and it'll be like that throughout your app.

<a routerLink="/home"></a>

UPDATE :

The other speciality about using brackets specifically for routerLink is that you can pass dynamic parameters to the link you're navigating to:

So adding a new variable

export class myComponent {
        private dynamicParameter = '129';
        public routerLinkVariable = "/home"; 

Updating the [routerLink]

  <a [routerLink]="[routerLinkVariable,dynamicParameter]"></a>

When you want to click on this link, it would become:

  <a href="/home/129"></a>

iOS application: how to clear notifications?

In Swift I'm using the following code inside my AppDelegate:

func applicationDidBecomeActive(application: UIApplication) {
    application.applicationIconBadgeNumber = 0
    application.cancelAllLocalNotifications()
}

Add a month to a Date

"mondate" is somewhat similar to "Date" except that adding n adds n months rather than n days:

> library(mondate)
> d <- as.Date("2004-01-31")
> as.mondate(d) + 1
mondate: timeunits="months"
[1] 2004-02-29

User Authentication in ASP.NET Web API

I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.

The client side code (CoffeeScript) to get the token is:

getAuthenticationToken = (username, password) ->
    dataToSend = "username=" + username + "&password=" + password
    dataToSend += "&grant_type=password"
    $.post("/token", dataToSend).success saveAccessToken

If successful the following is called, which saves the authentication token locally:

saveAccessToken = (response) ->
    window.authenticationToken = response.access_token

Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:

{ "Authorization": "Bearer " + window.authenticationToken }

How do I make a fully statically linked .exe with Visual Studio Express 2005?

I've had this same dependency problem and I also know that you can include the VS 8.0 DLLs (release only! not debug!---and your program has to be release, too) in a folder of the appropriate name, in the parent folder with your .exe:

How to: Deploy using XCopy (MSDN)

Also note that things are guaranteed to go awry if you need to have C++ and C code in the same statically linked .exe because you will get linker conflicts that can only be resolved by ignoring the correct libXXX.lib and then linking dynamically (DLLs).

Lastly, with a different toolset (VC++ 6.0) things "just work", since Windows 2000 and above have the correct DLLs installed.

Easy way to use variables of enum types as string in C?

I have created a simple templated class streamable_enum that uses stream operators << and >> and is based on the std::map<Enum, std::string>:

#ifndef STREAMABLE_ENUM_HPP
#define STREAMABLE_ENUM_HPP

#include <iostream>
#include <string>
#include <map>

template <typename E>
class streamable_enum
{
public:
    typedef typename std::map<E, std::string> tostr_map_t;
    typedef typename std::map<std::string, E> fromstr_map_t;

    streamable_enum()
    {}

    streamable_enum(E val) :
        Val_(val)
    {}

    operator E() {
        return Val_;
    }

    bool operator==(const streamable_enum<E>& e) {
        return this->Val_ == e.Val_;
    }

    bool operator==(const E& e) {
        return this->Val_ == e;
    }

    static const tostr_map_t& to_string_map() {
        static tostr_map_t to_str_(get_enum_strings<E>());
        return to_str_;
    }

    static const fromstr_map_t& from_string_map() {
        static fromstr_map_t from_str_(reverse_map(to_string_map()));
        return from_str_;
    }
private:
    E Val_;

    static fromstr_map_t reverse_map(const tostr_map_t& eToS) {
        fromstr_map_t sToE;
        for (auto pr : eToS) {
            sToE.emplace(pr.second, pr.first);
        }
        return sToE;
    }
};

template <typename E>
streamable_enum<E> stream_enum(E e) {
    return streamable_enum<E>(e);
}

template <typename E>
typename streamable_enum<E>::tostr_map_t get_enum_strings() {
    // \todo throw an appropriate exception or display compile error/warning
    return {};
}

template <typename E>
std::ostream& operator<<(std::ostream& os, streamable_enum<E> e) {
    auto& mp = streamable_enum<E>::to_string_map();
    auto res = mp.find(e);
    if (res != mp.end()) {
        os << res->second;
    } else {
        os.setstate(std::ios_base::failbit);
    }
    return os;
}

template <typename E>
std::istream& operator>>(std::istream& is, streamable_enum<E>& e) {
    std::string str;
    is >> str;
    if (str.empty()) {
        is.setstate(std::ios_base::failbit);
    }
    auto& mp = streamable_enum<E>::from_string_map();
    auto res = mp.find(str);
    if (res != mp.end()) {
        e = res->second;
    } else {
        is.setstate(std::ios_base::failbit);
    }
    return is;
}

#endif

Usage:

#include "streamable_enum.hpp"

using std::cout;
using std::cin;
using std::endl;

enum Animal {
    CAT,
    DOG,
    TIGER,
    RABBIT
};

template <>
streamable_enum<Animal>::tostr_map_t get_enum_strings<Animal>() {
    return {
        { CAT, "Cat"},
        { DOG, "Dog" },
        { TIGER, "Tiger" },
        { RABBIT, "Rabbit" }
    };
}

int main(int argc, char* argv []) {
    cout << "What animal do you want to buy? Our offering:" << endl;
    for (auto pr : streamable_enum<Animal>::to_string_map()) {          // Use from_string_map() and pr.first instead
        cout << " " << pr.second << endl;                               // to have them sorted in alphabetical order
    }
    streamable_enum<Animal> anim;
    cin >> anim;
    if (!cin) {
        cout << "We don't have such animal here." << endl;
    } else if (anim == Animal::TIGER) {
        cout << stream_enum(Animal::TIGER) << " was a joke..." << endl;
    } else {
        cout << "Here you are!" << endl;
    }

    return 0;
}

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

What is the difference between --save and --save-dev?

All explanations here are great, but lacking a very important thing: How do you install production dependencies only? (without the development dependencies). We separate dependencies from devDependencies by using --save or --save-dev. To install all we use:

npm i

To install only production packages we should use:

npm i --only=production

How do I load an org.w3c.dom.Document from XML in a string?

This works for me in Java 1.5 - I stripped out specific exceptions for readability.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;

public Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

Progress Bar with HTML and CSS

I like this one:

very slick with only this as HTML and the rest CSS3 that is backwards compatible (although it will have less eyecandy)

Edit Added code below, but taken directly from the page above, all credit to that author

_x000D_
_x000D_
.meter {_x000D_
  height: 20px;_x000D_
  /* Can be anything */_x000D_
  position: relative;_x000D_
  background: #555;_x000D_
  -moz-border-radius: 25px;_x000D_
  -webkit-border-radius: 25px;_x000D_
  border-radius: 25px;_x000D_
  padding: 10px;_x000D_
  -webkit-box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);_x000D_
  -moz-box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);_x000D_
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);_x000D_
}_x000D_
_x000D_
.meter>span {_x000D_
  display: block;_x000D_
  height: 100%;_x000D_
  -webkit-border-top-right-radius: 8px;_x000D_
  -webkit-border-bottom-right-radius: 8px;_x000D_
  -moz-border-radius-topright: 8px;_x000D_
  -moz-border-radius-bottomright: 8px;_x000D_
  border-top-right-radius: 8px;_x000D_
  border-bottom-right-radius: 8px;_x000D_
  -webkit-border-top-left-radius: 20px;_x000D_
  -webkit-border-bottom-left-radius: 20px;_x000D_
  -moz-border-radius-topleft: 20px;_x000D_
  -moz-border-radius-bottomleft: 20px;_x000D_
  border-top-left-radius: 20px;_x000D_
  border-bottom-left-radius: 20px;_x000D_
  background-color: #f1a165;_x000D_
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #f1a165), color-stop(1, #f36d0a));_x000D_
  background-image: -webkit-linear-gradient(top, #f1a165, #f36d0a);_x000D_
  background-image: -moz-linear-gradient(top, #f1a165, #f36d0a);_x000D_
  background-image: -ms-linear-gradient(top, #f1a165, #f36d0a);_x000D_
  background-image: -o-linear-gradient(top, #f1a165, #f36d0a);_x000D_
  -webkit-box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);_x000D_
  -moz-box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="meter">_x000D_
  <span style="width: 33%"></span>_x000D_
  <!-- I use my viewmodel in MVC to calculate the progress and then use @Model.progress to place it in my HTML with Razor -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Unable to connect to any of the specified mysql hosts. C# MySQL

Just ran into the same problem. Installing the .NET framework on the target machine solved the problem.

Better yet, make sure all required dependencies are present in the machine where the code will be running.

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

How can I change the Y-axis figures into percentages in a barplot?

ggplot2 and scales packages can do that:

y <- c(12, 20)/100
x <- c(1, 2)

library(ggplot2)
library(scales)
myplot <- qplot(as.factor(x), y, geom="bar")
myplot + scale_y_continuous(labels=percent)

It seems like the stat() option has been taken off, causing the error message. Try this:

library(scales)

myplot <- ggplot(mtcars, aes(factor(cyl))) + 
          geom_bar(aes(y = (..count..)/sum(..count..))) + 
          scale_y_continuous(labels=percent)

myplot

R dplyr: Drop multiple columns

You can try

iris %>% select(-!!drop.cols)

Can't access RabbitMQ web management interface after fresh install

Something that just happened to me and caused me some headaches:

I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).

The script had several of those "code" blocks:

rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"

Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.

Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.

... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:

rabbitmqctl change_password test test

(Another solution would have been to delete all users and then call the script again)

How do I delete an item or object from an array using ng-click?

This is a correct answer:

<a class="btn" ng-click="remove($index)">Delete</a>
$scope.remove=function($index){ 
  $scope.bdays.splice($index,1);     
}

In @charlietfl's answer. I think it's wrong since you pass $index as paramter but you use the wish instead in controller. Correct me if I'm wrong :)

Execute ssh with password authentication via windows command prompt

PuTTY's plink has a command-line argument for a password. Some other suggestions have been made in the answers to this question: using Expect (which is available for Windows), or writing a launcher in Python with Paramiko.

What is the point of WORKDIR on Dockerfile?

You can think of WORKDIR like a cd inside the container (it affects commands that come later in the Dockerfile, like the RUN command). If you removed WORKDIR in your example above, RUN npm install wouldn't work because you would not be in the /usr/src/app directory inside your container.

I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY is a relative path, so if you move your Dockerfile you may need to update those COPY commands.

Return only string message from Spring MVC 3 Controller

For outputing String as text/plain use:

@RequestMapping(value="/foo", method=RequestMethod.GET, produces="text/plain")
@ResponseBody
public String foo() {
    return "bar";
}

An "and" operator for an "if" statement in Bash

Quote:

The "-a" operator also doesn't work:

if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]

For a more elaborate explanation: [ and ] are not Bash reserved words. The if keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0 or false otherwise).

For trivial tests, there is the test program (man test).

As some find lines like if test -f filename; then foo bar; fi, etc. annoying, on most systems you find a program called [ which is in fact only a symlink to the test program. When test is called as [, you have to add ] as the last positional argument.

So if test -f filename is basically the same (in terms of processes spawned) as if [ -f filename ]. In both cases the test program will be started, and both processes should behave identically.

Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]] will parse to if + some job, the job being everything except the if itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([) is the command and the rest its positional arguments. There are remaining arguments after the first ].

Also not, [[ is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.

How do I install TensorFlow's tensorboard?

TensorBoard isn't a separate component. TensorBoard comes packaged with TensorFlow.

Do I use <img>, <object>, or <embed> for SVG files?

The best option is to use SVG Images on different devices :)

<img src="your-svg-image.svg" alt="Your Logo Alt" onerror="this.src='your-alternative-image.png'">

need to test if sql query was successful

Check this:

<?php
if (mysqli_num_rows(mysqli_query($con, sqlselectquery)) > 0)
{
    echo "found";
}
else
{
    echo "not found";
}
?>

<!----comment ---for select query to know row matching the condition are fetched or not--->

What's the difference between using "let" and "var"?

I think the terms and most of the examples are a bit overwhelming, The main issue i had personally with the difference is understanding what a "Block" is. At some point i realized, a block would be any curly brackets except for IF statement. an opening bracket { of a function or loop will define a new block, anything defined with let within it, will not be available after the closing bracket } of the same thing (function or loop); With that in mind, it was easier to understand:

_x000D_
_x000D_
let msg = "Hello World";_x000D_
_x000D_
function doWork() { // msg will be available since it was defined above this opening bracket!_x000D_
  let friends = 0;_x000D_
  console.log(msg);_x000D_
_x000D_
  // with VAR though:_x000D_
  for (var iCount2 = 0; iCount2 < 5; iCount2++) {} // iCount2 will be available after this closing bracket!_x000D_
  console.log(iCount2);_x000D_
  _x000D_
    for (let iCount1 = 0; iCount1 < 5; iCount1++) {} // iCount1 will not be available behind this closing bracket, it will return undefined_x000D_
  console.log(iCount1);_x000D_
  _x000D_
} // friends will no be available after this closing bracket!_x000D_
doWork();_x000D_
console.log(friends);
_x000D_
_x000D_
_x000D_

What is Activity.finish() method doing exactly?

Finish() method will destroy the current activity. You can use this method in cases when you dont want this activity to load again and again when the user presses back button. Basically it clears the activity from the.current stack.

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

Https Connection Android

Just use this method as your HTTPClient:

public static  HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

Transmitting newline character "\n"

Try using %0A in the URL, just like you've used %20 instead of the space character.

How to copy to clipboard in Vim?

I had issue because my vim was not supporting clipboard:

vim --version | grep clip
-clipboard       +insert_expand   +path_extra      +user_commands
+emacs_tags      -mouseshape      +startuptime     -xterm_clipboard

I installed vim-gnome (which support clipboard) and then checked again:

vim --version | grep clipboard
+clipboard       +insert_expand   +path_extra      +user_commands
+emacs_tags      +mouseshape      +startuptime     +xterm_clipboard

Now I am able to copy and paste using "+y and "+p respectively.

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

How do you close/hide the Android soft keyboard using Java?

Thanks to this SO answer, I derived the following which, in my case, works nicely when scrolling through the the fragments of a ViewPager...

private void hideKeyboard() {   
    // Check if no view has focus:
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

private void showKeyboard() {   
    // Check if no view has focus:
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
}

C/C++ line number

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

Setting the default active profile in Spring-boot

Currently using Maven + Spring Boot. Our solution was the following:

application.properties

#spring.profiles.active= # comment_out or remove

securityConfig.java

@Value(${spring.profiles.active:[default_profile_name]}")
private String ACTIVE_PROFILE_NAME;

Credit starts with MartinMlima. Similar answer provided here:

How do you get current active/default Environment profile programmatically in Spring?

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

I caught this error a few days ago.

IN my case it was because I was using a Transaction on a Singleton.

.Net does not work well with Singleton as stated above.

My solution was this:

public class DbHelper : DbHelperCore
{
    public DbHelper()
    {
        Connection = null;
        Transaction = null;
    }

    public static DbHelper instance
    {
        get
        {
            if (HttpContext.Current is null)
                return new DbHelper();
            else if (HttpContext.Current.Items["dbh"] == null)
                HttpContext.Current.Items["dbh"] = new DbHelper();

            return (DbHelper)HttpContext.Current.Items["dbh"];
        }
    }

    public override void BeginTransaction()
    {
        Connection = new SqlConnection(Entity.Connection.getCon);
        if (Connection.State == System.Data.ConnectionState.Closed)
            Connection.Open();
        Transaction = Connection.BeginTransaction();
    }
}

I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

Where is the Postgresql config file: 'postgresql.conf' on Windows?

postgresql.conf is located in PostgreSQL's data directory. The data directory is configured during the setup and the setting is saved as PGDATA entry in c:\Program Files\PostgreSQL\<version>\pg_env.bat, for example

@ECHO OFF
REM The script sets environment variables helpful for PostgreSQL

@SET PATH="C:\Program Files\PostgreSQL\<version>\bin";%PATH%
@SET PGDATA=D:\PostgreSQL\<version>\data
@SET PGDATABASE=postgres
@SET PGUSER=postgres
@SET PGPORT=5432
@SET PGLOCALEDIR=C:\Program Files\PostgreSQL\<version>\share\locale

Alternatively you can query your database with SHOW config_file; if you are a superuser.

How to get the absolute path to the public_html folder?

<?php

    // Get absolute path
    $path = getcwd(); // /home/user/public_html/test/test.php.   

    $path = substr($path, 0, strpos($path, "public_html"));

    $root = $path . "public_html/";

    echo $root; // This will output /home/user/public_html/

Change directory command in Docker?

You can run a script, or a more complex parameter to the RUN. Here is an example from a Dockerfile I've downloaded to look at previously:

RUN cd /opt && unzip treeio.zip && mv treeio-master treeio && \
    rm -f treeio.zip && cd treeio && pip install -r requirements.pip

Because of the use of '&&', it will only get to the final 'pip install' command if all the previous commands have succeeded.

In fact, since every RUN creates a new commit & (currently) an AUFS layer, if you have too many commands in the Dockerfile, you will use up the limits, so merging the RUNs (when the file is stable) can be a very useful thing to do.

What to return if Spring MVC controller method doesn't return value?

Here is example code what I did for an asynchronous method

@RequestMapping(value = "/import", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void importDataFromFile(@RequestParam("file") MultipartFile file) 
{
    accountingSystemHandler.importData(file, assignChargeCodes);
}

You do not need to return any thing from your method all you need to use this annotation so that your method should return OK in every case

@ResponseStatus(value = HttpStatus.OK)

Sort array by value alphabetically php

  • If you just want to sort the array values and don't care for the keys, use sort(). This will give a new array with numeric keys starting from 0.
  • If you want to keep the key-value associations, use asort().

See also the comparison table of sorting functions in PHP.

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

I stumbled on this question as I had the same error. Mine was due to a slightly different problem and since I resolved it on my own I thought it useful to share here. Original code with issue:

$comment = "$_POST['comment']";

Because of the enclosing double-quotes, the index is not dereferenced properly leading to the assignment error. In my case I chose to fix it like this:

$comment = "$_POST[comment]";

but dropping either pair of quotes works; it's a matter of style I suppose :)

String date to xmlgregoriancalendar conversion

For me the most elegant solution is this one:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");

Using Java 8.

Extended example:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");
System.out.println(result.getDay());
System.out.println(result.getMonth());
System.out.println(result.getYear());

This prints out:

7
1
2014

CSV with comma or semicolon?

Initially it was to be a comma, however as the comma is often used as a decimal point it wouldnt be such good separator, hence others like the semicolon, mostly country dependant

http://en.wikipedia.org/wiki/Comma-separated_values#Lack_of_a_standard

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Ubuntu 10.04 comes with the Suhosin patch only, which does not give you configuration options. But you can install php5-suhosin to solve this:

apt-get update
apt-get install php5-suhosin

Now you can edit /etc/php5/conf.d/suhosin.ini and set:

suhosin.memory_limit = 1G

Then using ini_set will work in a script:

ini_set('memory_limit', '256M');

How to debug SSL handshake using cURL?

openssl s_client -connect 127.0.0.1:6379 -state
CONNECTED(00000003)
SSL_connect:before SSL initialization
SSL_connect:SSLv3/TLS write client hello

Can I pass parameters by reference in Java?

Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:

Object o = "Hello";
mutate(o)
System.out.println(o);

private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!

Will print Hello to the console. The options if you wanted the above code to print Goodbye are to use an explicit reference as follows:

AtomicReference<Object> ref = new AtomicReference<Object>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!

private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }

How do I programmatically determine operating system in Java?

Below code shows the values that you can get from System API, these all things you can get through this API.

public class App {
    public static void main( String[] args ) {
        //Operating system name
        System.out.println(System.getProperty("os.name"));

        //Operating system version
        System.out.println(System.getProperty("os.version"));

        //Path separator character used in java.class.path
        System.out.println(System.getProperty("path.separator"));

        //User working directory
        System.out.println(System.getProperty("user.dir"));

        //User home directory
        System.out.println(System.getProperty("user.home"));

        //User account name
        System.out.println(System.getProperty("user.name"));

        //Operating system architecture
        System.out.println(System.getProperty("os.arch"));

        //Sequence used by operating system to separate lines in text files
        System.out.println(System.getProperty("line.separator"));

        System.out.println(System.getProperty("java.version")); //JRE version number

        System.out.println(System.getProperty("java.vendor.url")); //JRE vendor URL

        System.out.println(System.getProperty("java.vendor")); //JRE vendor name

        System.out.println(System.getProperty("java.home")); //Installation directory for Java Runtime Environment (JRE)

        System.out.println(System.getProperty("java.class.path"));

        System.out.println(System.getProperty("file.separator"));
    }
}

Answers:-

Windows 7
6.1
;
C:\Users\user\Documents\workspace-eclipse\JavaExample
C:\Users\user
user
amd64


1.7.0_71
http://java.oracle.com/
Oracle Corporation
C:\Program Files\Java\jre7
C:\Users\user\Documents\workspace-Eclipse\JavaExample\target\classes
\

How to convert rdd object to dataframe in spark

SparkSession has a number of createDataFrame methods that create a DataFrame given an RDD. I imagine one of these will work for your context.

For example:

def createDataFrame(rowRDD: RDD[Row], schema: StructType): DataFrame

Creates a DataFrame from an RDD containing Rows using the given schema.

javascript - pass selected value from popup window to parent window input box

use: opener.document.<id of document>.innerHTML = xmlhttp.responseText;

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

I was trying to create a web application with spring boot and I got the same error. After inspecting I found that I was missing a dependency. So, be sure to add following dependency to your pom.xml file.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency> 

LINQ with groupby and count

After calling GroupBy, you get a series of groups IEnumerable<Grouping>, where each Grouping itself exposes the Key used to create the group and also is an IEnumerable<T> of whatever items are in your original data set. You just have to call Count() on that Grouping to get the subtotal.

foreach(var line in data.GroupBy(info => info.metric)
                        .Select(group => new { 
                             Metric = group.Key, 
                             Count = group.Count() 
                        })
                        .OrderBy(x => x.Metric))
{
     Console.WriteLine("{0} {1}", line.Metric, line.Count);
}

> This was a brilliantly quick reply but I'm having a bit of an issue with the first line, specifically "data.groupby(info=>info.metric)"

I'm assuming you already have a list/array of some class that looks like

class UserInfo {
    string name;
    int metric;
    ..etc..
} 
...
List<UserInfo> data = ..... ;

When you do data.GroupBy(x => x.metric), it means "for each element x in the IEnumerable defined by data, calculate it's .metric, then group all the elements with the same metric into a Grouping and return an IEnumerable of all the resulting groups. Given your example data set of

    <DATA>           | Grouping Key (x=>x.metric) |
joe  1 01/01/2011 5  | 1
jane 0 01/02/2011 9  | 0
john 2 01/03/2011 0  | 2
jim  3 01/04/2011 1  | 3
jean 1 01/05/2011 3  | 1
jill 2 01/06/2011 5  | 2
jeb  0 01/07/2011 3  | 0
jenn 0 01/08/2011 7  | 0

it would result in the following result after the groupby:

(Group 1): [joe  1 01/01/2011 5, jean 1 01/05/2011 3]
(Group 0): [jane 0 01/02/2011 9, jeb  0 01/07/2011 3, jenn 0 01/08/2011 7]
(Group 2): [john 2 01/03/2011 0, jill 2 01/06/2011 5]
(Group 3): [jim  3 01/04/2011 1]

Exporting functions from a DLL with dllexport

I think _naked might get what you want, but it also prevents the compiler from generating the stack management code for the function. extern "C" causes C style name decoration. Remove that and that should get rid of your _'s. The linker doesn't add the underscores, the compiler does. stdcall causes the argument stack size to be appended.

For more, see: http://en.wikipedia.org/wiki/X86_calling_conventions http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx

The bigger question is why do you want to do that? What's wrong with the mangled names?

How to move or copy files listed by 'find' command in unix?

If you're using GNU find,

find . -mtime 1 -exec cp -t ~/test/ {} +

This works as well as piping the output into xargs while avoiding the pitfalls of doing so (it handles embedded spaces and newlines without having to use find ... -print0 | xargs -0 ...).

Adding a css class to select using @Html.DropDownList()

You Can do it using jQuery

  $("select").addClass("form-control")

here, Select is- html tag, Form-control is- class name

 @Html.DropDownList("SupplierId", "Select Supplier")

and here, SupplierId is ViewBagList, Select Supplier is - Display Name

How to upgrade Angular CLI project?

Just use the build-in feature of Angular CLI

ng update

to update to the latest version.

What's the difference between a web site and a web application?

A website might just be static content - a web application would have dynamic content. It is a very fuzzy line.

Make an image width 100% of parent div, but not bigger than its own width

I would use the property display: table-cell

Here is the link

INNER JOIN same table

Perhaps this should be the select (if I understand the question correctly)

select user.user_fname, user.user_lname, parent.user_fname, parent.user_lname
... As before

How to sum columns in a dataTable?

It's a pity to use .NET and not use collections and lambda to save your time and code lines This is an example of how this works: Transform yourDataTable to Enumerable, filter it if you want , according a "FILTER_ROWS_FIELD" column, and if you want, group your data by a "A_GROUP_BY_FIELD". Then get the count, the sum, or whatever you wish. If you want a count and a sum without grouby don't group the data

var groupedData = from b in yourDataTable.AsEnumerable().Where(r=>r.Field<int>("FILTER_ROWS_FIELD").Equals(9999))
                          group b by b.Field<string>("A_GROUP_BY_FIELD") into g
                          select new
                          {
                              tag = g.Key,
                              count = g.Count(),
                              sum = g.Sum(c => c.Field<double>("rvMoney"))
                          };

What is the difference between <html lang="en"> and <html lang="en-US">?

<html lang="en">
<html lang="en-US">

The first lang tag only specifies a language code. The second specifies a language code, followed by a country code.

What other values can follow the dash? According to w3.org "Any two-letter subcode is understood to be a [ISO3166] country code." so does that mean any value listed under the alpha-2 code is an accepted value?

Yes, however the value may or may not have any real meaning.

<html lang="en-US"> essentially means "this page is in the US style of English." In a similar way, <html lang="en-GB"> would mean "this page is in the United Kingdom style of English."

If you really wanted to specify an invalid combination, you could. It wouldn't mean much, but <html lang="en-ES"> is valid according to the specification, as I understand it. However, that language/country combination won't do much since English isn't commonly spoken in Spain.

I mean does this somehow further help the browser to display the page?

It doesn't help the browser to display the page, but it is useful for search engines, screen readers, and other things that might read and try to interpret the page, besides human beings.

How to add data to DataGridView

My favorite way to do this is with an extension function called 'Map':

public static void Map<T>(this IEnumerable<T> source, Action<T> func)
{
    foreach (T i in source)
        func(i);
}

Then you can add all the rows like so:

X.Map(item => this.dataGridView1.Rows.Add(item.ID, item.Name));

Xcode Error: "The app ID cannot be registered to your development team."

I had the issue with different development teams. I just checked the schema signings and picked the correct development team for the schemas that I needed:

Ss from Xcode

Django auto_now and auto_now_add

I needed something similar today at work. Default value to be timezone.now(), but editable both in admin and class views inheriting from FormMixin, so for created in my models.py the following code fulfilled those requirements:

from __future__ import unicode_literals
import datetime

from django.db import models
from django.utils.functional import lazy
from django.utils.timezone import localtime, now

def get_timezone_aware_now_date():
    return localtime(now()).date()

class TestDate(models.Model):
    created = models.DateField(default=lazy(
        get_timezone_aware_now_date, datetime.date)()
    )

For DateTimeField, I guess remove the .date() from the function and change datetime.date to datetime.datetime or better timezone.datetime. I haven't tried it with DateTime, only with Date.

There is already an open DataReader associated with this Command which must be closed first

In my case, I had to set the MultipleActiveResultSets to True in the connection string.
Then it appeared another error (the real one) about not being able to run 2 (SQL) commands at the same time over the same data context! (EF Core, Code first)
So the solution for me was to look for any other asynchronous command execution and turn them to synchronous, as I had just one DbContext for both commands.

I hope it helps you

Conditionally hide CommandField or ButtonField in Gridview

You can hide a CommandField or ButtonField based on the position (index) in the GridView.

For example, if your CommandField is in the first position (index = 0), you can hide it adding the following code in the event RowDataBound of the GridView:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((System.Web.UI.Control)e.Row.Cells[0].Controls[0]).Visible = false;
    }
}

Convert Xml to Table SQL Server

The sp_xml_preparedocument stored procedure will parse the XML and the OPENXML rowset provider will show you a relational view of the XML data.

For details and more examples check the OPENXML documentation.

As for your question,

DECLARE @XML XML
SET @XML = '<rows><row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row></rows>'

DECLARE @handle INT  
DECLARE @PrepareXmlStatus INT  

EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML  

SELECT  *
FROM    OPENXML(@handle, '/rows/row', 2)  
    WITH (
    IdInvernadero INT,
    IdProducto INT,
    IdCaracteristica1 INT,
    IdCaracteristica2 INT,
    Cantidad INT,
    Folio INT
    )  


EXEC sp_xml_removedocument @handle 

How do I attach events to dynamic HTML elements with jQuery?

After jQuery 1.7 the preferred methods are .on() and .off()

Sean's answer shows an example.

Now Deprecated:

Use the jQuery functions .live() and .die(). Available in jQuery 1.3.x

From the docs:

To display each paragraph's text in an alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Also, the livequery plugin does this and has support for more events.

Iterating through a list to render multiple widgets in Flutter?

For googler, I wrote a simple Stateless Widget containing 3 method mentioned in this SO. Hope this make it easier to understand.

import 'package:flutter/material.dart';

class ListAndFP extends StatelessWidget {
  final List<String> items = ['apple', 'banana', 'orange', 'lemon'];

  //  for in (require dart 2.2.2 SDK or later)
  Widget method1() {
    return Column(
      children: <Widget>[
        Text('You can put other Widgets here'),
        for (var item in items) Text(item),
      ],
    );
  }

  // map() + toList() + Spread Property
  Widget method2() {
    return Column(
      children: <Widget>[
        Text('You can put other Widgets here'),
        ...items.map((item) => Text(item)).toList(),
      ],
    );
  }

  // map() + toList()
  Widget method3() {
    return Column(
      // Text('You CANNOT put other Widgets here'),
      children: items.map((item) => Text(item)).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: method1(),
    );
  }
}

Escape dot in a regex range

On this web page, I see that:

"Remember that the dot is not a metacharacter inside a character class, so we do not need to escape it with a backslash."

So I guess the escaping of it is unnecessary...

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

$(form).ajaxSubmit is not a function

Try ajaxsubmit library. It does ajax submition as well as validation via ajax.

Also configuration is very flexible to support any kind of UI.

Live demo available with js, css and html examples.

Border Height on CSS

Yes, you can set the line height after defining the border like this:

border-right: 1px solid;
line-height: 10px;

Compress images on client side before uploading

I just developed a javascript library called JIC to solve that problem. It allows you to compress jpg and png on the client side 100% with javascript and no external libraries required!

You can try the demo here : http://makeitsolutions.com/labs/jic and get the sources here : https://github.com/brunobar79/J-I-C

Remote origin already exists on 'git push' to a new repository

You can simply edit your configuration file in a text editor.

In the ~/.gitconfig you need to put in something like the following:

[user]
        name  = Uzumaki Naruto
        email = [email protected]

[github]
        user = myname
        token = ff44ff8da195fee471eed6543b53f1ff

In the oldrep/.git/config file (in the configuration file of your repository):

[remote "github"]
        url = [email protected]:myname/oldrep.git
        push  = +refs/heads/*:refs/heads/*
        push  = +refs/tags/*:refs/tags/*

If there is a remote section in your repository's configuration file, and the URL matches, you need only to add push configuration. If you use a public URL for fetching, you can put in the URL for pushing as 'pushurl' (warning: this requires the just-released Git version 1.6.4).

What version of MongoDB is installed on Ubuntu

To be complete, a short introduction for "shell noobs":

First of all, start your shell - you can find it inside the common desktop environments under the name "Terminal" or "Shell" somewhere in the desktops application menu.

You can also try using the key combo CTRL+F2, followed by one of those commands (depending on the desktop envrionment you're using) and the ENTER key:

xfce4-terminal
gnome-console
terminal
rxvt
konsole

If all of the above fail, try using xterm - it'll work in most cases.

Hint for the following commands: Execute the commands without the $ - it's just a marker identifying that you're on the shell.

After that just fire up mongod with the --version flag:

$ mongod --version

It shows you then something like

$ mongod --version
db version v2.4.6
Wed Oct 16 16:17:00.241 git version: nogitversion

To update it just execute

$ sudo apt-get update

and then

$ sudo apt-get install mongodb

How can I pretty-print JSON using node.js?

Another workaround would be to make use of prettier to format the JSON. The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.

const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Try:

html, body {
    height: 102%;
}
.wrapper {
    position: relative;
    height: 100%;
    width: 100%;
}
.div {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 1000px;
    min-height: 100%;
}

Haven't tested it yet...

JQuery create a form and add elements to it programmatically

You need to append form itself to body too:

$form = $("<form></form>");
$form.append('<input type="button" value="button">');
$('body').append($form);

Notepad++ incrementally replace

You can do it using Powershell through regex and foreach loop, if you store your values in file input.txt:

$initialNum=1; $increment=1; $tmp = Get-Content input.txt | foreach {  $n = [regex]::match($_,'id="(\d+)"').groups[1
].value; if ($n) {$_ -replace "$n", ([int32]$initialNum+$increment); $increment=$increment+1;} else {$_}; }

After that you can store $tmp in file using $tmp > result.txt. This doesn't need data to be in columns.

Reshape an array in NumPy

There are two possible result rearrangements (following example by @eumiro). Einops package provides a powerful notation to describe such operations non-ambigously

>> a = np.arange(18).reshape(9,2)

# this version corresponds to eumiro's answer
>> einops.rearrange(a, '(x y) z -> z y x', x=3)

array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

# this has the same shape, but order of elements is different (note that each paer was trasnposed)
>> einops.rearrange(a, '(x y) z -> z x y', x=3)

array([[[ 0,  2,  4],
        [ 6,  8, 10],
        [12, 14, 16]],

       [[ 1,  3,  5],
        [ 7,  9, 11],
        [13, 15, 17]]])

How to make HTML table cell editable?

This is a runnable example.

_x000D_
_x000D_
$(function(){
  $("td").click(function(event){
    if($(this).children("input").length > 0)
          return false;

    var tdObj = $(this);
    var preText = tdObj.html();
    var inputObj = $("<input type='text' />");
    tdObj.html("");

    inputObj.width(tdObj.width())
            .height(tdObj.height())
            .css({border:"0px",fontSize:"17px"})
            .val(preText)
            .appendTo(tdObj)
            .trigger("focus")
            .trigger("select");

    inputObj.keyup(function(event){
      if(13 == event.which) { // press ENTER-key
        var text = $(this).val();
        tdObj.html(text);
      }
      else if(27 == event.which) {  // press ESC-key
        tdObj.html(preText);
      }
    });

    inputObj.click(function(){
      return false;
    });
  });
});
_x000D_
<html>
    <head>
        <!-- jQuery source -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>
    <body>
        <table align="center">
            <tr> <td>id</td> <td>name</td> </tr>
            <tr> <td>001</td> <td>dog</td> </tr>
            <tr> <td>002</td> <td>cat</td> </tr>
            <tr> <td>003</td> <td>pig</td> </tr>
        </table>
    </body>
</html>
_x000D_
_x000D_
_x000D_

Duplicate line in Visual Studio Code

The duplicate can be achieved by CTRL+C and CTRL+V with cursor in the line without nothing selected.

What's the best way to send a signal to all members of a process group?

In sh the jobs command will list the background processes. In some cases it might be better to kill the newest process first, e.g. the older one created a shared socket. In those cases sort the PIDs in reverse order. Sometimes you want to wait moment for the jobs to write something on disk or stuff like that before they stop.

And don't kill if you don't have to!

for SIGNAL in TERM KILL; do
  for CHILD in $(jobs -s|sort -r); do
    kill -s $SIGNAL $CHILD
    sleep $MOMENT
  done
done

XML Document to String

Assuming doc is your instance of org.w3c.dom.Document:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

How to comment a block in Eclipse?

Eclipse Oxygen with CDT, PyDev:

Block comments under Source menu

Add Comment Block Ctrl + 4

Add Single Comment Block Ctrl+Shift+4

Remove Comment Block Ctrl + 5

Adobe Acrobat Pro make all pages the same dimension

You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.

CSS/HTML: What is the correct way to make text italic?

Perhaps it has no special meaning and only needs to be rendered in italics to separate it presentationally from the text preceding it.

If it has no special meaning, why does it need to be separated presentationally from the text preceding it? This run of text looks a bit weird, because I’ve italicised it for no reason.

I do take your point though. It’s not uncommon for designers to produce designs that vary visually, without varying meaningfully. I’ve seen this most often with boxes: designers will give us designs including boxes with various combinations of colours, corners, gradients and drop-shadows, with no relation between the styles, and the meaning of the content.

Because these are reasonably complex styles (with associated Internet Explorer issues) re-used in different places, we create classes like box-1, box-2, so that we can re-use the styles.

The specific example of making some text italic is too trivial to worry about though. Best leave minutiae like that for the Semantic Nutters to argue about.

Use and meaning of "in" in an if statement?

You are used to using the javascript if, and I assume you know how it works.

in is a Pythonic way of implementing iteration. It's supposed to be easier for non-programmatic thinkers to adopt, but that can sometimes make it harder for programmatic thinkers, ironically.

When you say if x in y, you are literally saying:

"if x is in y", which assumes that y has an index. In that if statement then, each object at each index in y is checked against the condition.

Similarly,

for x in y

iterates through x's in y, where y is that indexable set of items.

Think of the if situation this way (pseudo-code):

for i in next:
    if i == "0" || i == "1":
        how_much = int(next)

It takes care of the iteration over next for you.

Happy coding!

Suppress console output in PowerShell

Try redirecting the output like this:

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

You can use like the following

string result = null;
object value = cmd.ExecuteScalar();
 if (value != null)
 {
    result = value.ToString();
 }     
 conn.Close();
return result;

How to remove only 0 (Zero) values from column in excel 2010

Press Control + H, then select Options and check Match entire cell contents and Match case. In the Find what field type a 0, and leave the Replace with field blank. Then Replace All. This will remove all of the zeros that are stand alone.

Set initially selected item in Select list in Angular2

You can achieve the same using

<select [ngModel]="object">
  <option *ngFor="let object of objects;let i= index;" [value]="object.value" selected="i==0">{{object.name}}</option>
</select>

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

Change onClick attribute with javascript

You want to do this - set a function that will be executed to respond to the onclick event:

document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;

The things you are doing don't work because:

  1. The onclick event handler expects to have a function, here you are assigning a string

    document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
    
  2. In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:

    document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
    

How do I get the current timezone name in Postgres 9.3?

I don't think this is possible using PostgreSQL alone in the most general case. When you install PostgreSQL, you pick a time zone. I'm pretty sure the default is to use the operating system's timezone. That will usually be reflected in postgresql.conf as the value of the parameter "timezone". But the value ends up as "localtime". You can see this setting with the SQL statement.

show timezone;

But if you change the timezone in postgresql.conf to something like "Europe/Berlin", then show timezone; will return that value instead of "localtime".

So I think your solution will involve setting "timezone" in postgresql.conf to an explicit value rather than the default "localtime".

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

Scenario 1

In client application (application is not web application, e.g may be swing app)

private static ApplicationContext context = new  ClassPathXmlApplicationContext("test-client.xml");

context.getBean(name);

No need of web.xml. ApplicationContext as container for getting bean service. No need for web server container. In test-client.xml there can be Simple bean with no remoting, bean with remoting.

Conclusion: In Scenario 1 applicationContext and DispatcherServlet are not related.

Scenario 2

In a server application (application deployed in server e.g Tomcat). Accessed service via remoting from client program (e.g Swing app)

Define listener in web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

At server startup ContextLoaderListener instantiates beans defined in applicationContext.xml.

Assuming you have defined the following in applicationContext.xml:

<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />
<import resource="test4.xml" />

The beans are instantiated from all four configuration files test1.xml, test2.xml, test3.xml, test4.xml.

Conclusion: In Scenario 2 applicationContext and DispatcherServlet are not related.

Scenario 3

In a web application with spring MVC.

In web.xml define:

<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
</servlet>

<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

When Tomcat starts, beans defined in springweb-servlet.xml are instantiated. DispatcherServlet extends FrameworkServlet. In FrameworkServlet bean instantiation takes place for springweb . In our case springweb is FrameworkServlet.

Conclusion: In Scenario 3 applicationContext and DispatcherServlet are not related.

Scenario 4

In web application with spring MVC. springweb-servlet.xml for servlet and applicationContext.xml for accessing the business service within the server program or for accessing DB service in another server program.

In web.xml the following are defined:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>springweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        
</servlet>

<servlet-mapping>
    <servlet-name>springweb</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

At server startup, ContextLoaderListener instantiates beans defined in applicationContext.xml; assuming you have declared herein:

<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />
<import resource="test4.xml" />

The beans are all instantiated from all four test1.xml, test2.xml, test3.xml, test4.xml. After the completion of bean instantiation defined in applicationContext.xml, beans defined in springweb-servlet.xml are instantiated.

So the instantiation order is: the root (application context), then FrameworkServlet.

Now it should be clear why they are important in which scenario.

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

You are passing a target array of shape (x-dim, y-dim) while using as loss categorical_crossentropy. categorical_crossentropy expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:

from keras.utils import to_categorical
y_binary = to_categorical(y_int)

Alternatively, you can use the loss function sparse_categorical_crossentropy instead, which does expect integer targets.

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

How to set the color of "placeholder" text?

::-webkit-input-placeholder { /* WebKit browsers */
    color:    #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #999;
}

IO Error: The Network Adapter could not establish the connection

I was having issues with this as well. I was using the jdbc connection string to connect to the database. The hostname was incorrectly configured in the string. I am using Mac, and the same string was being used on Windows machines without an issue. On my connection string, I had to make sure that I had the full url with the appending "organizationname.com" to the end of the hostname.

Hope this helps.

What is the best way to search the Long datatype within an Oracle database?

First convert LONG type column to CLOB type then use LIKE condition, for example:

CREATE TABLE tbl_clob AS
   SELECT to_lob(long_col) lob_col FROM tbl_long;

SELECT * FROM tbl_clob WHERE lob_col LIKE '%form%';

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

There's no need to downgrade Android Tools. On Windows, Gradle moved from:

C:\Users\you_username\AppData\Local\Android\sdk\tools

to:

C:\Program Files\Android\Android Studio\plugins\android\lib\templates\gradle\wrapper

So you just need to adjust your path so that it points to the right folder.

How can I test a change made to Jenkinsfile locally?

A bit late to the party, but that's why I wrote jenny, a small reimplementation of some core Jenkinsfile steps. (https://github.com/bmustiata/jenny)

How to quickly clear a JavaScript Object?

So to recap your question: you want to avoid, as much as possible, trouble with the IE6 GC bug. That bug has two causes:

  1. Garbage Collection occurs once every so many allocations; therefore, the more allocations you make, the oftener GC will run;
  2. The more objects you've got ‘in the air’, the more time each Garbage Collection run takes (since it'll crawl through the entire list of objects to see which are marked as garbage).

The solution to cause 1 seems to be: keep the number of allocations down; assign new objects and strings as little as possible.

The solution to cause 2 seems to be: keep the number of 'live' objects down; delete your strings and objects as soon as you don't need them anymore, and create them afresh when necessary.

To a certain extent, these solutions are contradictory: to keep the number of objects in memory low will entail more allocations and de-allocations. Conversely, constantly reusing the same objects could mean keeping more objects in memory than strictly necessary.


Now for your question. Whether you'll reset an object by creating a new one, or by deleting all its properties: that will depend on what you want to do with it afterwards.

You’ll probably want to assign new properties to it:

  • If you do so immediately, then I suggest assigning the new properties straightaway, and skip deleting or clearing first. (Make sure that all properties are either overwritten or deleted, though!)
  • If the object won't be used immediately, but will be repopulated at some later stage, then I suggest deleting it or assigning it null, and create a new one later on.

There's no fast, easy to use way to clear a JScript object for reuse as if it were a new object — without creating a new one. Which means the short answer to your question is ‘No’, like jthompson says.

Why dividing two integers doesn't get a float?

Dividing two integers will result in an integer (whole number) result.

You need to cast one number as a float, or add a decimal to one of the numbers, like a/350.0.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Thanks Friend, i got an answer. This is only possible because of your help. you all give me a ray of hope towards resolving this problem.

Here is the code:

package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Facebook {
    public static void main(String args[]){
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.facebook.com");
        WebElement email= driver.findElement(By.id("email"));
        Actions builder = new Actions(driver);
        Actions seriesOfActions = builder.moveToElement(email).click().sendKeys(email, "[email protected]");
        seriesOfActions.perform();
        WebElement pass = driver.findElement(By.id("pass"));
        WebElement login =driver.findElement(By.id("u_0_b"));
        Actions seriesOfAction = builder.moveToElement(pass).click().sendKeys(pass, "naveench").click(login);
        seriesOfAction.perform();
        driver.
    }    
}

Generate GUID in MySQL for existing Data?

Just a minor addition to make as I ended up with a weird result when trying to modify the UUIDs as they were generated. I found the answer by Rakesh to be the simplest that worked well, except in cases where you want to strip the dashes.

For reference:

UPDATE some_table SET some_field=(SELECT uuid());

This worked perfectly on its own. But when I tried this:

UPDATE some_table SET some_field=(REPLACE((SELECT uuid()), '-', ''));

Then all the resulting values were the same (not subtly different - I quadruple checked with a GROUP BY some_field query). Doesn't matter how I situated the parentheses, the same thing happens.

UPDATE some_table SET some_field=(REPLACE(SELECT uuid(), '-', ''));

It seems when surrounding the subquery to generate a UUID with REPLACE, it only runs the UUID query once, which probably makes perfect sense as an optimization to much smarter developers than I, but it didn't to me.

To resolve this, I just split it into two queries:

UPDATE some_table SET some_field=(SELECT uuid());
UPDATE some_table SET some_field=REPLACE(some_field, '-', '');

Simple solution, obviously, but hopefully this will save someone the time that I just lost.

Using reCAPTCHA on localhost

Yes, this an older question but this may be helping all the users having problems with reCaptcha on localhost. Google indeed says "By default, all keys work on 'localhost' (or '127.0.0.1')" but for real using reCaptcha on localhost may cause problems. In my case I solved mine using secure token

I posted a WORKING SOLUTION for PHP here

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

Select and trigger click event of a radio button in jquery

In my case i had to load images on radio button click, I just uses the regular onclick event and it worked for me.

 <input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion"  onclick="return get_images(this, {{color.id}})">

<script>
  function get_images(obj, color){
    console.log($("input[type='radio'][name='colors']:checked").val());

  }
  </script>

Validate fields after user has left a field

We can use onfocus and onblur functions. Would be simple and best.

<body ng-app="formExample">
  <div ng-controller="ExampleController">
  <form novalidate class="css-form">
    Name: <input type="text" ng-model="user.name" ng-focus="onFocusName='focusOn'" ng-blur="onFocusName=''" ng-class="onFocusName" required /><br />
    E-mail: <input type="email" ng-model="user.email" ng-focus="onFocusEmail='focusOn'" ng-blur="onFocusEmail=''" ng-class="onFocusEmail" required /><br />
  </form>
</div>

<style type="text/css">
 .css-form input.ng-invalid.ng-touched {
    border: 1px solid #FF0000;
    background:#FF0000;
   }
 .css-form input.focusOn.ng-invalid {
    border: 1px solid #000000;
    background:#FFFFFF;
 }
</style>

Try here:

http://plnkr.co/edit/NKCmyru3knQiShFZ96tp?p=preview

How to remove a class from elements in pure JavaScript?

Given worked for me.

document.querySelectorAll(".widget.hover").forEach(obj=>obj.classList.remove("hover"));

Set value of textbox using JQuery

You're targeting the wrong item with that jQuery selector. The name of your search bar is searchBar, not the id. What you want to use is $('#main_search').val('hi').

How to Retrieve value from JTextField in Java Swing?

testField.getText()

See the java doc for JTextField

Sample code can be:

button.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent ae){
      String textFieldValue = testField.getText();
      // .... do some operation on value ...
   }
})

Breaking out of a for loop in Java

break; is what you need to break out of any looping statement like for, while or do-while.

In your case, its going to be like this:-

for(int x = 10; x < 20; x++) {
         // The below condition can be present before or after your sysouts, depending on your needs.
         if(x == 15){
             break; // A unlabeled break is enough. You don't need a labeled break here.
         }
         System.out.print("value of x : " + x );
         System.out.print("\n");
}

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

This is a fast way to encode the array, the array shape and the array dtype:

def numpy_to_bytes(arr: np.array) -> str:
    arr_dtype = bytearray(str(arr.dtype), 'utf-8')
    arr_shape = bytearray(','.join([str(a) for a in arr.shape]), 'utf-8')
    sep = bytearray('|', 'utf-8')
    arr_bytes = arr.ravel().tobytes()
    to_return = arr_dtype + sep + arr_shape + sep + arr_bytes
    return to_return

def bytes_to_numpy(serialized_arr: str) -> np.array:
    sep = '|'.encode('utf-8')
    i_0 = serialized_arr.find(sep)
    i_1 = serialized_arr.find(sep, i_0 + 1)
    arr_dtype = serialized_arr[:i_0].decode('utf-8')
    arr_shape = tuple([int(a) for a in serialized_arr[i_0 + 1:i_1].decode('utf-8').split(',')])
    arr_str = serialized_arr[i_1 + 1:]
    arr = np.frombuffer(arr_str, dtype = arr_dtype).reshape(arr_shape)
    return arr

To use the functions:

a = np.ones((23, 23), dtype = 'int')
a_b = numpy_to_bytes(a)
a1 = bytes_to_numpy(a_b)
np.array_equal(a, a1) and a.shape == a1.shape and a.dtype == a1.dtype

Difference in make_shared and normal shared_ptr in C++

If you need special memory alignment on the object controlled by shared_ptr, you cannot rely on make_shared, but I think it's the only one good reason about not using it.

The Android emulator is not starting, showing "invalid command-line parameter"

There is currently a problem with R12 where the SDK location cannot contain any spaces.

The default installation location is: C:\Programme Files(x86)\Android\android-sdk. They are currently fixing the problem but you can currently work around it by changing the SDK location path in eclipse to C:\PROGRA~2\Android\android-sdk.

If you are running 32-bit Windows, change the path to C:\PROGRA~1\Android\android-sdk.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

You have to put your main queue dispatching in the block that runs the computation. For example (here I create a dispatch queue and don't use a global one):

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
  // Do some computation here.

  // Update UI after computation.
  dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
  });
});

Of course, if you create a queue don't forget to dispatch_release if you're targeting an iOS version before 6.0.

Passing data to a jQuery UI Dialog

A solution inspired by Boris Guery that I employed looks like this: The link:

<a href="#" class = "remove {id:15} " id = "mylink1" >This is my clickable link</a>

bind an action to it:

$('.remove').live({
        click:function(){
            var data = $('#'+this.id).metadata();
            var id = data.id;
            var name = data.name;
            $('#dialog-delete')
                .data('id', id)
                .dialog('open');    
            return false;
        }
    });

And then to access the id field (in this case with value of 15:

$('#dialog-delete').dialog({
    autoOpen: false,
    position:'top',
    width: 345,
    resizable: false,
    draggable: false,
    modal: true,
    buttons: {            
        Cancel: function() {

            $(this).dialog('close');
        },
        'Confirm delete': function() {
            var id = $(this).data('id');
            $.ajax({
                url:"http://example.com/system_admin/admin/delete/"+id,
                type:'POST',
                dataType: "json",
                data:{is_ajax:1},
                success:function(msg){

                }
            })
        }
    }
});

How do I remove duplicates from a C# array?

Removing duplicate and ignore case sensitive using Distinct & StringComparer.InvariantCultureIgnoreCase

string[] array = new string[] { "A", "a", "b", "B", "a", "C", "c", "C", "A", "1" };
var r = array.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList();
Console.WriteLine(r.Count); // return 4 items

Simplest way to detect a mobile device in PHP

Simply you can follow the link. its very simple and very easy to use. I am using this. Its working fine.

http://mobiledetect.net/

use like this

//include the file
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {
 //do some code
}

// Any tablet device.
if( $detect->isTablet() ){
 //do some code
}

Inner join vs Where

i had this conundrum today when inspecting one of our sp's timing out in production, changed an inner join on a table built from an xml feed to a 'where' clause instead....average exec time is now 80ms over 1000 executions, whereas before average exec was 2.2 seconds...major difference in the execution plan is the dissapearance of a key lookup... The message being you wont know until youve tested using both methods.

cheers.

What are the differences between normal and slim package of jquery?

The short answer taken from the announcement of jQuery 3.0 Final Release :

Along with the regular version of jQuery that includes the ajax and effects modules, we’re releasing a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code.

The file size (gzipped) is about 6k smaller, 23.6k vs 30k.

Google Chrome redirecting localhost to https

@Adiyat Mubarak answer did not work for me. When I attempted to clear the cache and hard-reload, the page still redirected to https.

My solution: In the upper right-hand corner of the url bar (just to the left of the favorites star icon) there is an icon with an "x" through it. Right-click on that, and it will say something about "unsafe scripts", then there is an option to load them anyway. Do that.

UTF-8 text is garbled when form is posted as multipart/form-data

I think i'am late for the party but when you use a wildfly, you can add an default-encoding to the standalone.xml. Just search in the standalone.xml for

<servlet-container name="default"> 

and add encoding like this:

<servlet-container name="default" default-encoding="UTF-8">

How to add a WiX custom action that happens only on uninstall (via MSI)?

Here's a set of properties i made that feel more intuitive to use than the built in stuff. The conditions are based off of the truth table supplied above by ahmd0.

<!-- truth table for installer varables (install vs uninstall vs repair vs upgrade) https://stackoverflow.com/a/17608049/1721136 -->
 <SetProperty Id="_INSTALL"   After="FindRelatedProducts" Value="1"><![CDATA[Installed="" AND PREVIOUSVERSIONSINSTALLED=""]]></SetProperty>
 <SetProperty Id="_UNINSTALL" After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED="" AND REMOVE="ALL"]]></SetProperty>
 <SetProperty Id="_CHANGE"    After="FindRelatedProducts" Value="1"><![CDATA[Installed<>"" AND REINSTALL="" AND PREVIOUSVERSIONSINSTALLED<>"" AND REMOVE=""]]></SetProperty>
 <SetProperty Id="_REPAIR"    After="FindRelatedProducts" Value="1"><![CDATA[REINSTALL<>""]]></SetProperty>
 <SetProperty Id="_UPGRADE"   After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED<>"" ]]></SetProperty>

Here's some sample usage:

  <Custom Action="CaptureExistingLocalSettingsValues" After="InstallInitialize">NOT _UNINSTALL</Custom>
  <Custom Action="GetConfigXmlToPersistFromCmdLineArgs" After="InstallInitialize">_INSTALL OR _UPGRADE</Custom>
  <Custom Action="ForgetProperties" Before="InstallFinalize">_UNINSTALL OR _UPGRADE</Custom>
  <Custom Action="SetInstallCustomConfigSettingsArgs" Before="InstallCustomConfigSettings">NOT _UNINSTALL</Custom>
  <Custom Action="InstallCustomConfigSettings" Before="InstallFinalize">NOT _UNINSTALL</Custom>

Issues:

How to create EditText with rounded corners?

With the Material Components Library you can use the MaterialShapeDrawable to draw custom shapes.

With a EditText you can do:

    <EditText
        android:id="@+id/edittext"
        ../>

Then create a MaterialShapeDrawable:

float radius = getResources().getDimension(R.dimen.default_corner_radius);

EditText editText = findViewById(R.id.edittext);
//Apply the rounded corners 
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
                .toBuilder()
                .setAllCorners(CornerFamily.ROUNDED,radius)
                .build();

MaterialShapeDrawable shapeDrawable = 
            new MaterialShapeDrawable(shapeAppearanceModel);
//Apply a background color
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.white));
//Apply a stroke
shapeDrawable.setStroke(2.0f, ContextCompat.getColor(this,R.color.colorAccent));

ViewCompat.setBackground(editText,shapeDrawable);

enter image description here

It requires the version 1.1.0 of the library.

wget ssl alert handshake failure

I was in SLES12 and for me it worked after upgrading to wget 1.14, using --secure-protocol=TLSv1.2 and using --auth-no-challenge.

wget --no-check-certificate --secure-protocol=TLSv1.2 --user=satul --password=xxx --auth-no-challenge -v --debug https://jenkins-server/artifact/build.x86_64.tgz

Setting PATH environment variable in OSX permanently

For setting up path in Mac two methods can be followed.

  1. Creating a file for variable name and paste the path there under /etc/paths.d and source the file to profile_bashrc.
  2. Export path variable in ~/.profile_bashrc as

    export VARIABLE_NAME = $(PATH_VALUE)

AND source the the path. Its simple and stable.

You can set any path variable by Mac terminal or in linux also.

How to get a jqGrid cell value when editing

I think a better solution than using getCell which as you know returns some html when in edit mode is to use jquery to access the fields directly. The problem with trying to parse like you are doing is that it will only work for input fields (not things like select), and it won't work if you have done some customizations to the input fields. The following will work with inputs and select elements and is only one line of code.

ondblClickRow: function(rowid) {
    var val = $('#' + rowid + '_MyCol').val();
}

How to Customize the time format for Python logging?

Using logging.basicConfig, the following example works for me:

logging.basicConfig(
    filename='HISTORYlistener.log',
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)

This allows you to format & config all in one line. A resulting log record looks as follows:

2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start

How to use "Share image using" sharing Intent to share images in android?

try this,

Uri imageUri = Uri.parse("android.resource://your.package/drawable/fileName");
      Intent intent = new Intent(Intent.ACTION_SEND);
      intent.setType("image/png");

      intent.putExtra(Intent.EXTRA_STREAM, imageUri);
      startActivity(Intent.createChooser(intent , "Share"));

How to consume a webApi from asp.net Web API to store result in database?

In this tutorial is explained how to consume a web api with C#, in this example a console application is used, but you can also use another web api to consume of course.

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

You should have a look at the HttpClient

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/yourwebapi");

Make sure your requests ask for the response in JSON using the Accept header like this:

client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

Now comes the part that differs from the tutorial, make sure you have the same objects as the other WEB API, if not, then you have to map the objects to your own objects. ASP.NET will convert the JSON you receive to the object you want it to be.

HttpResponseMessage response = client.GetAsync("api/yourcustomobjects").Result;
if (response.IsSuccessStatusCode)
{
    var yourcustomobjects = response.Content.ReadAsAsync<IEnumerable<YourCustomObject>>().Result;
    foreach (var x in yourcustomobjects)
    {
        //Call your store method and pass in your own object
        SaveCustomObjectToDB(x);
    }
}
else
{
    //Something has gone wrong, handle it here
}

please note that I use .Result for the case of the example. You should consider using the async await pattern here.

Modular multiplicative inverse function in Python

You might also want to look at the gmpy module. It is an interface between Python and the GMP multiple-precision library. gmpy provides an invert function that does exactly what you need:

>>> import gmpy
>>> gmpy.invert(1234567, 1000000007)
mpz(989145189)

Updated answer

As noted by @hyh , the gmpy.invert() returns 0 if the inverse does not exist. That matches the behavior of GMP's mpz_invert() function. gmpy.divm(a, b, m) provides a general solution to a=bx (mod m).

>>> gmpy.divm(1, 1234567, 1000000007)
mpz(989145189)
>>> gmpy.divm(1, 0, 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 9)
mpz(7)

divm() will return a solution when gcd(b,m) == 1 and raises an exception when the multiplicative inverse does not exist.

Disclaimer: I'm the current maintainer of the gmpy library.

Updated answer 2

gmpy2 now properly raises an exception when the inverse does not exists:

>>> import gmpy2

>>> gmpy2.invert(0,5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: invert() no inverse exists

What does Ruby have that Python doesn't, and vice versa?

From Ruby's website:

Similarities As with Python, in Ruby,...

  • There’s an interactive prompt (called irb).
  • You can read docs on the command line (with the ri command instead of pydoc).
  • There are no special line terminators (except the usual newline).
  • String literals can span multiple lines like Python’s triple-quoted strings.
  • Brackets are for lists, and braces are for dicts (which, in Ruby, are called “hashes”).
  • Arrays work the same (adding them makes one long array, but composing them like this a3 = [ a1, a2 ] gives you an array of arrays).
  • Objects are strongly and dynamically typed.
  • Everything is an object, and variables are just references to objects.
  • Although the keywords are a bit different, exceptions work about the same.
  • You’ve got embedded doc tools (Ruby’s is called rdoc).

Differences Unlike Python, in Ruby,...

  • Strings are mutable.
  • You can make constants (variables whose value you don’t intend to change).
  • There are some enforced case-conventions (ex. class names start with a capital letter, variables start with a lowercase letter).
  • There’s only one kind of list container (an Array), and it’s mutable.
  • Double-quoted strings allow escape sequences (like \t) and a special “expression substitution” syntax (which allows you to insert the results of Ruby expressions directly into other strings without having to "add " + "strings " + "together"). Single-quoted strings are like Python’s r"raw strings".
  • There are no “new style” and “old style” classes. Just one kind.
  • You never directly access attributes. With Ruby, it’s all method calls.
  • Parentheses for method calls are usually optional.
  • There’s public, private, and protected to enforce access, instead of Python’s _voluntary_ underscore __convention__.
  • “mixin’s” are used instead of multiple inheritance.
  • You can add or modify the methods of built-in classes. Both languages let you open up and modify classes at any point, but Python prevents modification of built-ins — Ruby does not.
  • You’ve got true and false instead of True and False (and nil instead of None).
  • When tested for truth, only false and nil evaluate to a false value. Everything else is true (including 0, 0.0, "", and []).
  • It’s elsif instead of elif.
  • It’s require instead of import. Otherwise though, usage is the same.
  • The usual-style comments on the line(s) above things (instead of docstrings below them) are used for generating docs.
  • There are a number of shortcuts that, although give you more to remember, you quickly learn. They tend to make Ruby fun and very productive.

jQuery 'input' event

jQuery has the following signature for the .on() method: .on( events [, selector ] [, data ], handler )

Events could be anyone of the ones listed on this reference:

https://developer.mozilla.org/en-US/docs/Web/Events

Though, they are not all supported by every browser.

Mozilla states the following about the input event:

The DOM input event is fired synchronously when the value of an or element is changed. Additionally, it fires on contenteditable editors when its contents are changed.

jQuery DatePicker with today as maxDate

In recent version, The following works fine:

    $('.selector').datetimepicker({
        maxDate: new Date()
    });

maxDate accepts a Date object as parameter.

The following found in documentation:

Multiple types supported:

  • Date: A date object containing the minimum date.

  • Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.

  • String: A string in the format defined by the dateFormat option, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.

I am not able launch JNLP applications using "Java Web Start"?

In my case, Netbeans automatically creates a .jnlp file that doesn't work and my problem was due to an accidental overwriting of the launch.jnlp file on the server (by the inadequate and incorrect version from Netbeans). This caused a mismatch between the local .jnlp file and the remote .jnlp file, resulting in Java Web Start just quitting after "Verifying application."

So no one else has to waste an hour finding a bug that should be communicated adequately (but isn't) by Java WS.

How do you implement a class in C?

C Interfaces and Implementations: Techniques for Creating Reusable Software, David R. Hanson

http://www.informit.com/store/product.aspx?isbn=0201498413

This book does an excellent job of covering your question. It's in the Addison Wesley Professional Computing series.

The basic paradigm is something like this:

/* for data structure foo */

FOO *myfoo;
myfoo = foo_create(...);
foo_something(myfoo, ...);
myfoo = foo_append(myfoo, ...);
foo_delete(myfoo);

git still shows files as modified after adding to .gitignore

To the people who might be searching for this issue still, are looking at this page only.

This will help you remove cached index files, and then only add the ones you need, including changes to your .gitignore file.

1. git rm -r --cached .  
2. git add .
3. git commit -m 'Removing ignored files'

Here is a little bit more info.

  1. This command will remove all cached files from index.
  2. This command will add all files except those which are mentioned in gitignore.
  3. This command will commit your files again and remove the files you want git to ignore, but keep them in your local directory.

Factorial using Recursion in Java

A recursive solution using ternary operators.

public static int fac(int n) {
    return (n < 1) ? 1 : n*fac(n-1);
}

How to check if a given directory exists in Ruby

You can also use Dir::exist? like so:

Dir.exist?('Directory Name')

Returns true if the 'Directory Name' is a directory, false otherwise.1

Joining 2 SQL SELECT result sets into one

Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a

If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.

Read environment variables in Node.js

To retrieve environment variables in Node.JS you can use process.env.VARIABLE_NAME, but don't forget that assigning a property on process.env will implicitly convert the value to a string.

Avoid Boolean Logic

Even if your .env file defines a variable like SHOULD_SEND=false or SHOULD_SEND=0, the values will be converted to strings (“false” and “0” respectively) and not interpreted as booleans.

if (process.env.SHOULD_SEND) {
 mailer.send();
} else {
  console.log("this won't be reached with values like false and 0");
}

Instead, you should make explicit checks. I’ve found depending on the environment name goes a long way.

 db.connect({
  debug: process.env.NODE_ENV === 'development'
 });

Python urllib2: Receive JSON response from url

you can also get json by using requests as below:

import requests

r = requests.get('http://yoursite.com/your-json-pfile.json')
json_response = r.json()

How to initialize an array of custom objects

Here is a concise way to initialize an array of custom objects in PowerShell.

> $body = @( @{ Prop1="1"; Prop2="2"; Prop3="3" }, @{ Prop1="1"; Prop2="2"; Prop3="3" } )
> $body

Name                           Value
----                           -----
Prop2                          2
Prop1                          1
Prop3                          3
Prop2                          2
Prop1                          1
Prop3                          3  

How do I run Visual Studio as an administrator by default?

Right click on the application, Props -> Compatibility -> Check the Run the program as administrator

Default values in a C Struct

One pattern gobject uses is a variadic function, and enumerated values for each property. The interface looks something like:

update (ID, 1,
        BACKUP_ROUTE, 4,
        -1); /* -1 terminates the parameter list */

Writing a varargs function is easy -- see http://www.eskimo.com/~scs/cclass/int/sx11b.html. Just match up key -> value pairs and set the appropriate structure attributes.

MySQL Error #1133 - Can't find any matching row in the user table

I think the answer is here now : https://bugs.mysql.com/bug.php?id=83822

So, you should write :

GRANT ALL PRIVILEGES ON mydb.* to myuser@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'mypassword';

And i think that could be work :

SET PASSWORD FOR myuser@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'old_password' = PASSWORD('new_password');

Get URL of ASP.Net Page in code-behind

If you want only the scheme and authority part of the request (protocol, host and port) use

Request.Url.GetLeftPart(UriPartial.Authority)

How to get value from form field in django framework?

Take your pick:

def my_view(request):

    if request.method == 'POST':
        print request.POST.get('my_field')

        form = MyForm(request.POST)

        print form['my_field'].value()
        print form.data['my_field']

        if form.is_valid():

            print form.cleaned_data['my_field']
            print form.instance.my_field

            form.save()
            print form.instance.id  # now this one can access id/pk

Note: the field is accessed as soon as it's available.

Max length for client ip address

There's a caveat with the general 39 character IPv6 structure. For IPv4 mapped IPv6 addresses, the string can be longer (than 39 characters). An example to show this:

IPv6 (39 characters) :

ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD

IPv4-mapped IPv6 (45 characters) :

ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:192.168.158.190

Note: the last 32-bits (that correspond to IPv4 address) can need up to 15 characters (as IPv4 uses 4 groups of 1 byte and is formatted as 4 decimal numbers in the range 0-255 separated by dots (the . character), so the maximum is DDD.DDD.DDD.DDD).

The correct maximum IPv6 string length, therefore, is 45.

This was actually a quiz question in an IPv6 training I attended. (We all answered 39!)

Excel formula to get week number in month (having Monday)

If week 1 always starts on the first Monday of the month try this formula for week number

=INT((6+DAY(A1+1-WEEKDAY(A1-1)))/7)

That gets the week number from the date in A1 with no intermediate calculations - if you want to use your "Monday's date" in B1 you can use this version

=INT((DAY(B1)+6)/7)

Number of times a particular character appears in a string

try that :

declare @t nvarchar(max)
set @t='aaaa'

select len(@t)-len(replace(@t,'a',''))

Convert String to Float in Swift

I found another way to take a input value of a UITextField and cast it to a float:

    var tempString:String?
    var myFloat:Float?

    @IBAction func ButtonWasClicked(_ sender: Any) {
       tempString = myUITextField.text
       myFloat = Float(tempString!)!
    }

How to write a full path in a batch file having a folder name with space?

CD E:\Documents and Settings\All Users\Application Data

E:\Documents and Settings\All Users\Application Data>REGSVR32 xyz.dll

How to make a HTML list appear horizontally instead of vertically using CSS only?

Using display: inline-flex

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  display: inline-flex_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using display: inline-block

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#menu li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Mongodb: failed to connect to server on first connect

I was running mongod in a PowerShell instance. I was not getting any output in the powershell console from mongod. I clicked on the PowerShell instance where mongod was running, hit enter and and execution resumed. I am not sure what caused the execution to halt, but I can connect to this instance of mongo immediately now.

Resource u'tokenizers/punkt/english.pickle' not found

After adding this line of code, the issue will be fixed:

nltk.download('punkt')

SQL Left Join first match only

After careful consideration this dillema has a few different solutions:

Aggregate Everything Use an aggregate on each column to get the biggest or smallest field value. This is what I am doing since it takes 2 partially filled out records and "merges" the data.

http://sqlfiddle.com/#!3/59cde/1

SELECT
  UPPER(IDNo) AS user_id
, MAX(FirstName) AS name_first
, MAX(LastName) AS name_last
, MAX(entry) AS row_num
FROM people P
GROUP BY 
  IDNo

Get First (or Last record)

http://sqlfiddle.com/#!3/59cde/23

-- ------------------------------------------------------
-- Notes
-- entry: Auto-Number primary key some sort of unique PK is required for this method
-- IDNo:  Should be primary key in feed, but is not, we are making an upper case version
-- This gets the first entry to get last entry, change MIN() to MAX()
-- ------------------------------------------------------

SELECT 
   PC.user_id
  ,PData.FirstName
  ,PData.LastName
  ,PData.entry
FROM (
  SELECT 
      P2.user_id
     ,MIN(P2.entry) AS rownum
  FROM (
    SELECT
        UPPER(P.IDNo) AS user_id 
      , P.entry 
    FROM people P
  ) AS P2
  GROUP BY 
    P2.user_id
) AS PC
LEFT JOIN people PData
ON PData.entry = PC.rownum
ORDER BY 
   PData.entry

Add data dynamically to an Array

just for fun...

$array_a = array('0'=>'foo', '1'=>'bar');
$array_b = array('foo'=>'0', 'bar'=>'1');

$array_c = array_merge($array_a,$array_b);

$i = 0; $j = 0;
foreach ($array_c as $key => $value) {
    if (is_numeric($key)) {$array_d[$i] = $value; $i++;}
    if (is_numeric($value)) {$array_e[$j] = $key; $j++;}
}

print_r($array_d);
print_r($array_e);

PHP add elements to multidimensional array with array_push

As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:

array_push($md_array['recipe_type'], $newdata);

Create a directory if it doesn't exist

Probably the easiest and most efficient way is to use boost and the boost::filesystem functions. This way you can build a directory simply and ensure that it is platform independent.

const char* path = _filePath.c_str();
boost::filesystem::path dir(path);
if(boost::filesystem::create_directory(dir))
{
    std::cerr<< "Directory Created: "<<_filePath<<std::endl;
}

boost::filesystem::create_directory - documentation