Q:

Is there a preprocessor macro that expands to the current selector?

Possible Duplicate:
Dynamically retrieving current method's name
Obj-C introspection: How can a method reference it's own selector?

This applies to Objective-C, is there a preprocessor macro or something to get the SEL value of the current selector? Specifically I'm looking for something like:
-(void) someSelector
{
    SEL mySelector = __CURRENT_SELECTOR__;
    NSLog(@"I'm in selector %@",NSStringFromSelector(mySelector));
}

it's kinda like the __FILE__ macro but this to obtain the current selector. Pretty useful to pass it to others while not worrying to update it if the selector name is changed.

A:

Every method has two implicit parameters, self which is an id (the receiver) and a SEL called _cmd, which is probably what you want.
Note that this has nothing to do with preprocessor or anything before compile-time, _cmd is not a macro, it's an argument.
-(void) someSelector
{
    NSLog(@"I'm in selector %@",NSStringFromSelector(_cmd));
}

A:

What sidyll said should answer your question. Just wanted to add if you just need it for logging you can also use the usual C keywords, e.g.
NSLog( @"%s" , __PRETTY_FUNCTION__ );


Q:

React Native navigator.geolocation is undefined

I am trying to use:
navigator.geolocation.getCurrentPosition

but when I evaluate navigator.geolocation, I get:
navigator.geolocation is undefined

A:

In your scenario since React Native version 0.60 the Geolocation module was migrated out of React Native Core. For more information follow docs
Migrating from the core react-native module
OLD :
navigator.geolocation.setRNConfiguration(config);

UPDATED :
import Geolocation from '@react-native-community/geolocation';

Geolocation.setRNConfiguration(config);

For your problem use like this:
import Geolocation from '@react-native-community/geolocation';
Geolocation.getCurrentPosition(info => console.log(info));


Q:

Why do I have to reconnect to localhost:3000 in a new window?

I have written a program that when running, I can connect to using localhost:3000 in browser (chrome). Periodically when debugging the WebSocket Connection fails:

WebSocket connection to 'ws://localhost:3000/serv/socketio/?EIO=3&transport=websocket' failed: WebSocket is closed before the connection is established.

My issue is that when I restart the program and try to reconnect I cannot simply refresh the page. If I just try to refresh the page it will continue to print out the WebSocket connection failed message. I have to open a new window. Why is this and is there a fix?
Edit: I have tested in IE and I can refresh the page with no issues. IE will connect back up to localhost:3000 with no WebSocket Disconnect Failure

A:

Ive ran into funny issues like this when debugging sockets with specifically web browsers. I'm sure there is a magic answer for this, but my hand wavy answer is that in my experience the browsers try to be smart and remember the fact that a socket doesn't work, as well as many other things about the information they expect to receive, etc. They're not very responsive to changes in state. This applies to many things, much less whether or not they can establish a TCP connection. For example, CSS caching and the like...
All of this is done to try to save some internet bandwidth. i.e. make 'reasonable assumptions' and download less things per page load. Of course, those assumptions are built on the premise that you are doing regular web browsing.
So just open a new window long story short.
Using a private browsing window may also help.


Q:

Tab cursor when character inserted into input textbox

Here is a js fiddle example:
http://jsfiddle.net/4m5fg/158/
HTML:
<input type="text" maxlength="1" size="1" />
<input type="text" maxlength="1" size="1" />
<input type="text" maxlength="1" value="e" tabindex="-1" size="1" readonly />
<input type="text" maxlength="1" size="1" />
<input type="text" maxlength="1" value="r" tabindex="-1" size="1" readonly />
<input type="text" maxlength="1" size="1" />

<div>
<button class="buttons">á</button>
<button class="buttons">é</button>
<button class="buttons">í</button>
<button class="buttons">ó</button>
<button class="buttons">ú</button>
<button class="buttons">ñ</button>
<button class="buttons">ü</button>
</div>

JS:
$("input").bind("input", function () {
    var $this = $(this);
    if ($this.val().length >= parseInt($this.attr("maxlength"), 10)) {
        var nextEmpty = $this.nextAll("input[value=''], input:not([value])")[0];
        if (nextEmpty) {
            nextEmpty.focus();
        }
    }
});

$('input').focus(function(){
        $(this).addClass('active').siblings('.active').removeClass('active')
});

    $(".buttons").click(function () {
        var cntrl = $(this).html();
        $('input.active').val(cntrl);
    });

As can be seen from the js fiddle when the user enters a letter from the keyboard the cursor tabs to the next blank input textbox. How can I replicate this same behavior (tabbing to next blank) when the user clicks a character button and inserts it into the textbox.

A:

$('input.active').next().focus();

fiddle


Q:

ejabberd gen_mod development issue

Following this stackoverflow question, and this tutorial series, I implemented mod_test module, which implements both gen_mod and gen_server behaviours. It is very stupid for now, since it does nothing more that adding itself to ejabber_sup.
My problem is that I am not sure whether the module is started by ejabberd_sup or not since I can't find it in the list provided by:
supervisor:which_children(ejabberd_sup).

Given that I have gen_mod.beam and mod_test.erl in the same directory, I compiled my code using:
erlc -pa ./ mod_test.erl

and this gives no errors. After compilation, I copied the file into ebin folder of ejabberd installation and changed ejabberd.cfg adding:
....
{mod_test, []},
....

My code is  the following:
-module(mod_test).

-behaviour(gen_server).
-behaviour(gen_mod).

-export([start/2, stop/1]).

-export([start_link/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
         terminate/2, code_change/3]).

-record(state, {}).

start(Host, Opts) ->
    Proc = gen_mod:get_module_proc(Host, ?MODULE),
    ChildSpec = {Proc,
                 {?MODULE, start_link, [Host, Opts]},
                 permanent,
                 1000,
                 worker,
                 [?MODULE]},
    supervisor:start_child(ejabberd_sup, ChildSpec).

stop(Host) ->
    Proc = gen_mod:get_module_proc(Host, ?MODULE),
    supervisor:terminate_child(ejabberd_sup, Proc),
    supervisor:delete_child(ejabberd_sup, Proc).

start_link(_Host, _Opts) ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

init([]) ->
    {ok, #state{}}.

handle_call(_Request, _From, State) ->
    Reply = ok,
    {reply, Reply, State}.

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

Is something wrong in my approach? How can I be sure that the module is correctly started?

A:

I reinstalled ejabberd (vsn 2.1.11) and now it is working.
I add in this answer the parts of the code which are different from the code in the questoin. Changes were done following mod_echo.erl
-define(PROCNAME, ejabberd_mod_test).

start_link(Host, Opts) ->
    Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
    gen_server:start_link({local, Proc}, ?MODULE, [Host, Opts], []).

start(Host, Opts) ->
    Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
    ChildSpec =
    {Proc,
     {?MODULE, start_link, [Host, Opts]},
     temporary,
     1000,
     worker,
     [?MODULE]},
    supervisor:start_child(ejabberd_sup, ChildSpec).

stop(Host) ->
    Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
    gen_server:call(Proc, stop),
    supervisor:terminate_child(ejabberd_sup, Proc),
    supervisor:delete_child(ejabberd_sup, Proc).

Hope this will help somebody else as well.


Q:

Can the serial number printed on the COA sticker of a Sony laptop be used with other Windows 7 install disks?

I want to reinstall Windows 7 on my Sony Vaio laptop using a generic OEM Windows 7 disk to avoid Sony's crapware because they're a pain to remove.
However, I've heard mixed results regarding the use of COA product keys on Windows 7 disks not bundled with the computer.
Thanks in advance

A:

You can use the COA to install using an OEM disc, yes.
Bear in mind that for VAIO notebooks, you'll need to follow the Install Order on Sony's support site if you want basically anything on the notebook to work properly (wireless and webcam are the major problems).


Q:

onLongItemClick affects recycled views

I have a list view which loads items from an arrayList, the problem comes in when using the onLongClickItemListener
Whenever an item is long clicked I show a hidden layout in that item itself. So whenever the list is recycling items, the hidden layout would be visible for items that are recycled (which are supposed to not show the layout).
Any ideas? I've tried to add a flag to the object itself of each item in the list with no luck, the most I could get is to make the layout gone for every item that is shown when scrolling, but I want to keep the opened ones by the user stay visible.
Here's my current code:
 messageListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                LinearLayout ll = (LinearLayout) view.findViewById(R.id.hiddenLayout);
                if (ll.getVisibility() == View.VISIBLE) {
                    ll.setVisibility(View.GONE);
                    msgs.get(position).setViewFlag(false);
                    msgAdapter.setMessages(msgs);
                } else {
                    ll.setVisibility(View.VISIBLE);
                    msgs.get(position).setViewFlag(true);
                    msgAdapter.setMessages(msgs);
                }
                return true;
            }
        });

And here's the code for the adapter:
 public class MessagesAdapter extends BaseAdapter {

        private static int lastPos = -1;
        private ArrayList<Message> messages;
        private Context context;

    public MessagesAdapter(ArrayList<Message> messages, Context context) {
        this.messages = messages;
        this.context = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            convertView = inflater.inflate(R.layout.message_list_row, null);

            ViewHolder viewHolder = new ViewHolder();

            viewHolder.title = (TextView) convertView.findViewById(R.id.msgTitle);
            viewHolder.body = (TextView) convertView.findViewById(R.id.msgBody);
            viewHolder.monthDate = (TextView) convertView.findViewById(R.id.monthDate);
            viewHolder.dayDate = (TextView) convertView.findViewById(R.id.dayDate);
            viewHolder.status = (ImageView) convertView.findViewById(R.id.statusIcon);
            viewHolder.linearLayout = (LinearLayout) convertView.findViewById(R.id.hiddenLayout);
            viewHolder.linearLayout.setVisibility(View.GONE);

            convertView.setTag(viewHolder);
        }

        ViewHolder holder = (ViewHolder) convertView.getTag();

        if (!(messages.get(position).isViewFlag()))
            holder.linearLayout.setVisibility(View.GONE);

        holder.title.setText(messages.get(position).getTitle());
        holder.body.setText(messages.get(position).getBody());
        switch (messages.get(position).getMessageType()) {
            case READ:
                holder.status.setBackgroundResource(R.drawable.yellowcircle);
                break;
            case UNREAD:
                holder.status.setBackgroundResource(R.drawable.redcircle);
                break;
        }
        lastPos = position;
        return convertView;
    }

    @Override
    public int getCount() {
        return messages.size();
    }

    @Override
    public Object getItem(int position) {
        return messages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    static class ViewHolder {
        public TextView title;
        public TextView body;
        public TextView dayDate;
        public TextView monthDate;
        public ImageView status;
        public TextView read;
        public TextView unread;
        public TextView remove;
        public TextView reply;
        public LinearLayout linearLayout;

    }

    public void setMessages(ArrayList<Message> msgs) {
        this.messages = msgs;
    }

}

A:

It is not a good idea to modify the visibility of the views inside the ListView directly. As a general pattern, you need to update the data that is backing up the ListView - the messages array in your case. You would need to set the isViewFlag property in your Message rather than trying to change the visibility on a view that you don't control on which item is being used.
Your click handler would just do (and follow the changes in the adapter as well):
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    msgAdapter.setExpandedPosition(msgAdapter.getExpandedPosition() == position ? -1 : position);
    return true;
}

However, since this is a UI state that doesn't really depend on the properties on your item, but rather based on the user interaction with the UI, one might argue (me included) that this information does not belong in there. I would set a property in the adapter (if only one item can be in the expended state at a particular time) or a list of properties like a sparse array (if multiple items can be in the expended state at the same moment in time).
Your adapter would be something like (also please not the changes to your original getItemId() and setMessages() which don't have anything to do with the problem in hand, but are just good practice):
public class MessagesAdapter extends BaseAdapter {
    // for Option1 - only one item expanded at a time
    int expandedPos = -1;
    ....

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ....
        //Option 1 - only one item expanded at a time
        holder.linearLayout.setVisibility(position == expandedPos ? View.GONE : View.VISIBLE);
        //Option 2 - multiple items can be expanded at the same time, following your current implementation
        holder.linearLayout.setVisibility(messages.get(position).isViewFlag() ? View.VISIBLE : View.GONE);
        ....
    }

    public void setExpandedPosition(int position) {
        //Option 1 - only one item expanded at a time
        expandedPos = position;

        //Option 2 - multiple items can be expanded at the same time, following your current implementation
        messages.get(position).setIsViewFlag(position != -1);

        // In both cases:
        notifyDataSetChanged();
    }

    // only for Option 1 - only one item expanded at a time
    public int getExpandedPosition() {
        return expandedPos;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void setMessages(ArrayList<Message> msgs) {
        this.messages = msgs;
        notifyDataSetChanged();
    }

}


Q:

Connection refused implementing a tcp server

I'm trying to make a server and client. But when I try to connect the client to the server, I get connection refused. The other answers on stack overflow said to make sure you have listen() and accept(), which I do, and to check the firewalls. So I turned off all the firewalls just to make sure.
I still get connection refused, so I tried ./telnet 10.1.10.13 9696, and got:
Trying 10.1.10.13...
telnet: connect to address 10.1.10.13: Connection refused
telnet: Unable to connect to remote host
Here's the code for the server
int setUpServer(struct fuzzerObj *ptr)
{
    /* Declarations */
    int hostSocket, yes = 1, rtrn;

    union
    {
        struct sockaddr_in in;

    }address;

   /* Create Socket */
   hostSocket = socket(AF_INET, SOCK_STREAM, 0);
   if(hostSocket < 0)
   {
       errorHandler("Could not create socket\n", FUNCTION_ID_SET_UP_SERVER);
       return -1;
   }

   /* Reuse Address */
   rtrn = setsockopt(hostSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
   if(rtrn < 0)
   {
        errorHandler("Couldn't Reuse Address\n", FUNCTION_ID_SET_UP_SERVER);
        return -1;
   }

   errno = 0;

   /* Set Up Struct */
   address.in.sin_len = sizeof(address.in);
   address.in.sin_family = AF_INET;
   address.in.sin_port = BBPORT_NUMBER;
   address.in.sin_addr.s_addr = htonl(INADDR_ANY);
   memset(address.in.sin_zero, 0, sizeof(address.in.sin_zero));

   /* Bind Address to Socket */
   rtrn = bind(hostSocket, (struct sockaddr*) &address, address.in.sin_len);
   if(rtrn < 0)
   {
       errorHandler("Can't Bind Address to Socket\n", FUNCTION_ID_SET_UP_SERVER);
       perror("");
       return -1;
   }

   /* listen */
   rtrn = listen(hostSocket, ptr->numberOfClients);
   if(rtrn < 0)
    {
        errorHandler("Can't Listen\n", FUNCTION_ID_SET_UP_SERVER);
        return -1;
    }

   while(1) acceptClient(hostSocket);

   return 0;
}

int acceptClient(int fd)
{
    struct sockaddr_storage addr;
    socklen_t addr_len = sizeof(addr);

    int clientFd = accept(fd, (struct sockaddr *) &addr, &addr_len);
    if(clientFd < 0)
    {
        printf("Can't Accept Client\n");
        return -1;
    }

    return clientFd;
}

and the code for the client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>

#define BLACKBOX_PORT 9696

int main(int argc, char *argv[])
{
    /* Check To See If an argument was passed */
    if(argc < 2)
    {
         printf("No enough Arguments\n");
         return -1;
    }

     /* Declaration's */
     const char *ip = argv[1];
     int sockfd, fd, rtrn;
     char *inBuf;
     struct sockaddr_in servaddr,cliaddr;
     socklen_t len = sizeof(cliaddr);

     /* Get Socket to Connect to Fuzz Server */
     sockfd = socket(PF_INET, SOCK_STREAM, 0);
     if(sockfd < 0)
     {
         perror("Can't Create Socket");
         return -1;
     }

     /* Fill Out Struct */
     servaddr.sin_family = AF_INET;
     servaddr.sin_port = htons(BLACKBOX_PORT);
     inet_pton(AF_INET, ip, &servaddr.sin_addr);

     /* Attempt Connection */
     fd = connect(sockfd,(struct sockaddr *)&servaddr, sizeof(servaddr));
     if(fd < 0)
     {
        perror("Can not connect to BlackBox Fuzz server");
        return -1;
     }

    /* Allocate Space in Memory for Incoming Connection */
    inBuf = (char *) malloc(1025);
    if(inBuf == NULL)
    {
        perror("Mem Error");
        return -1;
    }

    /* Read From Socket */
    rtrn = read(fd, inBuf, 1024);
    if(rtrn < 0)
    {
        perror("Can't Read Data From BlackBox Server");
        return -1;
    }
    printf("Received Data: %s\n", inBuf);
    free(inBuf);
    return 0;
}

Output from client:
./client 10.1.10.13
Can not connect to BlackBox Fuzz server
Connection refused
Any help would be appreciated, thanks.

A:

Assuming that you're running this code on a little-endian machine, you need to use htons() when assigning the port number on the server side too.
(On big-endian machines htons() is a "no-op", but you should always use it to ensure portability)


Q:

rails tutorial expected css title with text to return something

I am working through the RoR tutorial at ruby.railstutorial.org and am currently on chapter 4.  The tests aren't validating and I have no idea why.
Top part of my spec file looks like this.  The other methods all look identical to Help:
describe "StaticPages" do
 let(:page_title) {"Ruby on Rails Tutorial Sample App"}
 let(:h1_test) {"should have the h1"}
 let(:title_test) {"should have the title"}
 describe "Home page" do |title_test, h1_test|
  it "#{h1_test} 'Sample App'" do
   visit '/static_pages/home'
   page.should have_selector('h1',:text=>'Sample App')
  end

  it "#{title_test} 'Home'" do
   visit '/static_pages/home'
   page.should have_selector('title', :text=> '#{page_title}')
  end

  it "should not have a custom page title" do
   visit '/static_pages/home'
   page.should_not have_selector('title', :text=> '| Home')
  end
end

describe "Help page" do |title_test, h1_test|
 it "#{h1_test} 'Help'" do
  visit '/static_pages/help'
  page.should have_selector('h1', :text =>'Help')
 end

 it "#{title_test} 'Help'" do
  visit '/static_pages/help'
  page.should have_selector('title',
    :text=>'#{page_title} | Help')
 end
end

My application_helper.rb:
module ApplicationHelper
  def full_title(page_title)
    base_title = "Ruby on Rails Tutorial Sample App"
  if page_title.empty?
    base_title
  else
    "#{base_title} | #{page_title}"
    end
  end
end

My application.html.haml file:
!!!
%html
  %head
    %title= full_title(yield(:title))
    = stylesheet_link_tag "application", :media => "all"
    = javascript_include_tag "application"
    = csrf_meta_tags
  %body= yield

Now the 4 errors are identical minus one word change, so I'll just post one:
  1) StaticPages Contact#<Class:0x0000000446e818> 'Contact'
     Failure/Error: page.should have_selector('title', :text=>'#{page_title} | Contact')
       expected css "title" with text "\#{page_title} | Contact" to return something
     # ./spec/requests/static_pages_spec.rb:65:in `block (3 levels) in <top (required)>'

I am mystified because I am just copying it straight from the guide other than using haml and adding in those top few lines in my spec file to minimize repeat text. I didn't include the page html files because I can't see how they could be the problem.  Especially since the home.html.haml doesn't have a - provide(:title, 'Home') like the others but is still throwing the same error as above.
Any help would be greatly appreciated!
Edit: Here is my Gemfile:
  gem 'rails',       '3.2.12'
  gem 'haml',        '4.0.0'
group :development, :test do
  gem 'sqlite3',     '1.3.5'
  gem 'rspec-rails', '2.11.0'
  gem 'haml-rails',  '0.4'
  gem 'guard-rspec', '1.2.1'
  gem 'guard-spork', '1.4.2'
  gem 'spork',       '0.9.2'
end
group :assets do
  gem 'sass-rails',  '3.2.5'
  gem 'coffee-rails','3.2.2'
  gem 'uglifier',    '1.2.3'
end

gem 'jquery-rails',  '2.0.2'

group :test do
  gem 'capybara',    '1.1.2'
  gem 'rb-inotify',  '0.8.8'
  gem 'libnotify',   '0.5.9'
end

group :production do
  gem 'pg',          '0.12.2'
end

A:

Make sure you are using Capybara version 1.* (as used in the tutorial). New versions of Capybara, starting from 2.0, change the way it checks page content. Now construction
page.should have_selector(selector, :text=> text)

works only for visible DOM elements (h1, p, span, etc.), but does not work for non-visible elements like title or script.
You can set previous Capybara version in the Gemfile
group :test do
  gem 'capybara', '1.1.2'
end

Or modify your tests:
page.source.should have_selector(selector, :text=> text)

A:

I figured out the problem.  Where I say '#{page_title}' it should be "#{page_title}".  Double quotes instead of single quotes -_-.   Can someone tell me why that works?  Especially because I have stuff like 'Sample App' in the same have_selector checks and that doesn't throw any kind of error.  Hope this helps someone in the future at least.


Q:

Elegant way to convert list to hex string

I have a long list that looks like this:
[True, True, True, False, ... ]

Representing walls in a tile map. It isn't guaranteed to be a multiple of 4 long, but it doesn't matter if it gets padded at the end.
I'd like to convert this into a hex string, so for the above example it would start with E ...
I was hoping there was a nice elegant way to do this (using Python 2.7.3)!
Thanks.
EDITED
This is an example of a 9x9 map:
map = [True, True, True, True,
       True, True, True, True,
       True, True, True, True,
       True, False, False, True,
       True, True, True, True,
       True, False, False, False,
       False, True, True, True,
       True, True, False, False,
       False, False, True, True,
       True, True, True, True,
       False, False, True, True,
       True, True, True, True,
       True, True, True, True,
       True, True, True, True,
       True, True, True, True,
       True, True, True, True,
       True, True, True, True,
       True, True, True, True,
       True, True, True, True,
       True, True, True, True,
       True]# False, False, False padded

what I would like is to be able to
str = heximify(map)
print str
> FFF9F87C3F3FFFFFFFFF8

A:

Joining the one-liners club, by way of bit manipulation which seems more appropriate.
val = hex(reduce(lambda total, wall: total << 1 | wall, walls, 0))

This does the same as:
val = 0
for wall in walls:
    val <<= 1 # add one 0 bit at the "end"
    val |= wall # set this bit to 1 if wall is True, otherwise leave it at 0

val = hex(val) # get a hex string in the end
val = format(val, 'x') # or without the leading 0x if it's undesired

A:

>>> walls = [True, True, True, False]
>>> hex(int(''.join([str(int(b)) for b in walls]), 2))
'0xe'

or (inspired by @millimoose's answer),
>>> hex(sum(b<<i for i,b in enumerate(reversed(walls))))
'0xe'


Q:

sorting alphabetically after stripping "the, a, an" only working partially

Trying to hack apart an annoying bug here.
We have a regex which correctly strips off leading articles like "a", "the", etc.   It also sorts alphabetically fine for some of the entries, but not for the rest.   What happens is we get a list where some of the listings with these articles are embedded properly within the output, and then it gets to the end and starts over, with those entries correctly sorted among themselves.
Here's an example of how it's appearing

Apple
Banana
The Carrot
The Grapefruit
Kiwi
The aardvark
The emu
A zebra

As you can see, it does fine at first, but then gets to the end and starts over with only those items with articles.  I've looked at the data, and can't find any consistencies that would explain the variation.
Here's the regex comparison (in an entity called Bibliography)
    public static function compareTitles(Bibliography $a, Bibliography $b)
{
    $ignored_word_regex = '/^(the|a|an)\s/i';
    $tag_quote_regex = '/"?(\<\/?[a-zA-Z]+\>)?/';
    $a_test = preg_replace($ignored_word_regex ,'', $a->getTitle());
    $a_test = preg_replace($tag_quote_regex, '', $a_test);
    $b_test = preg_replace($ignored_word_regex ,'', $b->getTitle());
    $b_test = preg_replace($tag_quote_regex, '', $b_test);
    return strcmp( $a_test,
                   $b_test);
}

This is being pulled in from an entity called Review
    /**
 * @param Review $a
 * @param Review $b
 *
 * @return boolean
 */
public static function compareTitles($a, $b)
{
    return \Entity\Bibliographies\Bibliography::compareTitles($a->getBiblio(), $b->getBiblio());
}

This is then sorted in the controller using these two methods:
    public function exportIndexTitleAction( Request $request ){
    $response = $this->renderExportXMLSorted(
        'Review:Export/index_title.xml.twig',
        $request,
        array('Entity\Reviews\Review', 'compareTitles'));
    return $this->setExportHeaders($response, date("o-m-d-")."index_title.txt");
}

and using a uasort:
    protected function renderExportXMLSorted($template, Request $request, $sort_method, $filter_method = null){
    $reviews = $this->getReviewsFromRequest($request);
    if ($filter_method != null)
        $reviews = array_filter($reviews, $filter_method);
    uasort($reviews, $sort_method);

    return $this->renderExportXML($template, $reviews);
}

I've been digging through this and cannot figure what causes it to stop and start over again. I can get it to sort fine if it treats "the" and "a" as they are, but they really need to be stripped, but also be displayed.  (yes, it would be easier to simply remove them, but they need to remain).
I'm thinking there's something in the regex that I'm missing...

A:

Obviously the problem is case.  You need to use strcasecmp to treat both cases the same.  You could also strtolower or strtoupper both before the compare.
 Also, that is a lot of code that can be boiled down to something simpler:
uasort($array, function($a, $b) {
                     $p = '/^(the|a|an)\s/i';
                     $a = preg_replace($p, '', $a);
                     $b = preg_replace($p, '', $b);
                     return strcasecmp($a, $b);
               });


Q:

Creating split panel in react js

I need to create split div functionality in reactjs. As shown in this fiddle. this one is implemented in extjs. I want similar implementation is reactjs. We need to add grids on either side of split panel. I am short of ideas on how to implement it. Not looking for code, but need ideas.

A:

Hi you can check this package called react-split-pane. Also there you can find example for you case. Also there others examples.


Q:

input type in android such keypad first line of keyboard show numeric and then qwety keyboard

In android i want a keyboard which has first row with all the numeric and then QWERTY Keyboard show with in same keypad so is it possible in android
                    samsung phone show keyboard like this
                         How Write in XML as well as programmatically

A:

use code editText.setRawInputType(Configuration.KEYBOARD_QWERTY);


Q:

How can I set a conditional function argument value here?

I want to automatically set the value of an argument in a function based on another argument's value.
More specifically, I want to set a timezone value (offset) to automatically adjust time values given the region.
However, my implementation doesn't seem to work (as in the offset is never applied unless I specifically pass it as an argument to the function).
Part of the function (is supposed to) set the offset value based on region's value, and also connect to the corresponding Elasticsearch server.
This is what I have:
if (region == "EU") {
    offset = "+00:00:00"
    # Code to connect to EU ElasticSearch server
  } else if (region == "US") {
    offset = "-06:00:00"
    # Code to connect to US ElasticSearch server
  } else {
  paste0(stop("Incorrect region supplied: ", region))
}

The function:
time_function <- function(region, retailer, start_date, end_date, offset = "+00:00:00"){
    # Function body
}

(Note that I have set the default value of offset to "+00", otherwise it will throw an error that the argument is missing.)
Clearly I have gone wrong somewhere because the offset is never applied unless I explicitly specify in the argument list.
This is what I want to do:
If region == "US", then set offset to "-06:00:00",
Else if region == "EU", then set offset to "+00:00:00"
Else Error message: "supply valid region"
In short, I am looking to set a conditional argument value.
How can I achieve this?

A:

It turns out I made an oversight in the order of assignment implementations and have just now spotted it.
For those who might be experiencing similar problems, it might be worth highlighting where I went wrong: I set the offset value after it was used, meaning that it was used/processed (using the previous iteration's value) and then it was assigned the new value.
In short, my implementation was completely correct but the order of events was incorrect.
Therefore, make sure that you set the required values before they are processed.


Q:

Java Best way to parse quarterly dates

I have a date as APR-JUN10 or APR-JUN 2010 and i need output as 2010-06-30 I need the best way to parse above date in java and should be flexible in adding more such format of dates. note: APR-JUN10 will not parse by any java api, we have to break down APR & JUN 10 and get date as 2010-06-30.

A:

You need to firm up your requirements.
Currently all you have told us is that APR-JUN 2010 should translate to the last day of June.
But what about FEB-JUN 2010? Should that also translate to the last day of June? Or should it throw a parse exception due to not being a full quarter? What about JUL-JUN 2010, where the second month is before the first? What about MAY-JUL 2010 -- three months but perhaps your definition of "quarter" requires starts of January, April, July, October.
Once you have your own requirements down, you can get to work on the conversion.
It's unlikely that an existing DateFormat implementation will do this exact task for you. You're likely to need to parse the string in your own code.
If the only legal options are JAN-MAR, APR-JUN, JUL-SEP, OCT-DEC, then you just have a five-way switch statement to set the month and day on a Calendar object (the fifth way being a default: case that throws an exception.
If your requirement is more complex, then your code will need to be more complex. Breaking the string into parts using a regex would be a good first step.
Pattern patt = Pattern.compile("(.{3})-(.{3}) (\d+)");
Matcher matcher = patt.matcher(qaurterString);
if(! matcher.find() || m.groupCount() != 3) {
    throw new ParseException(...)
}
String fromMonth = matcher.group(1);
String toMonth = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));

I think you'll have to write parsing code from scratch, whatever you do. The neatest end result would for you to create a class that implements DateFormat.


Q:

Stopping animate, increasing circle radius with KineticJS on mousedown

this is my first question here so if there is any additional information you require please let me know.
So my goal is to be able to click on the moving circle and have its movement stopped and while the mouse button is down have its radius increased steadily (like an expanding balloon). Currently I have it so the radius expands by 1 when the mouse is down and then it goes bonkers once I mouse up (I would like it to keep moving with its new radius on mouse up).
Here is my code:
HTML

    <meta>
    <link rel="stylesheet" type="text/css" href="styles/main.css" />

CSS
#wrapper{
    margin: 10% auto;
    width: 900px;
    text-align: center;
}
#stage{
    border: 1px solid black;
    display: block;
}

Javascript
var circlevx = 5;
var circlevy = 5;
var runAnimation = true;
/*******************************
setting up the stage/layers
********************************/
window.onload = function(){
    var stage = new Kinetic.Stage({
        container : 'stage',
        width : 900,
        height : 600
    });
    var shapesLayer = new Kinetic.Layer();

    /**********************************
        creating the circle object
    *************************************/
    var circle = new Kinetic.Circle({
        x : stage.getWidth() / 2,
        y : stage.getHeight() / 2,
        radius : 50,
        fill : 'grey',
        stroke : 'black',
        strokeWidth : 1
    });

    /*************************************
        add the circle to the stage
    **************************************/
    //bindingBox.add(circle);
    shapesLayer.add(circle);
    stage.add(shapesLayer);

    var date = new Date();
    var time = date.getTime();
    animate(time, circle, runAnimation);
}

window.requestAnimFrame = (function(callback){
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
})();

function animate(lastTime, circle, runAnimation){
    if(runAnimation) {
        var stage = circle.getStage();
        var shapesLayer = circle.getLayer();
        var date = new Date();
        var time = date.getTime();
        var timeDiff = time - lastTime;

        // update
        updateCircle(timeDiff, circle);

        // draw
        shapesLayer.draw();

        // request new frame
        requestAnimFrame(function(){
            animate(time, circle, runAnimation);
        });
    }
}

function updateCircle(timeDiff, circle){
    var stage = circle.getStage().attrs;
    var circleX = circle.attrs.x;
    var circleY = circle.attrs.y;
    var circleRadius = circle.attrs.radius;
    var newRadius = circleRadius + 2;
    circleX += circlevx;
    circleY += circlevy;
    //console.log(stage);

    //throw 'aarg';
    // ceiling condition
    if (circleY < circleRadius) {
        circleY = circleRadius;
        circlevy *= -1;
    }

    // floor condition
    if (circleY > (stage.height - circleRadius)) {
        //console.log('bottom');
        circleY = stage.height - circleRadius;
        circlevy *= -1;
    }

    // right wall condition
    if (circleX > (stage.width - circleRadius)) {
        circleX = stage.width - circleRadius;
        circlevx *= -1;
    }

    // left wall condition
    if (circleX < (circleRadius)) {
        circleX = circleRadius;
        circlevx *= -1;
    }

    circle.setPosition(circleX, circleY);
    //
    circle.on('mousedown', function(){
        runAnimation = false;
        circle.setRadius(newRadius);
    });
    circle.on('mouseup', function(){
        runAnimation = true;
        if(runAnimation) {
            var date = new Date();
            var time = date.getTime();
            animate(time, circle, runAnimation);
        }
        console.log('mouseout');

    });
}

A:

You can use a Kinetic Tween to control the expansion of you "balloon"
First, declare these useful additional properties on the Kinetic balloon object:
    balloon.X=150;
    balloon.Y=150;
    balloon.VX=0.50;
    balloon.VY=0.50;
    balloon.RAF;
    balloon.tw;

On balloon mousedown cancel the movement animation and start the tween to expand the balloon:
You can continue expanding the balloon if you again press the mouse down.
    balloon.on("mousedown",function(){
        cancelAnimationFrame(this.RAF);
        this.tw=new Kinetic.Tween({
            node:this,
            duration:3,
            radius:100
        });
        this.tw.play();
    });

Then on mouseup, pause the inflation tween and restart the move animation:
The balloon will retain its expanded size.
Note: if you have the mouse down and move off the balloon to release the mouse,  this mouseup will not be called and the balloon will continue to expand, even though the mouse is up.
    balloon.on("mouseup",function(){
        this.tw.pause();
        this.move();
    });

Here is the RAF animation function added to the balloon object to do balloon movement:
    balloon.move=function(){

        // calc new balloon position
        this.X+=this.VX;
        this.Y+=this.VY;

        // reverse if colliding
        var r=this.getRadius();
        if(this.X<r){ this.VX*=-1; this.X=r; }
        if(this.X>stageWidth-r){ this.VX*=-1; this.X=stageWidth-r; }
        if(this.Y<r){ this.VY*=-1; this.Y=r; }
        if(this.Y>stageHeight-r){ this.VY*=-1; this.Y=stageHeight-r; }

        // set the new balloon position
        this.setPosition(this.X,this.Y);
        layer.draw();

        // request a new animation loop
        var b=this;
        this.RAF=requestAnimationFrame(function(){ b.move();});
    }

Here is code and a Fiddle:  http://jsfiddle.net/m1erickson/D7Ndc/
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Prototype</title>


Q:

Join table complicate

i have these table
Person
ID_PRS   Name
------   -----
1        John
2        Brian
3        Mike

Con_PRS_Fonc
    ID_PRS  ID_FONCT
    -----   -------
     1       17
     1       18
     3       17

   Fonction
       ID_FONCT   LABEL  ID_CATEG  ID_MET ID_ANA
       -------    -----  --------  ------ ------
         17       Boss      1        56     78
         18       Junior    1        45     56

Category
 ID_CATEG  LABEL
 --------  -----
    1      Cleaning
    2      Wahsing

MEtir
 ID_MET   LABEL
 ------   -----
  56       Go
  45       Come

Analys
 ID_ANA  LABEL
 ------  -----
  78     Think
  56     Drink

how can i get:
ID_PRS  NOM  ID_FONCT   LABEL_FONCT  ID_CATEG  LAB_CAT   ID_MET   LAB_MET   ID_AN   LAB_ANA
------  ---- --------   -----------  --------  -------    ------   -------   -----   -------
   1    John  17         Boss           1      Cleaning   56        GO        56     Think

i know only i can join the table Person with table Con_PRS_Fonc, but how can i join with other ?
SELECT * FROM PERSON
LEFT JOIN Con_PRS_Fonc ON PERSON.ID_PRS = Con_PRS_Fonc .ID_PRS

Thanks you in advance,
Stev

A:

This should get you exactly what you want:
    SELECT
Person.ID_PRS,
Person.Name,
Fonction.ID_FONCT,
Fonction.LABEL AS LABEL_FONCT,
Fonction.ID_CATEG,
Category.LABEL AS LAB_CAT,
MEtir.ID_MET,
MEtirLABEL AS LAB_MET,
Analys.ID_ANA,
Analys.LABEL AS LAB_ANS
FROM PERSON
INNER JOIN Con_Prs_Fonc ON Person.ID_PRS = Con_Prs_Fonc.ID_PRS
INNER JOIN Fonction ON Fonction.ID_FONCT = Con_Prs_Fonc.ID_FONCT
INNER JOIN Category ON Category.ID_CATEG = Fonction.ID_CATEG
INNER JOIN MEtir ON MEtir.ID_MET = Fonction.ID_MET
INNER JOIN Analys ON Analys.ID_ANA = Fonction.ID_ANA


Q:

How to apply 2 filters drawtext and drawbox using FFMPEG

I'm having problems combining filters.  I'm trying to take video from the camera, apply a timer on it and also overlay a box in the center.  I can put a time code (local time and pts) using the -vf drawtext command no problems:
ffmpeg -f video4linux2 -input_format mjpeg -s 1280x720 -i /dev/video0 \
-vf "drawtext=fontfile=/usr/share/fonts/truetype/freefont/FreeSerif.ttf: \
text='%{localtime} %{pts\:hms}':  fontcolor=white: fontsize=24: box=1: \
boxcolor=black@0.8: boxborderw=5: x=0: y=0" -vcodec libx264 \
-preset ultrafast -f mp4 -pix_fmt yuv420p -y output.mp4

Then I have one that draws a small box using drawbox:
ffmpeg -f video4linux2 -input_format mjpeg -s 1280x720 -i /dev/video0 \
-filter_complex " drawbox=x=iw/2:y=0:w=10:h=ih:color=red@0.1": \
-vcodec libx264 -preset ultrafast -f mp4 -pix_fmt yuv420p -y output.mp4

I assumed I could combine these with the filter_complex switch and separate them using the semicolon like this
ffmpeg -f video4linux2 -input_format mjpeg -s 1280x720 -i /dev/video0 -filter_complex "drawtext=fontfile=/usr/share/fonts/truetype/freefont/FreeSerif.ttf: text='%{localtime} %{pts\:hms}':  fontcolor=white: fontsize=24: box=1: boxcolor=black@0.8;drawbox=x=iw/2:y=0:w=10:h=ih:color=red@0.1": -vcodec libx264 -preset ultrafast -f mp4 -pix_fmt yuv420p -y output.mp4

But it fails to find the input stream on the second filter:

Input #0, video4linux2,v4l2, from '/dev/video0':
Duration: N/A, start: 10651.720690, bitrate: N/A
Stream #0:0: Video: mjpeg, yuvj422p(pc, bt470bg/unknown/unknown), 1280x720, -5 kb/s, 30 fps, 30 tbr, 1000k tbn, 1000k tbc
Cannot find a matching stream for unlabeled input pad 0 on filter Parsed_drawbox_1

I tried to direct it to [0] like this:
ffmpeg -f video4linux2 -input_format mjpeg -s 1280x720 -i /dev/video0 -filter_complex " \
drawtext=fontfile=/usr/share/fonts/truetype/freefont/FreeSerif.ttf: \
text='%{localtime} %{pts\:hms}':  fontcolor=white: fontsize=24: box=1: \
boxcolor=black@0.8;[0] drawbox=x=iw/2:y=0:w=10:h=ih:color=red@0.1": \
-vcodec libx264 -preset ultrafast -f mp4 -pix_fmt yuv420p -y output.mp4

But it fails to put the box on the output.
So I tried to split streams like this
ffmpeg -f video4linux2 -input_format mjpeg -s 1280x720 -i /dev/video0 -filter_complex " \
split [main][tmp];\
[main] drawtext=fontfile=/usr/share/fonts/truetype/freefont/FreeSerif.ttf: \
text='%{localtime} %{pts\:hms}':  fontcolor=white: fontsize=24: box=1: boxcolor=black@0.8 [tmp];\
[main] drawbox=x=iw/2:y=0:w=10:h=ih:color=red@0.1 [tmp2]; [tmp][tmp2] overlay": \
-vcodec libx264 -preset ultrafast -f mp4 -pix_fmt yuv420p -y output.mp4

But my build doesn't have the overlay filter complied with it.  At this point I decided to stop and ask if I'm making this harder than it should be.  The end result is I just want a timer and a box drawn on the video.  Is there a better way or a formatting trick to do this?
Thanks

A:

You can just apply them one after the another, by separating via a comma.
ffmpeg -f video4linux2 -input_format mjpeg -s 1280x720 -i /dev/video0 -filter_complex " \
drawtext=fontfile=/usr/share/fonts/truetype/freefont/FreeSerif.ttf: \
text='%{localtime} %{pts\:hms}':  fontcolor=white: fontsize=24: box=1: \
boxcolor=black@0.8, drawbox=x=iw/2:y=0:w=10:h=ih:color=red@0.1": \
-vcodec libx264 -preset ultrafast -f mp4 -pix_fmt yuv420p -y output.mp4


Q:

A question about Fraenkel's 1922 paper

In Fraenkel's 1922 paper, what does the angle bracket mean that he uses on page 254 on line 3 in the expression $\phi(x) = \{\{\langle x \rangle, \langle o \rangle \}, \mathfrak U x+ \{\langle o\rangle\}\}$?

A:

It is just a guess, but it seems to me that $\langle\,\rangle$ is just the third level of nested set building braces $\{\,\}$, after the outmost "big" $\bigl\{\bigr\}$ and the second $\{\}$.


Q:

How to take input of a directory

What I'm trying to do is troll through a directory of log files which begin like this "filename001.log" there can be 100s of files in a directory
The code I want to run against each files is to check to make sure that the 8th position of the log always contains a number. I have a suspicion that a non-digit is throwing off our parser. Here's some simple code I'm trying to check this:
# import re
from urlparse import urlparse

a = '/folderA/filename*.log' #<< currently this only does 1 file
b = '/folderB/' #<< I'd like it to write the same file name as it read
with open(b, 'w') as newfile, open(a, 'r') as oldfile:
    data = oldfile.readlines()
    for line in data:
        parts = line.split()
        status = parts[8]  # value of 8th position in the log file
        isDigit = status.isdigit()

        if isDigit = False:
                print " Not A Number :",status
                newfile.write(status)

My problem is:

How do I tell it to read all the files in a directory? (The above really only works for 1 file at a time)
If I find something is not a number I would like to write that character into a file in a different folder but of the same name as the log file. For example I find filename002.log has a "*" in one of the log lines. I would like folderB/filename002.log to made and the non-digit character to the written.

Sounds sounds simple enough I'm just a not very good at coding.

A:

To read files in one directory matching a given pattern and write to another, use the glob module and the os.path functions to construct the output files:
srcpat = '/folderA/filename*.log'
dstdir = '/folderB'
for srcfile in glob.iglob(srcpat):
   if not os.path.isfile(srcfile): continue

   dstfile = os.path.join(dstdir, os.path.basename(srcfile))
   with open(srcfile) as src, open(dstfile, 'w') as dst:
       for line in src:
           parts = line.split()
           status = parts[8]  # value of 8th position in the log file
           if not status.isdigit():
               print " Not A Number :", status
               dst.write(status)  # Or print >>dst, status if you want newline

This will create empty files even if no bad entries are found. You can either wait until you're finished processing the files (and the with block is closed) and just check the file size for the output and delete it if empty then, or you can move to a lazy approach where you delete the output file before beginning iteration unconditionally, but don't open it; only if you get a bad value do you open the file (for append instead of write to keep earlier loops' output from being discarded), write to it, allow it to close.


Q:

Excel INDIRECT returns with REF error

I don't understand why my INDIRECT function does not work. I'm dynamically changing D2 value from a list.
=INDIRECT("'G:\Production\OPH 2015\"&D2&"'!"&"G4")

where
D2 = [Spreadsheet.xslx]Sheet1
G4 would be the value I want the formula to return with.
The same formula on its own returns the value 72.2% and looks like this:
='G:\Production\OPH 2015\[Spreadsheet.xlsx]Sheet1'!G4

A:

It isn't your formula that is incorrect, the INDIRECT formula will return #REF! if the workbook is closed.
I haven't tried this, but I believe this add-in will solve your problem: http://www.ashishmathur.com/tag/indirect-ext/


Q:

Alignment left on top and bottom in same div with bootstrap?

I'm trying to align a row of buttons on the bottom but also have two rows of text at the top both justified left using twitter bootstrap.  Here is what I'm trying to achieve:

Here is a jsfiddle of my recent attempt:
My current css files look like this:
.profile-avatar {
  position:relative;
  height:170px;
}

.profile-avatar img {
  height: 160px;
  width: 160px;
  margin-left: 20px;
}

.profile-buttons {
  margin-left: 15px;
  margin-top: 110px;
}

I'm completely lost on how to add two rows of text to the top right of the image above the three buttons.
Any thoughts?
Thanks,
-Paul

A:

http://jsfiddle.net/kks6h0bc/7/
.text-0,.text-1{
    position: absolute;
    top: 0px;
   left: 200px;
    display:block;

}
.text-0{
    top: 0px;
    font-size:30px;
}

.text-1 {
    top: 50px;
}


Q:

Sort a Generic List with orderby or sort

I have a Generic List with this structure:
        public class Emoticon
    {
        public int id { get; set; }
        public string code { get; set; }
        public string emoticon_set { get; set; }
    }

    public class Emoticons
    {
        public List<Emoticon> emoticons { get; set; }
    }

The List is Emoticons twitch_emoticons. No i want to sort the list by the ID. can anyone help me?

A:

Add the namespace,
  using System.Linq;

Then try with,
var result = twitch_emoticons.OrderBy(res => res.id).ToList();


Q:

Обобщенный JSON

Сервер присылает ответы в формате
{response: {.......}}

например
{response: {code: 0}}
{response: {type: "test"}}

Пытаюсь сделать парсинг при помощи библиотеки gson в таком виде
class Response<T> {
    private T response;
    public T getResponse() {
        return response;
    }
}

class CodeInfo {
    private int code;
}

class TypeInfo {
    private String type;
}

<T> T parse(String str) {
  Response<T> resp = gson.fromJson(str, Response<T>.class);
  return resp.getResponse();
}

CodeInfo = parse<CodeInfo>("{response: {code: 0}}");

Внутренние классы довольно обширные
На конструкции Response<T>.class компилятор меня посылает. Решается ли задача без кучи наследников Response<T>? В принципе, могу даже сменить парсер

A:

Спасибо @diraria за направление на путь истинный. Итого получилось
public <T> T parse(String str, Class<T> AClass) {
  Response<T> resp = JSON.fromJson(
    str,
    TypeToken.getParameterized(Response.class, AClass).getType()
  );
  return resp.getResponse();
}

CodeInfo info = parse("{response: {code: 0}}", CodeInfo.class)

Если писать так
public <T> T parse(String str) {
  Response<T> resp = JSON.fromJson(
    str,
    new TypeToken<Response<T>>(){}.getType()
  );
  return resp.getResponse();
}

то строка парсится, но resp.getResponse() возвращает объект класса   com.google.gson.internal.LinkedTreeMap


Q:

how to build a xml response in twiml in ruby with comments

Xml response like below:
<?xml version="1.0" encoding="UTF-8"?>
    <Response>
    <!--my error message-->
<Reject/>
</Response>

enter code here:
currently i am using ruby to build response
xml.Response do |r|
     r.Reject
end.text

I need a comment before reject verb..Any one help?

A:

Twilio Evangelist here.
Twilio's Ruby helper library is built on Builder (see here). Therefore, you can use the standard Builder approach:
xml.Response do |r|
  r.comment! "This is a comment!"
  r.Reject
end.text

This will generate:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <!--This is a comment!-->
  <Reject/>
</Response>

Hope this helps!


Q:

Method with try catch and exception throws

So I have the following method:
template <class DT> //needs testing
DT& LinkedSortedArrays<DT>::find (const DT& key)
{
    list<SortedArray<DT>>::iterator it = SAList.begin();
    for( ; it != SAList.end(); ++it){
        try{
            if (it == SAList.begin() && key < (*it)[0]) throw Exception();
            return (*it).find(const_cast<DT&> (key));
        } catch (ArrayException e) {

        }
    }
    throw Exception();
}

I have previously defined the classes Exception and ArrayException. (*it).find(const_cast<DT&> (key)) will throw a ArrayException everytime that key is not found in the specific Array class being searched at the moment. SAList is a STL List. The code compiles just fine. However I haven't tried it in my program. Why? I need somebody to confirm or correct me on the following assumptions I have done:

Whenever if (it == SAList.begin() && key < (*it)[0]) throw Exception(); throws an exception, it means it will throw it outside the for loop and even outside the method, right?
I am almost sure that the last line throw Exception(); will throw the Exception outside the method.
The way the for loop is arranged, it won't skip the first element of SAList, right? I mean, I have seen this specific code all over the internet that serves to iterate through all elements of the list as if it was standard or flawless, but... that ++it is twisting my brain. Help?
I was receiving an error of can't convert const int to int& (since the find() in (*it).find(const_cast<DT&> (key)) is not the one belonging to LinkedSortedArrays but rather a different one that requires a DT& variable and LinkedSortedArrays's find() has parameters of type const DT&) and I found that a possible solution might be writing it as const_cast<DT&> (key). I need a second opinion on this.

Lastly, I understand if this is not a specific question and therefore I get downvotes and/or the question gets closed. I simply don't really know where else to ask.
If it is the case that I am asking in the wrong place. My apologies.

A:

Yes, it will go up the stack until it finds the appropriate catch handler. If it finds no such handler, the program will terminate.
Yes it will.
No, it will not, since end should return an iterator to one past the end, not the last element. Unless that container is badly designed as well, but  you'll have to consult the documentation to be sure.
That's a bad design, find should take its parameter by const reference. Since you can't, you'll have to make a copy unless you want to risk undefined behaviour:
DT nonconstkey = key;
return it->find(nonconstkey);


Q:

Regex captures don't live as long as I think they should

I'm trying to write a Rust function that takes a regex, and a string/str and returns a HashMap of all the named captures in that regex. Here's the code:
use std::collections::HashMap;
use regex::Regex;

fn get_matches<'a>(line: &'a str, re: &Regex) -> HashMap<&'a str, &'a str> {
    let mut results = HashMap::new();

    match re.captures(line) {
        None => { return results; },
        Some(caps) => {
            for (name, value) in caps.iter_named() {
                if let Some(value) = value {
                    results.insert(name, value);
                }
            }
        }
    }

    results
}

And I get this compiler error (Rust 1.9.0):
error: `caps` does not live long enough
      for (name, value) in caps.iter_named() {
                           ^~~~
note: reference must be valid for the lifetime 'a as defined on the block at 6:79...
    fn get_matches<'a>(line: &'a str, re: &Regex) -> HashMap<&'a str, &'a str> {
        let mut results = HashMap::new();

        match re.captures(line) {
            None => { return results; },
            Some(caps) => {
    ...
note: ...but borrowed value is only valid for the match at 9:8
        match re.captures(line) {
            None => { return results; },
            Some(caps) => {
                for (name, value) in caps.iter_named() {
                    if let Some(value) = value {
                        results.insert(name, value);
        ...

However, I don't understand. regex::Regex::captures return value has a lifetime of 't, which is the same lifetime as the string, in this case, that means 'a', the regex::Captures::iter_named returned value also has the same lifetime of 't, which is 'a in this case, and that means the (name, value) for that thing should also be 't, which in this case is 'a.
My function definition has a HashMap that uses that 'a lifetime, so shouldn't it all Just Work(tm)? I think I understand why you can't use a local variable, unless you return it, but in this case, I'm using references which should live long enough, right?
I suppose I could .clone() everything to String, but I'm curious if I can write this with just references. Isn't that supposed to be more efficient? I'm a little new to Rust, so I'm trying to grok things and do things in a proper, advanced way.

A:

Your reasoning is right, but you forgot a detail:

regex::Regex::captures return value has a lifetime of 't, which is the same lifetime as the string, in this case, that means 'a, the regex::Captures::iter_named* returned value also has the same lifetime of 't, which is 'a in this case, and that means the (name, value) for that thing should also be 't, which in this case is 'a.

* regex::Captures::iter_named also requires a &'t self, that is, &caps must have lifetime 't ('a in this case).
Note that the compiler is not complaining about results but about caps. regex::Regex::captures returns caps: Captures<'a>, that means that caps holds something with lifetime 'a. But to call regex::Captures::iter_named it is necessary to have a reference with lifetime 'a (iter_named parameter is &'a self = &'a Captures<'a>). Although caps holds something with lifetime 'a, it does not have lifetime 'a (the lifetime is only the Some arm).

I don't know how iter_named handle capture with empty names, but here is an implementation that returns only named captures:
extern crate regex;

use std::collections::HashMap;
use regex::Regex;

fn get_matches<'a>(line: &'a str, re: &'a Regex) -> HashMap<&'a str, &'a str> {
    let mut results = HashMap::new();

    match re.captures(line) {
        None => {
            return results;
        }
        Some(caps) => {
            for name in re.capture_names() {
                if let Some(name) = name {
                    if let Some(value) = caps.name(name) {
                        results.insert(name, value);
                    }
                }
            }
        }
    }

    results
}

This maybe slower than iter_named.


Q:

Push/pull of an unnamed branch, leaving behind the other (topologically unrelated) unnamed branches?

I use Mercurial named branches regularly for job and for hobbies, and I thought I understood them reasonably well.  I also thought that I understood the differences between named and unnamed/anonymous branches.  But a group at work has run into a problem that I admit has me a little stumped, and now I'm questioning my own understanding and all of my life decisions.
A coder was working on their default/unnamed line of development:
A -> B -> C

Then they did a few small commits for a side task, with the intention of later updating back to an ancestor and resuming normal checkins there.  That is, first doing:
A -> B -> C -> D -> E -> F

and then committing more to C:
             /-> D -> E -> F   (unnamed branch for later)
            /
A -> B -> C ---> G             (new tip)

Their plan is to come back to F at some future date.  So they did all that; work continued at G, and that part of the graph has been a surprisingly straight line from G to say M.
Now they want to sync their repo, and the target repository stops at say B.  (Both pushing or pulling are viable, so they'll use whichever approach supports whatever options are needed.)  Except that only the main path through the graph
A -> B -> C -> G -> ... -> M

should be pushed/pulled.  The D->E->F branch is topologically unrelated, and shouldn't (to my understanding) count as ancestors of G onward.  But trying things on the target repo like
hg incoming -r M  /path/to/above/repo
hg incoming -r M -b default  /path/to/above/repo

is correctly finding B as the most recent common ancestor, but then it decides that all changes "more recent" than B need to go across, instead of the ones along the branch from M back to B.
Gotta admit, I'm not sure how to exclude the little unnamed offshoot branches.  Personally, I typically clone the repo at C and then commit D through F off in the clone, but that's why I've never run into this situation and can't answer their question.  I've found lots of "guides to branching" that explain how to merge F back into M, and how to make sure the D->E->F branch is pushed remotely (--new-branch), and several writeups on how to make the offshoot go away (variations on --close-branch and no-op merging), but I know and use all of those already; I'm drawing a blank on how to simply leave it behind across a pull.
After we played around for a while and couldn't find the options to do this, their eventual solution was to clone the repo containing the offshoot, then strip the offshoot changesets before finally synchronizing.  Which everyone agreed was kind of kludgy, but at least let their team make progress again.  I'd like to find something better for next time.

A:

The easy way to do it is to mark these commits secret so that they just don't get exported at all.  That's not quite what you asked, but that's what I'd do.  Ignoring that option, though, I think the short answer is that you can't, at least not directly.  But that might be wrong; maybe you can, using the Convert extension.
Mercurial documentation likes to call these anonymous branches, but I think that this phrase is ill-advised.  I would just call them daglets, made up of a selected (usually linear) chain of commits leading up to each head.  A branch in Mercurial is a named entity.  Every commit exists on exactly one branch.  When you have a situation in which the default branch has commits:
        D--E--F
       /
A--B--C--G

what you really have is one branch, named default, with seven commits and two heads.  The fact that one head is named tip at the moment is not really relevant since we could easily create a new branch X with commit H:
default:           D--E--F
default:          /
default:   A--B--C--G
                     \
X:                    H

and now tip means commit H, not commit G.  Branch default continues to exist with its seven branches and two heads.  When you hook two hg repositories together, they'll transfer commits according to the (named) branches.
The convert extension does let you skip and/or re-map parts of the graph.  It's possible that you could use this to keep D-E-F from coming in, and/or to splice them into a different branch.  It seems like making this work would take a lot of human-time (and effort) and hence not really be particularly viable, though.


Q:

Link Strange Unicode

I've a link that when I copy paste it changes.the copied url is
https://www.webteb.com/tests/search?Text=الدم

the pasted
https://www.webteb.com/tests/search?Text=%20%D8%A7%D9%84%D8%AF%D9%85

as you can see the word الدم is converted to %20%D8%A7%D9%84%D8%AF%D9%85
How does that happen? what is the unicoding type?? how I can understand it?
I try in many ways but I'm still a beginner so I didn't find any good approach.

A:

What you've got there is Unicode text first encoded as UTF-8, then each byte of that encoded using URL encoding.
URL encoding replaces each byte by a percent sign (%) and two hex digits.
See https://en.wikipedia.org/wiki/Percent-encoding for more information.

Quick example:

%20 encodes a single byte, which is UTF-8 for U+0020 (SPACE, ).
%D8%A7 encodes two bytes (D8 A7), which is UTF-8 for U+0627 (ARABIC LETTER ALEF, ا).
%D9%84 encodes two bytes (D9 84), which is UTF-8 for U+0644 (ARABIC LETTER LAM, ل).
etc.


Q:

UIColor does not match standard RGB color wheel?

Hue in UIColor is not the same as a standard RGB color wheel. What I mean by that is, two opposing colors on a color wheel will match (i.e., yellow and purple), but if you take two opposing colors in UIColor, for example:
Color 1: Hue 0.45
Color 2: Hue 0.95
they don't match. Is there any way to find the opposite color in the spectrum through UIColor?

A:

Colors opposite each other on a wheel not usually called "matching", they are called "complementary", as in, if you mix them together, you get white (or black if you're dealing with subtractive colors, i.e., pigments).
RGB isn't really a color "wheel" -- it's more of a cube shape. The Hue in HSB, however, is often expressed as an angle, from 0˚ to 360˚, with red at 0˚, and turquoise at 180˚. If you take a value 180˚ from whatever you start with, you get the complement: Red 0˚/turquoise 180˚, green 120˚/purple 300˚, etc. When programming, the range of hue is usually written as a fraction between 0 and 1 inclusive. In that scheme, you can do
fmod(val - 0.5, 1.0)

to get the complement.
You haven't said what result you're expecting and what result you're getting, so it's hard to be specifically helpful, but 0.95 and 0.45 are indeed complementary, and when I create UIColors with those values, I see the expected reddish and turquoise-ish hues.
The colors on a computer screen behave differently than the colors of paint, because in the first case, you are adding wavelengths of light to get a result, and in the second, you are selectively absorbing wavelengths. This may be the source of your confusion. Red plus yellow equals orange with pigments, but red plus green equals yellow with light.


Q:

How to grab element you are hovering over?

How do you grab the element you are currently hovering over using pure Javascript, no jQuery?
HTML

JavaScript
(function() {

    var item = document.querySelector('li');

    function randomColor() {
        return '#' + Math.random().toString(16).slice(2, 8);
    }

    item.onmouseover = function() {
        this.style.backgroundColor = randomColor();
    };

    item.onmouseleave = function() {
        this.style.backgroundColor = randomColor();
    };

}());

The problem is that it only changes the color on one of the elements, but not the other 2 when hovering over.
Solution thanks to RUJordan
(function() {

    var box = document.querySelectorAll('li');

    function randomColor() {
        return '#' + Math.random().toString(16).slice(2, 8);
    }

    for (var i = 0; i <= box.length; i++) {

        box[i].onmouseover = function() {
            this.style.backgroundColor = randomColor();
        };

        box[i].onmouseleave = function() {
            this.style.backgroundColor = randomColor();
        };

    }

}());

A:

querySelector only returns the first index of the array of elements you would get back from that method.
To get all li, use querySelectorAll("li") and loop through the elements node list (array like) to add eventListeners to them.


Q:

Is there a natural number between $0$ and $1$?

Is there a natural number between $0$ and $1$?

A proof, s'il vous plaît, not your personal opinion. (Assume the Peano Postulates.)

A:

Every natural number $m$ is either $0$ or $s(n)$, where $n$ is a natural number.
Proof: It can't be both, because $s(n)$ can't be $0$. Set of all natural numbers which are either $0$ or $s(n)$ for some $n$ satisfies induction principle, so it contains all natural numbers.
Direct consequence: Every natural number is either $0$, or $s(0)$ or $s(s(n))$ for some natural number $n$.
Suppose there is $m$ such that $0 < m < s(0)$. Either $m$ is $0$, $s(0)$ or $s(s(n))$. First two cannot hold, so you have $s(s(n)) < s(0)$, i.e., $s(n) < 0$.


Q:

Filter node by custom_field in admin panel

I'm using Drupal 7, Views and Panels. Created a content type and custom field (field_list) And showing contents by list on my site. Thanks Views :) But when i click find content in admin panel, many many contents in my area.
Can i add filter option by field_list in my admin panel? Is it possible?

A:

You need to install Admin views module. It will replace administrative overview/listing pages with actual views for superior usability. Now, you can override your views for admin panel for filter content by field_list.


Q:

Add headers to JSON using JS

I'm looking to add text header to a JSON I'm tryind to send via JS, the actual method put the text in doubles quotes, here's what I expect by adding a header:

{"text": "URL.com"}

function getData() {
    var input = $("#user_input").val();
    var jsonencod = JSON.stringify(input);
    alert(jsonencod);
}
Enter a URL

<input type=" text"id="user_input">
<button onclick="getData()">Go!</button>

<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>

A:

The below should give you the output you are looking for.
Simply change input to {"text": input} to product the desired JSON.

function getData() {
    var input = $("#user_input").val();
    var jsonencod = JSON.stringify({"text": input});
    alert(jsonencod);
}
Enter a URL

<input type=" text"id="user_input">
<button onclick="getData()">Go!</button>

<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>


Q:

Dynamic Dropdowns POST

I'm trying to post the values that I get from each dropdown menu, this is an n-level, however I'm going to use them maximum of 3. How can I post every value i get from each selection?
 <?php

  include('dbcon.php');

  if($_REQUEST)
   {
$id     = $_REQUEST['parent_id'];

$query  = "select * from ajax_categories where pid = ".$id;
$results  = @mysql_query( $query);
$num_rows = @mysql_num_rows($results);
if($num_rows > 0)
{?>
    <select name="sub_category" class="parent">
    <option value="" selected="selected">-- Sub Category --</option>
    <?php
    while ($rows = mysql_fetch_assoc(@$results))
    {?>
        <option value="<?php echo $rows['id'];?>"><?php echo $rows['category'];?></option>
    <?php
    }?>
    </select>
<?php
}
else{echo 'No Record Found !';}
  }

  ?>

http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/

A:

change the select option of your like this
<select name="sub_category" class="parent">
    <option value="" selected="selected">-- Sub Category --</option>
 while ($rows = mysql_fetch_assoc(@$results))
    {?>
      echo   '<option value="'.$row['id'].'">'.$rows['category'].'</option>';

    <?php
    }?>
    </select>
<?php
}
else{echo 'No Record Found !';}
  }
 </select>


Q:

php preg_split into array

I have the following code:
$input = '2018-10-28T08:36:31.521Z';
$dateTime = preg_split('[T.]', $input);
echo ($dateTime[1]);

The output is:

08:36:31.521Z

the split with 'T' works, but dosen't work with '.' (The point)
I tried:
'[T\.]'

it dosen't work also (it dosen't ever split it).

A:

For preg_split() function, the pattern must be surrounded by slash (or other character that fits the needs). For exemple :
 $input = '2018-10-28T08:36:31.521Z';
 $dateTime = preg_split('/[T.]/', $input);

 echo ($dateTime[1]);

Output :

08:36:31

But for datetime manupulation, you'd better use PHP DateTime object.
Hope it helps.


Q:

As of Mountain Lion, Google Chrome has asked for permission to view my contacts. Does this mean that it has likely had unrestricted access before?

I'm not sure why Chrome wants this access, but since prior to Mountain Lion there wasn't a prompt for this, it makes me think that it must have been looking at them this whole time. Right?

A:

To turn this off and eliminate the error messages, you can do the following:

Click the Chrome menu  on the browser toolbar. Select Settings.
Click Show advanced settings and find the "Passwords and forms" section.
Click "Manage Autofill Settings"
Deselect the "Include addresses from my Address Book card" checkbox.

A:

Yes, right.  Round about Tiger (10.4) Apple introduced a nice neat way for apps to integrate with your address book and calendar data stores etc.  At the time it was a novel thing that allowed for any number of clever calendar widgets etc, and stuff that could happily replace the in-built tools (or enhance them) without you having to change anything at an account or data level.
These days, because of a number of high profile mobile apps getting in trouble for doing what the desktop OS have been doing for years, they are cranking up the security and privacy options.


Q:

When I integrate the PayPal SDK it prompt a error message "internal server error"

I Add the library of PayPal SDK and add
[PayPal initializeWithAppID:@"XXXXXXXXX" forEnvironment:XXXXXX];
 code then it give the error message "internal server Error"
Please provide me the step of in integration of PayPal.
There is no proper documentation of PayPal integration in iOS.In its sample code the parallel transaction going very smooth when i create a new project and add paypal library it gives an error.
In the sample code add -lxml2 in other linker library but In the documentation of PayPal there is no such things so I think something is missing in my project.

A:

Just add Bundle display name in your info.plist of your project as an empty.
Here's the screenshot.


Q:

declaring matrix as np.float32(np.array())

 matrix = np.float32(np.array([[0.0 for i in range(dimension)] for j in range(dimension)]))

If I want to do matrix operation in single precision, is the declaring array as above sufficient, or do I have to truncate for every arithmetic operation as follows?
np.float32(matrix[a][b] op matrix[c][d])

A:

No, you can specify the dtype of the array:
np.array([[0.0 for i in range(dimension)] for j in range(dimension)],
         dtype=np.float32)
Note that if you work with zeros, you can also use:
np.zeros((dimension, dimension), dtype=np.float32)

By specifying dtype, all elements of the array have the same type. You can also specify the type of data if for instance each column has the same type, but the columns might differ, like is described in this answer.


Q:

Likelihood across multiple averages... Sorta

Hopefully my title isn't misleading... i'm not sure what this math problem is called, making searching for the answer quite difficult. Maybe someone can tag this question appropriately if you know the name for what i'm asking.
The Question:
Let's suppose I am applying to get into a variety of schools, each one with a different acceptance percentage (defined as the number of students they accept out of the number of applications they receive). How do I determine what the likelihood is that I would be accepted into at least one of the schools, given I know the acceptance rate of each?
Example/Data:
School A: 50% Acceptance Rate
School B: 25% Acceptance Rate
School C: 25% Acceptance Rate
School D: 20% Acceptance Rate

Given the above data, what is the likelihood I'll be accepted into any (at least one) of schools A, B, C, or D.
What I know (or think i know)

It has to be at least as high as the highest percent (using the example, 50%)
If they were all 50% (like a coin-toss), the chances of getting all declined is 6.25% (1 in 16), leaving the remaining 15 possibilities, or 93.75%, with me getting into one or more schools.
No matter how many schools I add, the answer can never be equal to, or over 100%, unless one of the school's acceptance rates is 100% (asymptote?)

My own attempt at an answer
I started plugging numbers into excel based on some gut feelings on how to approach this. I used the coin-flip logic to test my calculations, then applied it to the example data. I ended up with answer of 77.5%, but am not sure if this is correct.
Here is a screenshot of my function and table:

(Note cell E4 with the same 93.75%)
Closing Remarks
This question was sparked in my office in response to this website which shows an "Aggregate Admission Probability" in which they simply add the percents. This seemed completely wrong and useless to me. Thought I would turn to the internets to settle the dispute :)
Hopefully this isn't something really easy that I am thinking is more complicated than it is. If that's true, let me down gently ;)

A:

I assume the probabilities are independent, meaning that one school's decision has no influence on the result of another. This is probably false, but it's the only way a definitive answer can be given (unless you know exactly what the dependence is).
The probability of getting into at least one school is $1$ minus the probability of getting rejected from every school. Assuming independence, this is just the product of the probabilities of getting rejected from each school. In your example, we get
$$1-(1-.5)(1-.25)(1-.25)(1-.5)=.859375=85.9375\%$$
as the probability of getting accepted into at least one school.


Q:

HDMI switches - how are they supposed to work?

I have never used any HDMI switch before, so my knowledge about them is zero.
Now I have one and I am wondering if its behaviour is normal.
I have a beamer for the output signal, a Wii U as first input signal and a laptop as second input signal. The switch I bought has one output and two input plugs, so I put them in accordingly. The packaging says that the switch has an automatic switching function, pretending that the correct signal will be recognized.
Now what happens? The switch only let a signal through if BOTH input devices are PLUGGED IN AND SWITCHED ON. Then, I can use the manual switch button to switch to the signal I want. But whenever I turn one of the devices off (Wii U or laptop) or unplug it (we only plug the laptop in if we want to wantch movies), no signal gets through to the beamer. And the manual switch button does not work either.
Is this behaviour normal, or have I just bought junk?
I was expecting that it recognizes if just one input is switched on and lets this signal through accordingly. This is what I think of "automatic switching".
What are your experiences with HDMI switches? Are there any models that do what I expect of them, or is the behaviour of my switch the normal one? Mine is from Vivanco, and it cost 45€. It says "full HDTV" and 1080p, and supports deep color.
Any suggestions on other manufacturers, models and usual prices will be appreciated. I live in Germany, so if anyone knows models I can get here (via amazon.de or just some media store), this will be especially appreciated.

A:

Most video switches will attempt to draw power from the inputs, but if you want them to work in all conditions (e.g., no input providing power to one side) you need a separate power connection.  Your switch probably has a DC power input: just get a corresponding connector and plug it in.


Q:

Select Specific Columns only form a dataframe in Python

Using python and pandas as pd, I am trying to OUTPUT a file that has a subset of columns based on specific headers.
Here is an example of an input file
gene_input = pd.read_table(args.gene, sep="\t" ,index_col=0)

The structure of gene_input:

       Sample1  Sample2  Sample3  Sample4  Sample5  Sample6  Sample7  Sample8
Gene1        2       23      213      213       13      132      213     4312
Gene2        3       12    21312      123      123       23     4321      432
Gene3        5      213    21312       15      516     3421     4312     4132
Gene4        2      123      123        7      610       23     3214     4312
Gene5        1      213      213        1      152       23     1423     3421

Using a different loop, I generated TWO dictionaries. The first one has the keys (Sample 1 and Sample 7) and the second has the keys (Sample 4 and 8).
I would like to have the following output (Note that I want the samples from each of the dictionaries to be consecutive; i.e. all Dictionary 1 first, then all Dictionary 2):
The output that I am looking for is:

        Sample1 Sample7 Sample4 Sample8
Gene1   2   213 213 4312
Gene2   3   4321    123 432
Gene3   5   4312    15  4132
Gene4   2   3214    7   4312
Gene5   1   1423    1   3421

I have tried the following but none worked:
key_num=list(dictionary1.keys())
num = genes_input[gene_input.columns.isin(key_num)]

In order to extract the first set of columns then somehow combine it, but that failed. It kept giving me attributes error, and i did update pandas. I also tried the following:
reader = csv.reader( open(gene_input, 'rU'), delimiter='\t')
header_row = reader.next() # Gets the header

for key, value in numerator.items():
    output.write(key + "\t")
    if key in header_row:
        for row in reader:
            idx=header_row.index(key)
            output.write(idx +"\t")

as well as some other commands/loops/lines. Sometimes i only get the first key only to be in the output, other times i get an error; depending on which method i tried (i  am not listing them all here for sake of convenience).
Anyway, if anyone has any input on how  I can generate the output file of interest, I'd be grateful.
Again, here is what I want as a final output:

        Sample1 Sample7 Sample4 Sample8
Gene1   2   213 213 4312
Gene2   3   4321    123 432
Gene3   5   4312    15  4132
Gene4   2   3214    7   4312
Gene5   1   1423    1   3421

A:

For a specific set of columns in a specific order, use:
df = gene_input[['Sample1', 'Sample2', 'Sample4', 'Sample7']]
If you need to make that list (['Sample1',...]) automatically, and the names are as given, you should be able to build the two lists, combine them and then sort:
column_names = sorted(dictionary1.keys() + dictionary2.keys())
The names that you have should sort correctly. For output, you should be able to use:
df.to_csv(<output file name>, sep='\t')
EDIT: added part about output


Q:

Jquery SlideUp , close but don't show effect

I want use slideUp with jquery , for close div i use slideUp , but close div happend in one second and don´t show really this effect
My script it´s this :
jQuery("#web_header_info_show_close").click(function() {

jQuery("#web_header_info_show").slideUp(2000);

});

The case i try modificate all time the time but always get the same , and if i change the time inside function and put more time , the effect continue don´t show and close in one second the div , i don´t know if it´s because  use click function , but i think don´t must be a problem for works well slideUp
Thank´s for the help , Regards
UPDATE INFOR :
YOU CAN SEE DEMO HERE : https://jsfiddle.net/gzdjdz25/

A:

The issue is with min-height:100px; use height:100px; instead.
#web_header_info_show{
position:relative;
width:100%;
height:100px;
font-family:Arial;
font-size:14px;
color:#ffffff;
background-color:red;
}

Here's the updated fiddle:
https://jsfiddle.net/gzdjdz25/1/


Q:

Не получается добавить библиотеку при сборке проекта

Здравствуйте,есть класс,который подключается к базе данных.
C помощью eclipse создаю jar файл в котором этот класс и mysql connection,при запуске jar я постоянно вижу ошибку java.lang.ClassNotFoundException: com.mysql.jdbc:Driver подскажите,что я делаю не правильно?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

        public class Solution1 {
            private static Connection connection = null;
            private static Statement statement = null;
            private static String url = "jdbc:mysql://localhost:3306/example?autoReconnect=true&useSSL=false";

            public static void main(String[] args) {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    connection = DriverManager.getConnection(url, "admin", "admin");
                    statement = connection.createStatement();
                    PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM Example");
                    ResultSet resultSet = preparedStatement.executeQuery();

                    while (resultSet.next()) {
                        System.out.println(resultSet.getString(2));
                    }

                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

в итоге jar содержит:

пакет main в котором класс
jar файл connection
папка МЕТА-INF(сгенерирована автоматически)

A:

Проблема в том, что, когда Вы собираете проект, библиотеки и не добавляются в конечный исполняемый файл.
Для того, чтобы работал Ваш исполняемый файл:

Или пропишите путь к .jar в пути запуска.
Или добавьте в pom.xml (если Вы используете Maven:
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>

    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
            <archive>
                <manifest>
                    <mainClass>com.пакет.Main</mainClass>
                </manifest>
            </archive>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
        <executions>
            <execution>
                <id>make-assembly</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>

Main

                    jar-with-dependencies

                    make-assembly
                    package

                        single

Или же Вы можете вынести все зависимости в отдельную папку:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>${plugin.dependency.version}</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${distrib.directory}/lib</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                    </configuration>
                </execution>
            </executions>
        </plugin>


Q:

Is it enough to have Intermediate CA certificate in Trust store to validate a server certificate?

Lets assume that below is the chain:
Server cert -> Intermediate1 -> Intermediate2 ->Root cert
Below is the chain server sent to the client:
Server cert -> Intermediate1 -> Intermediate2
I have Intermediate1 certificate only(no other cert) in my truststore.
Given this scenario, Does client can verify the server certificate?
I'm pretty sure Client verifies successfully and initiates the SSL connection As the immediate Issuer is present in the trust store. Am i wrong?

A:

Take a look at RFC 5280 Section 6.

The selection of a trust anchor is a matter of policy: it could be
     the top CA in a hierarchical PKI, the CA that issued the verifier's
     own certificate(s), or any other CA in a network PKI.  The path validation procedure is the same regardless of the choice of trust
     anchor.  In addition, different applications may rely on different
     trust anchors, or may accept paths that begin with any of a set of
     trust anchors.

In other words, it depends on the implementation of the certification path validation at the client side. For some clients it works by having only a trusted intermediate CA certificate for others the full chain is required. Some client also cache the intermediate certificate once they have been verified in order to speed up the validation process.

A:

If you have the certificate for intermediate 1 in the trust store then this means that you trust the certificates issued by this CA, which includes the server certificate in question. Thus if the server sends only its leaf certificate issued by intermediate 1 then the client will trust it.
In theory the client would also trust the server if the server additionally sends intermediate 1 and intermediate 2, i.e. the CA's needed in the trust path to the root CA. Since the client does not know (trust) the root CA but trusts intermediate 1 only the superfluous chain certificates sent by the server should be simply ignored. Most clients behave that way but there was a bug in OpenSSL version before 1.0.2 where the validation failed in this case. See OpenSSL issue#3621 or this explanation at stackoverflow for more details.


Q:

SQL : select minimum value AND other values in the row with the minimum

Using Oracle SQL, I want to select a group of people's ID, test date, and test results based on when the test was taken. My problem is that the order of priority is not in chronological order. I want to select a date in year 1. If they don't have it in year 1, I want the date from year 3. If they don't have 1 or 3, I want the date from year 2.
I used a case function to create a variable (check1) to assign a value to each row based on the priority of the year in which the test was taken. So all rows have a 1, 2, or 3 in the check1 column. (1 is highest priority, 3 is lowest.)
I know how many people fall into each group using:
SELECT ID, MIN(check1)
FROM datatable
GROUP BY ID;

Here's my problem: I also need the date that they took the test so that I can join the correct test results back to the desired date. When I try to add the date to the previous function:
SELECT ID, MIN(check1), date
FROM datatable
GROUP BY ID;

Oracle errors because the date variable is not in the GROUP BY function. However, when I put the date in the group by function, it selects all the records, not just the min(check1).
How do I get it to select one row per person with the date I want?
Thanks in advance!!

A:

Often, the fastest method is a correlated subquery:
SELECT t.*
FROM datatable t
WHERE t.date = (SELECT MIN(t2.check1) FROM datatable t2 WHERE t2.id = t.id);

Or, an aggregation using KEEP:
select id, min(check1), min(date) keep (dense_rank first order by check1 asc) as date
from datatable t
group by id;


Q:

How can I upload a file via php?

I try to make a simple file uploader in php, but I fail already at the beginning.
This is the tutorial:
https://www.youtube.com/watch?v=PRCobMXhnyw
So at the beginning I should make a file index.html:
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>File upload</title>
    </head>
    <body>
        <from action="upload.php" method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="upload">
        </form>
    </body>
</html>

and an upload.php:
<?php
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];
    print_r($file);
}

When I upload the file I should see on my screen:
Array ([name] => uploadme.txt [type/plain [tmp_name] =>
/Applications/MAMP/tmp/php/phpXkZIVD [error] => 0 [size] => 9)

But it is not working. If i click on "upload" there is just nothing happen. What am I doing wrong?

A:

Mistake :
You are having typo in the <form
<from action="upload.php" method="post" enctype="multipart/form-data">
It should be as
<form action="upload.php" method="post" enctype="multipart/form-data">
It prevents you to submit the form
What you should do :
You're just printing the uploaded file, but you should move it to some folder like this.
$target_file = 'upload/'.basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);

Note :
You should create a folder named as upload and it should have read/write permission.
So, Your code should look something like this
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>File upload</title>
    </head>
    <body>
        <form action="upload.php" method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="upload">
        </form>
    </body>
</html>
<?php
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];
    print_r($file);
    $target_file = 'upload/'.basename($_FILES["file"]["name"]);
    move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
}
?>


Q:

Can I upgrade Windows 10 Home to Pro on a system running a dual boot with Windows 10 (Home) and Linux Mint?

I have a system running a dual boot setup with Linux Mint and Windows 10 Home.
Linux Mint is my daily driver but I want to do some stuff on Windows which requires Windows 10 Pro. I already have a new license key for the Pro version but I'm a bit hesitant in just running the upgrade.
Is the update going to destroy my Linux Mint installation?
Is the update going to destroy my Bootloader?

A:

Yes, you can upgrade.
Adding the Pro license just enables the Pro features, it's not a reinstallation (and even if it was, as long as you know what you're doing, dual-boot or not is irrelevant).
Occasionally Windows feature updates changes the boot order but users can always revert it to the previous configuration. This however is unrelated to the "Home to Pro" upgrade.