问:
Ruby Mail, how to achieve SSL email
I have successfully sent email to a remote server using port their port 25 (non-secure) with this script:

```<code>require 'rubygems'
require 'mail'

options = { :address              => "mail.domain.com",
            :port                 => 25,
            :domain               => 'mail.domain.com',
            :user_name            => 'somedude@domain.com',
            :password             => 'topsecret',
            :authentication       => 'login',
            :enable_starttls_auto => true  }
 Mail.defaults do
  delivery_method :smtp, options
end

 mail = Mail.new do
      from 'someotherdude@otherdomain.com'
        to 'somedude@domain.com'
   subject 'This is a test email'
      body File.read('body.txt')
 end

puts mail.to_s
mail.deliver!
</code>```

What I need to do now is use their SSL port 466. When I try it, I get the normal output detailing the message, then it pauses for about 2 minutes and coughs up this:

```<code>/usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/timeout.rb:60:in `rbuf_fill': execution expired (Timeout::Error)
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/protocol.rb:134:in `rbuf_fill'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/protocol.rb:126:in `readline'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:911:in `recv_response'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:554:in `do_start'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:921:in `critical'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:554:in `do_start'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:525:in `start'
        from /usr/local/rvm/gems/ruby-1.8.7-p249/gems/mail-2.2.10/lib/mail/network/delivery_methods/smtp.rb:127:in `deliver!'
        from /usr/local/rvm/gems/ruby-1.8.7-p249/gems/mail-2.2.10/lib/mail/message.rb:243:in `deliver!'
        from testmail.rb:30
</code>```

I think this is because it cannot even begin the SSL authentication process. How do I do it?

答:
Hmm reading the network/delivery_methods/smtp.rb,  it doesn't look like it support Direct SSL.  TLS isn't them same, as the connection starts out Plain Text and then Switches to SSL on the starttls command.   Can you just use starttls on port 587?

pulling my comment up.

see

How to send mail with ruby over smtp with ssl (not with rails, no TLS for gmail)

Which suggests that you can monkey patch Net::SMTP to do it..

Ok kinda found the issue and can patch around it, but so far this solution is yucky..  but it does work :)

```<code>#!/usr/bin/env ruby

require 'rubygems'
require "openssl"
require "net/smtp"
require "mail"

Net::SMTP.class_eval do

  def self.start( address, port = nil,
                  helo = 'localhost.localdomain',
                  user = nil, secret = nil, authtype = nil, use_tls = false,
                  use_ssl = true, &block) # :yield: smtp
    new(address, port).start(helo, user, secret, authtype, use_tls, use_ssl, &block)
  end

  def start( helo = 'localhost.localdomain',
             user = nil, secret = nil, authtype = nil, use_tls = false, use_ssl = true ) # :yield: smtp
    start_method = use_tls ? :do_tls_start : use_ssl ? :do_ssl_start : :do_start
    if block_given?
      begin
        send start_method, helo, user, secret, authtype
        return yield(self)
      ensure
        do_finish
      end
    else
      send start_method, helo, user, secret, authtype
      return self
    end
  end

  private

  def do_tls_start(helodomain, user, secret, authtype)
    raise IOError, 'SMTP session already started' if @started

    check_auth_args user, secret

    sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
    @socket = Net::InternetMessageIO.new(sock)
    @socket.read_timeout = 60 #@read_timeout
    @socket.debug_output = STDERR #@debug_output

    check_response(critical { recv_response() })
    do_helo(helodomain)

    raise 'openssl library not installed' unless defined?(OpenSSL)
    starttls
    ssl = OpenSSL::SSL::SSLSocket.new(sock)
    ssl.sync_close = true
    ssl.connect
    @socket = Net::InternetMessageIO.new(ssl)
    @socket.read_timeout = 60 #@read_timeout
    @socket.debug_output = STDERR #@debug_output
    do_helo(helodomain)

    authenticate user, secret, authtype if user
    @started = true
  ensure
    unless @started
      # authentication failed, cancel connection.
        @socket.close if not @started and @socket and not @socket.closed?
      @socket = nil
    end
  end

  def do_ssl_start(helodomain, user, secret, authtype)
    raise IOError, 'SMTP session already started' if @started

    check_auth_args user, secret

    sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
    raise 'openssl library not installed' unless defined?(OpenSSL)
    ssl = OpenSSL::SSL::SSLSocket.new(sock)
    ssl.sync_close = true
    ssl.connect
    @socket = Net::InternetMessageIO.new(ssl)
    @socket.read_timeout = 60 #@read_timeout
    @socket.debug_output = STDERR #@debug_output

    check_response(critical { recv_response() })
    do_helo(helodomain)

    do_helo(helodomain)

    authenticate user, secret, authtype if user
    @started = true
  ensure
    unless @started
      # authentication failed, cancel connection.
        @socket.close if not @started and @socket and not @socket.closed?
      @socket = nil
    end
  end

  def do_helo(helodomain)
     begin
      if @esmtp
        ehlo helodomain
      else
        helo helodomain
      end
    rescue Net::ProtocolError
      if @esmtp
        @esmtp = false
        @error_occured = false
        retry
      end
      raise
    end
  end

  def starttls
    getok('STARTTLS')
  end

  def quit
    begin
      getok('QUIT')
    rescue EOFError, OpenSSL::SSL::SSLError
    end
  end
end

options = {
  :address              => "mail.domain.net",
  :port                 => 466,
  :domain               => 'mail.domain.net',
  :user_name            => 'doon@domain.net',
  :password             => 'Secret!',
  :authentication       => 'login',
  :use_ssl => true  }

Mail.defaults do
  delivery_method :smtp, options
end

mail = Mail.new do
  from 'doon@domain.net'
  to 'doon@someotherdomain.com'
  subject 'This is a test email'
  body File.read('body.txt')
end

puts mail.to_s
mail.deliver!
</code>```

for some reason the use_ssl in the orig monkey patch doesn't make it in, and couple that with VERSION being undefined in Net::SMTP.    So I changed that out, and forced use_ssl to be true, and was able to send email..

Title: Ruby Mail, how to achieve SSL email

Body:
I have successfully sent email to a remote server using port their port 25 (non-secure) with this script:

require 'rubygems'
require 'mail'

options = { :address              => "mail.domain.com",
            :port                 => 25,
            :domain               => 'mail.domain.com',
            :user_name            => 'somedude@domain.com',
            :password             => 'topsecret',
            :authentication       => 'login',
            :enable_starttls_auto => true  }
 Mail.defaults do
  delivery_method :smtp, options
end

 mail = Mail.new do
      from 'someotherdude@otherdomain.com'
        to 'somedude@domain.com'
   subject 'This is a test email'
      body File.read('body.txt')
 end

puts mail.to_s
mail.deliver!

What I need to do now is use their SSL port 466. When I try it, I get the normal output detailing the message, then it pauses for about 2 minutes and coughs up this:

/usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/timeout.rb:60:in `rbuf_fill': execution expired (Timeout::Error)
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/protocol.rb:134:in `rbuf_fill'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/protocol.rb:126:in `readline'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:911:in `recv_response'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:554:in `do_start'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:921:in `critical'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:554:in `do_start'
        from /usr/local/rvm/rubies/ruby-1.8.7-p249/lib/ruby/1.8/net/smtp.rb:525:in `start'
        from /usr/local/rvm/gems/ruby-1.8.7-p249/gems/mail-2.2.10/lib/mail/network/delivery_methods/smtp.rb:127:in `deliver!'
        from /usr/local/rvm/gems/ruby-1.8.7-p249/gems/mail-2.2.10/lib/mail/message.rb:243:in `deliver!'
        from testmail.rb:30

I think this is because it cannot even begin the SSL authentication process. How do I do it?

Body:
Hmm reading the network/delivery_methods/smtp.rb,  it doesn't look like it support Direct SSL.  TLS isn't them same, as the connection starts out Plain Text and then Switches to SSL on the starttls command.   Can you just use starttls on port 587?

pulling my comment up.

see

How to send mail with ruby over smtp with ssl (not with rails, no TLS for gmail)

Which suggests that you can monkey patch Net::SMTP to do it..

Ok kinda found the issue and can patch around it, but so far this solution is yucky..  but it does work :)

#!/usr/bin/env ruby

require 'rubygems'
require "openssl"
require "net/smtp"
require "mail"

Net::SMTP.class_eval do

  def self.start( address, port = nil,
                  helo = 'localhost.localdomain',
                  user = nil, secret = nil, authtype = nil, use_tls = false,
                  use_ssl = true, &block) # :yield: smtp
    new(address, port).start(helo, user, secret, authtype, use_tls, use_ssl, &block)
  end

  def start( helo = 'localhost.localdomain',
             user = nil, secret = nil, authtype = nil, use_tls = false, use_ssl = true ) # :yield: smtp
    start_method = use_tls ? :do_tls_start : use_ssl ? :do_ssl_start : :do_start
    if block_given?
      begin
        send start_method, helo, user, secret, authtype
        return yield(self)
      ensure
        do_finish
      end
    else
      send start_method, helo, user, secret, authtype
      return self
    end
  end

  private

  def do_tls_start(helodomain, user, secret, authtype)
    raise IOError, 'SMTP session already started' if @started

    check_auth_args user, secret

    sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
    @socket = Net::InternetMessageIO.new(sock)
    @socket.read_timeout = 60 #@read_timeout
    @socket.debug_output = STDERR #@debug_output

    check_response(critical { recv_response() })
    do_helo(helodomain)

    raise 'openssl library not installed' unless defined?(OpenSSL)
    starttls
    ssl = OpenSSL::SSL::SSLSocket.new(sock)
    ssl.sync_close = true
    ssl.connect
    @socket = Net::InternetMessageIO.new(ssl)
    @socket.read_timeout = 60 #@read_timeout
    @socket.debug_output = STDERR #@debug_output
    do_helo(helodomain)

    authenticate user, secret, authtype if user
    @started = true
  ensure
    unless @started
      # authentication failed, cancel connection.
        @socket.close if not @started and @socket and not @socket.closed?
      @socket = nil
    end
  end

  def do_ssl_start(helodomain, user, secret, authtype)
    raise IOError, 'SMTP session already started' if @started

    check_auth_args user, secret

    sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
    raise 'openssl library not installed' unless defined?(OpenSSL)
    ssl = OpenSSL::SSL::SSLSocket.new(sock)
    ssl.sync_close = true
    ssl.connect
    @socket = Net::InternetMessageIO.new(ssl)
    @socket.read_timeout = 60 #@read_timeout
    @socket.debug_output = STDERR #@debug_output

    check_response(critical { recv_response() })
    do_helo(helodomain)

    do_helo(helodomain)

    authenticate user, secret, authtype if user
    @started = true
  ensure
    unless @started
      # authentication failed, cancel connection.
        @socket.close if not @started and @socket and not @socket.closed?
      @socket = nil
    end
  end

  def do_helo(helodomain)
     begin
      if @esmtp
        ehlo helodomain
      else
        helo helodomain
      end
    rescue Net::ProtocolError
      if @esmtp
        @esmtp = false
        @error_occured = false
        retry
      end
      raise
    end
  end

  def starttls
    getok('STARTTLS')
  end

  def quit
    begin
      getok('QUIT')
    rescue EOFError, OpenSSL::SSL::SSLError
    end
  end
end

options = {
  :address              => "mail.domain.net",
  :port                 => 466,
  :domain               => 'mail.domain.net',
  :user_name            => 'doon@domain.net',
  :password             => 'Secret!',
  :authentication       => 'login',
  :use_ssl => true  }

Mail.defaults do
  delivery_method :smtp, options
end

mail = Mail.new do
  from 'doon@domain.net'
  to 'doon@someotherdomain.com'
  subject 'This is a test email'
  body File.read('body.txt')
end

puts mail.to_s
mail.deliver!

for some reason the use_ssl in the orig monkey patch doesn't make it in, and couple that with VERSION being undefined in Net::SMTP.    So I changed that out, and forced use_ssl to be true, and was able to send email..


来源: stackexchange

问:
JTabbedPane click event
I need to be able to process a click on the tabs in a JTabbedPane. I'm not using this to change tabs, and this isn't going to trigger on tab change. What I'm attempting to do is close the tab when it is right clicked. However, I'm not sure how I can access the tab to add a click event on it. Most of the questions related to clicking on JTabbedPanes suggest using a ChangeListener, but that won't work, since the tabs aren't going to be changed on right click.

Is there any way for me to add a click event to a JTabbedPane's tab?

答:
Sorry for late answer, but I found this very usefull for me and for avoid extra clicks detected by stateChanged (with this you can detect all you want in "click tab"):

```<code>myJTabbedPane.addMouseListener(new MouseListener()
{

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("Panel 1 click");
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub

    }

});
</code>```

Finally, if you want to detect right click on tab you can see next tutorial (search getModifiers() in next page):

https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

ContentLicense: CC BY-SA 3.0

Title: JTabbedPane click event

Body:
Sorry for late answer, but I found this very usefull for me and for avoid extra clicks detected by stateChanged (with this you can detect all you want in "click tab"):

myJTabbedPane.addMouseListener(new MouseListener()
{

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println("Panel 1 click");
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub

    }

});

Finally, if you want to detect right click on tab you can see next tutorial (search getModifiers() in next page):

https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html


问:
Passport authentication won't pass
I am trying to use passport authentication with a local strategy but the authentication fails every time and doesn't move on to the local strategy.
I have added a couple console logs to see where the code is derailed but nothing at all is logged.

users.js(router)

```<code>var express = require('express');
var router = express.Router();
var User = require('../models/user');
var multer=require('multer');
var passport=require('passport');
var LocalStrategy=require('passport-local').Strategy;

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/register', function(req, res, next) {
  res.render('register',{
    'title':'Register'
  });
});

router.get('/login', function(req, res, next) {
  res.render('login',{
    'title':'Login'
  });
});

passport.use(new LocalStrategy(
    function(username,password,done){
        console.log('words');
        User.getUserByUsername(username,function(err,user){
            if (err) throw err;
            if(!user){
                console.log('Unknown user');
                return done(null,false);
            }
        });
    }
));

router.post('/login',passport.authenticate('local',{failureRedirect:'/users/register'}),function(req,res){
    console.log('Authentication succesful');
    req.flash('success','You are logged in');
    res.redirect('/');
});

module.exports = router;
</code>```

答:
Did you set the session and added passport to the router? I don't know if setting the initialize and session method in two different spots will work.
This is how I made it work: All set in in a router

```<code>let express = require('express');
let session = require('express-session');
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let router = express.Router();

passport.use(new LocalStrategy(
function(username, password, done) {
     User.findOne({username: username}, function (err, user) {
          if (err) { return done(err); }
          if (!user) {
               return done(null, false, { message: 'Incorrect username.' });
          }
          user.comparePassword(password, function (err, isMatch) {
               if (err) { return done(err); }
               if(!isMatch){
                    return done(null, false, { message: 'Incorrect password.' });
                } else {
                    return done(null, user);
                }
          });
       });
    }

));
passport.serializeUser(function(user, done) {
        done(null, {email: user.email, roles : user.roles});
});
passport.deserializeUser(function(session, done) {
    User.findOne({email: session.email}, function(err, user) {
          done(err, user);
    });
});
router.use(session({ secret: 'my super secret',name: 'my-id', resave: false, saveUninitialized: false }));

router.use(passport.initialize());
router.use(passport.session());
</code>```

Furthermore if this ever goes into production you need a different session handler than express-session like MongoStore or Redis

The routes

```<code>/* GET home page. */
 router.get('/', require('connect-ensure-login').ensureLoggedIn('login'), function (req, res, next) {
     if (req.user) {
         res.render('index');
    } else {
         res.redirect('/login');
    }
});

 router.get('/login', function (req, res, next) {
     res.render('login');
});
 router.post('/login', passport.authenticate('local', {
     successRedirect: '/',
     failureRedirect: '/login'
}));

 router.get('/logout', function (req, res) {
req.logout();
res.render('logout');
});
</code>```

Title: Passport authentication won't pass

Body:
I am trying to use passport authentication with a local strategy but the authentication fails every time and doesn't move on to the local strategy.
I have added a couple console logs to see where the code is derailed but nothing at all is logged.

users.js(router)

var express = require('express');
var router = express.Router();
var User = require('../models/user');
var multer=require('multer');
var passport=require('passport');
var LocalStrategy=require('passport-local').Strategy;

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/register', function(req, res, next) {
  res.render('register',{
    'title':'Register'
  });
});

router.get('/login', function(req, res, next) {
  res.render('login',{
    'title':'Login'
  });
});

passport.use(new LocalStrategy(
    function(username,password,done){
        console.log('words');
        User.getUserByUsername(username,function(err,user){
            if (err) throw err;
            if(!user){
                console.log('Unknown user');
                return done(null,false);
            }
        });
    }
));

router.post('/login',passport.authenticate('local',{failureRedirect:'/users/register'}),function(req,res){
    console.log('Authentication succesful');
    req.flash('success','You are logged in');
    res.redirect('/');
});

module.exports = router;

Body:
Did you set the session and added passport to the router? I don't know if setting the initialize and session method in two different spots will work.
This is how I made it work: All set in in a router

let express = require('express');
let session = require('express-session');
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let router = express.Router();

passport.use(new LocalStrategy(
function(username, password, done) {
     User.findOne({username: username}, function (err, user) {
          if (err) { return done(err); }
          if (!user) {
               return done(null, false, { message: 'Incorrect username.' });
          }
          user.comparePassword(password, function (err, isMatch) {
               if (err) { return done(err); }
               if(!isMatch){
                    return done(null, false, { message: 'Incorrect password.' });
                } else {
                    return done(null, user);
                }
          });
       });
    }

));
passport.serializeUser(function(user, done) {
        done(null, {email: user.email, roles : user.roles});
});
passport.deserializeUser(function(session, done) {
    User.findOne({email: session.email}, function(err, user) {
          done(err, user);
    });
});
router.use(session({ secret: 'my super secret',name: 'my-id', resave: false, saveUninitialized: false }));

router.use(passport.initialize());
router.use(passport.session());

Furthermore if this ever goes into production you need a different session handler than express-session like MongoStore or Redis

The routes

/* GET home page. */
 router.get('/', require('connect-ensure-login').ensureLoggedIn('login'), function (req, res, next) {
     if (req.user) {
         res.render('index');
    } else {
         res.redirect('/login');
    }
});

 router.get('/login', function (req, res, next) {
     res.render('login');
});
 router.post('/login', passport.authenticate('local', {
     successRedirect: '/',
     failureRedirect: '/login'
}));

 router.get('/logout', function (req, res) {
req.logout();
res.render('logout');
});


问:
Migrating from DotNetNuke to ASP.NET Core
I have an application based on DNN (a bunch of DNN modules) and would like to gradually migrate this app to plain ASP.NET Core. (getting away from DNN)
I'm only depending on DNN user management and navigation, all the rest is basically plain ASP.NET Web Forms. (or better: Web User Controls in DNN)

The plan is to create a brand new app (different sub-domain) and first migrate my user management to .NET Core Identity. Users would login via the new app and will need to switch between the Core App and DNN during the migration period. I want to use the new identity based mechanism and would have to keep users in sync with the DNN Membership based tables until I can deprecate the last DNN module.

From: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity
It seems identity creates its own cookie that is totally different from DNN.
Does anyone know of a way to create a shared cookie that would allow users to move from the old to the new app without having to login twice?
Or is there a better way to realize this functionality?

UPDATE:
Doing more research and at this point it seems to make more sense to split this project up in 2 phases:
1. Start the new App using MVC 5 (for stability)
2. Migrate the MVC 5 App to .NET Core after a while

The question still remains for MVC 5 using OWIN authentication in this case. Would it be possible to create a shared auth cookie between MVC and DNN?

答:
For anyone with the same problem, I found out that what I want to do is not possible. The format of authentication cookie has been changed with OWIN and there is no backwards compatibility with the previous FormsAuthentication.

I was able to create an OWIN cookie with the same name, MachineKey encryption, etc. but the content is different and DNN won't recognize this.

I will have to add an extra phase into my migration.
1. Create a new app with MVC 5 but use the old forms authentication
2. After all modules are migrated, I will be able to move to OWIN
3. Migrate to ASP.NET core


问:
Setting private property on ViewModel
I have followed this tutorial for creating drop downs in ASP.NET MVC: http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx

The code sample given is:

```<code>public class IceCreamFlavor
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ViewModel
{
    private readonly List<IceCreamFlavor> _flavors;

    [Display(Name = "Favorite Flavor")]
    public int SelectedFlavorId { get; set; }

    public IEnumerable<SelectListItem> FlavorItems
    {
        get { return new SelectList(_flavors, "Id", "Name");}
    }
}
</code>```

What is the proper way to set _flavors?  It is private readonly.  Is there any reason for this?  Some feature of MVC to populate it?

I can obviously make it public or private with a constructor but I am wondering why Scott Allen set it this way.  Is there some logic to it?

答:
What is the proper way to set _flavors?

You can set it to any List<IceCreamFlavor> you want based on your custom logic in the constructor of the view model.

The readonly modifier means that any assignments to the field must occur as part of the declaration or in a constructor in the same class: https://msdn.microsoft.com/en-us/library/acdd6hb7.aspx.

So you cannot set this field from anywhere else than in the constructor of the ViewModel class. The part of initializing the list has obviously been omitted from the example ("assuming the _flavors field is populated with real ice cream flavors from a database or elsewhere") but the view model class is supposed to create the List<IceCreamFlavor> in its constructor and then simply expose an IEnumerable<SelectListItem> that the view can bind to. The outside world only knows about the IEnumerable . Only the view model class itself knows about the private _flavors field.

Title: Setting private property on ViewModel

Body:
I have followed this tutorial for creating drop downs in ASP.NET MVC: http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx

The code sample given is:

public class IceCreamFlavor
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ViewModel
{
    private readonly List<IceCreamFlavor> _flavors;

    [Display(Name = "Favorite Flavor")]
    public int SelectedFlavorId { get; set; }

    public IEnumerable<SelectListItem> FlavorItems
    {
        get { return new SelectList(_flavors, "Id", "Name");}
    }
}

What is the proper way to set _flavors?  It is private readonly.  Is there any reason for this?  Some feature of MVC to populate it?

I can obviously make it public or private with a constructor but I am wondering why Scott Allen set it this way.  Is there some logic to it?


问:
Filter rows based on uniqueness of a column
I'm sure I'm overthinking a problem again. All I'm trying to achieve is a result array that only contains rows where the data in first column is unique and sorted.

So using an example array (say sheet 'DB')

```<code>A     B     C     D
Me    Pink  Car   Top
Me    Blue  Bike  Middle
You   Pink  Car   Bottom
They  Pink  Bike  Bottom
You   Blue  Bike  Top
Them  Red   Car   Middle
Them  Blue  Car   Top
Me          Bike  Middle
You         Car
Us                Top
</code>```

Results in another sheet (say 'Results')

```<code>A     B     C     D
Me    Pink  Car   Top
Them  Red   Car   Middle
They  Pink  Bike  Bottom
Us                Top
You   Pink  Car   Bottom
</code>```

Ideally a single formula will go in 'Results!A1'.

Ignoring the SORT element for the moment, this sledgehammer only works for small arrays

```<code>=filter(A1:D13,mmult((A1:D13=transpose(A1:D13))*(row(A1:D13)>=transpose(row(A1:D13))),row(A1:D13)^0)=1)
</code>```

but my DB table is 25,000+ rows (10+ wide) so seems to break the GS 2m cell limit (>matrix 1414*1414) - large arrays produce a 'Column expected 21,414, actual column 1' type error - rather than a more useful 'You broke a limit!'

Note. The above solution works best so far because the originating data is not sorted.

I've tried QUERY() but again, breaks on the UNIQUE() element.

```<code>=Query('DB!A2:I, "select * where Col1 matches '"&UNIQUE(DB!A2:A)&"'",0))
</code>```

error 'No Col1/A'

UNIQUE(...) works fine in terms of stripping duplicates in the key column but how do I then express the rest of the row to each unique entry?

UNIQUE({A1:A;FILTER({A1:D...)}) results in 'No values found'

I was hoping a simple SORT(UNIQUE(...)) would be the ideal solution but alas it seems I'm looking in the wrong haystack.

I've also tried the following structures but either the length of time taken to process or my syntax has crippled any result.

The resulting array btw will just be a helper array for a more rational user sheet that will use IMPORTRANGE() on the result above.

thx to Yogi-Anand for the first solution.

答:
This formula accomplishes this:

```<code>=ARRAYFORMULA(if(istext(SORT(UNIQUE(Sheet3!A:A))),arrayformula(VLOOKUP(SORT(UNIQUE(Sheet3!A:A)),Sheet3!A:D,{1,2,3,4},false)),))
</code>```

Body:
I'm sure I'm overthinking a problem again. All I'm trying to achieve is a result array that only contains rows where the data in first column is unique and sorted.

So using an example array (say sheet 'DB')

A     B     C     D
Me    Pink  Car   Top
Me    Blue  Bike  Middle
You   Pink  Car   Bottom
They  Pink  Bike  Bottom
You   Blue  Bike  Top
Them  Red   Car   Middle
Them  Blue  Car   Top
Me          Bike  Middle
You         Car
Us                Top

Results in another sheet (say 'Results')

A     B     C     D
Me    Pink  Car   Top
Them  Red   Car   Middle
They  Pink  Bike  Bottom
Us                Top
You   Pink  Car   Bottom

Ideally a single formula will go in 'Results!A1'.

Ignoring the SORT element for the moment, this sledgehammer only works for small arrays

=filter(A1:D13,mmult((A1:D13=transpose(A1:D13))*(row(A1:D13)>=transpose(row(A1:D13))),row(A1:D13)^0)=1)

but my DB table is 25,000+ rows (10+ wide) so seems to break the GS 2m cell limit (>matrix 1414*1414) - large arrays produce a 'Column expected 21,414, actual column 1' type error - rather than a more useful 'You broke a limit!'

Note. The above solution works best so far because the originating data is not sorted.

I've tried QUERY() but again, breaks on the UNIQUE() element.

=Query('DB!A2:I, "select * where Col1 matches '"&UNIQUE(DB!A2:A)&"'",0))

error 'No Col1/A'

UNIQUE(...) works fine in terms of stripping duplicates in the key column but how do I then express the rest of the row to each unique entry?

UNIQUE({A1:A;FILTER({A1:D...)}) results in 'No values found'

I was hoping a simple SORT(UNIQUE(...)) would be the ideal solution but alas it seems I'm looking in the wrong haystack.

I've also tried the following structures but either the length of time taken to process or my syntax has crippled any result.

The resulting array btw will just be a helper array for a more rational user sheet that will use IMPORTRANGE() on the result above.

thx to Yogi-Anand for the first solution.

Body:
This formula accomplishes this:

=ARRAYFORMULA(if(istext(SORT(UNIQUE(Sheet3!A:A))),arrayformula(VLOOKUP(SORT(UNIQUE(Sheet3!A:A)),Sheet3!A:D,{1,2,3,4},false)),))


问:
Python 3.5 typing custom type
I have a method that calls an API and that API responds with a dict which contains two keys: all, owner (it's a Github api actually that gets the commit activity for a given repository)

I'm playing with the newly integrated typing module/system into Python 3.5 and I want to know if it's possible to create a custom type that actually specifies that the Dict returned should contain these two keys (all and owner)

Here's what I have so far:

TypeRepositoryCommitActivity = Dict[str, List]

These are obviously primitive types assembled together so how do I go enforcing a little deeper?

答:
Until this becomes available in typing, you can use mypy extended features:

```<code>from mypy_extensions import TypedDict

TypeRepoCommits = TypedDict('TypeRepoCommits', {'all': str, 'owner': str})

x: TypeRepoCommits = {'all': 'a', 'owner': 'b'} # pass type check
y: TypeRepoCommits = {'all': 1, 'owner': 'b'} # fail type check
</code>```

Title: Python 3.5 typing custom type

Body:
Until this becomes available in typing, you can use mypy extended features:

from mypy_extensions import TypedDict

TypeRepoCommits = TypedDict('TypeRepoCommits', {'all': str, 'owner': str})

x: TypeRepoCommits = {'all': 'a', 'owner': 'b'} # pass type check
y: TypeRepoCommits = {'all': 1, 'owner': 'b'} # fail type check


问:
Casting to base class without knowing name of class in C#
I've been implementing visitor pattern in C#. What I have is:

Hierarchy of classes:

```<code>public class A {
  public virtual void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
}

public class B : A {
  public override void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
}
</code>```

The Visitor class:

```<code>public abstract class Visitor {
  public virtual void Visit(A item) {
    //...
  }
  public virtual void Visit(B item) {
    Visit(item as A);
  }
}
</code>```

Concrete Visitor class:

```<code>public class ConcreteVisitor : Visitor {
  public override void Visit(B item) {
    // do something
    // and call Visit for base class
    Visit(item as A); // I need to know type A.
  }
}
</code>```

Is there any way to call Visit for item's base class without knowing its direct base class name? I would like to be able to change hierarchy without changing ConcreteVisitor class.

Thank you

答:
Make it the responsibility of A. With a method for example:

```<code>public class A {
  public virtual void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
  public A AsBase()
  {
     return this;
  }
}
</code>```

and

```<code>public class ConcreteVisitor : Visitor {
  public override void Visit(B item) {
    // do something
    // and call Visit for base class
    Visit(item.AsBase()); // convert to base type
  }
}
</code>```

PS: your design is maybe a bit odd, but I was challenged by your question ;)

Body:
I've been implementing visitor pattern in C#. What I have is:

Hierarchy of classes:

public class A {
  public virtual void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
}

public class B : A {
  public override void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
}

The Visitor class:

public abstract class Visitor {
  public virtual void Visit(A item) {
    //...
  }
  public virtual void Visit(B item) {
    Visit(item as A);
  }
}

Concrete Visitor class:

public class ConcreteVisitor : Visitor {
  public override void Visit(B item) {
    // do something
    // and call Visit for base class
    Visit(item as A); // I need to know type A.
  }
}

Is there any way to call Visit for item's base class without knowing its direct base class name? I would like to be able to change hierarchy without changing ConcreteVisitor class.

Thank you

Body:
Make it the responsibility of A. With a method for example:

public class A {
  public virtual void Accept(Visitor visitor)
  {
    visitor.Visit(this);
  }
  public A AsBase()
  {
     return this;
  }
}

and

public class ConcreteVisitor : Visitor {
  public override void Visit(B item) {
    // do something
    // and call Visit for base class
    Visit(item.AsBase()); // convert to base type
  }
}

PS: your design is maybe a bit odd, but I was challenged by your question ;)


问:
Input specific string at last - c program
user input:

string[0]="My Address Street";

string[1]="My Street Address";

string[2]="Street Address";

```<code>strstr(string[i]," Street")
// return 0 for string[2], because there is no whitespace before `Street` word
</code>```

I want to make user input Street only at last string, not in the middle or first string use strstr();.

some trick using reverse string, then count until meet space, then reverse back to normal and substring [ ( string length - count ), (string length) ]. And then compare it with the required input ('Street' at the end of inputted string). if match -> pass or looping until match.

答:
thanks, i use this.</p>

```<code>char address[50];
do{
    printf("> ");
    scanf("%[^\n]",address);
}while(strstr(address," Street")==0 || strstr(address,"Street ")!=0);
/* user input:
> Orchard Road
> Street
> Street Orchad Road
> Orchad Street Road
> Orchad Road, Street
*/
</code>```

Body:
user input:

string[0]="My Address Street";

string[1]="My Street Address";

string[2]="Street Address";

strstr(string[i]," Street")
// return 0 for string[2], because there is no whitespace before `Street` word

I want to make user input Street only at last string, not in the middle or first string use strstr();.

some trick using reverse string, then count until meet space, then reverse back to normal and substring [ ( string length - count ), (string length) ]. And then compare it with the required input ('Street' at the end of inputted string). if match -> pass or looping until match.

Body:
thanks, i use this.

char address[50];
do{
    printf("> ");
    scanf("%[^\n]",address);
}while(strstr(address," Street")==0 || strstr(address,"Street ")!=0);
/* user input:
> Orchard Road
> Street
> Street Orchad Road
> Orchad Street Road
> Orchad Road, Street
*/


问:
'Acces denied' error with Visual Studio 2017
I get some errors when I build my code in Visual Studio 10, and I don't know how I can solve it. This is a error message that I got:

```<code>1>------ Rebuild All started: Project: Win32Project34, Configuration: Debug Win32 ------
1>C:\Program Files\Microsoft Visual Studio\2017\Professional\Common7\IDE\VC\VCTargets\Microsoft.CppClean.targets(76,5): warning : Access to the path 'c:\users\recht\documents\visual studio 2017\projects\win32project34\debug\win32project34.exe' is denied.
1>einde5.cpp
1>c:\users\recht\desktop\einde5.cpp(37): warning C4302: 'type cast': truncation from 'LPWSTR' to 'WORD'
1>c:\users\recht\desktop\einde5.cpp(42): warning C4302: 'type cast': truncation from 'LPWSTR' to 'WORD'
1>LINK : fatal error LNK1104: cannot open file 'c:\users\recht\documents\visual studio 2017\Projects\Win32Project34\Debug\Win32Project34.exe'
1>Done building project "Win32Project34.vcxproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
</code>```

Does someone know what the problem is, and how I can solve it?

答: Try running Visual Studios as an administrator (Right click, run as administrator on program link).</p>

Body:
I get some errors when I build my code in Visual Studio 10, and I don't know how I can solve it. This is a error message that I got:

1>------ Rebuild All started: Project: Win32Project34, Configuration: Debug Win32 ------
1>C:\Program Files\Microsoft Visual Studio\2017\Professional\Common7\IDE\VC\VCTargets\Microsoft.CppClean.targets(76,5): warning : Access to the path 'c:\users\recht\documents\visual studio 2017\projects\win32project34\debug\win32project34.exe' is denied.
1>einde5.cpp
1>c:\users\recht\desktop\einde5.cpp(37): warning C4302: 'type cast': truncation from 'LPWSTR' to 'WORD'
1>c:\users\recht\desktop\einde5.cpp(42): warning C4302: 'type cast': truncation from 'LPWSTR' to 'WORD'
1>LINK : fatal error LNK1104: cannot open file 'c:\users\recht\documents\visual studio 2017\Projects\Win32Project34\Debug\Win32Project34.exe'
1>Done building project "Win32Project34.vcxproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Does someone know what the problem is, and how I can solve it?


问:
Looking for a short term fix for limiting record display number without :limit => 10
I am wondering if there is a way to complete this hack that I am trying to do with my Ruby on Rails app. I'm having trouble with some associations and I can't find the solution. You can see that question here.

In the mean time I am wanting to limit the display of records to a number like 10 but I don't want to do it in the controller through the :limit => 10 manner because I need to loop through all the records. I'm not even sure if this is possible but thought I would ask.

My view code is:

```<code><% @comments.each do |comment| %>
  <% if comment.workout.user_id == current_user.id %><br/>
    <%= link_to (comment.user.username), comment.user %> <br/>
    <%= time_ago_in_words(comment.created_at) %> <br/>
    <%= link_to (comment.workout.title), comment.workout %><br/>
    <%= sanitize(simple_format(comment.body), :tags => %w(p)) %>
  <% end %>
<% end %>
</code>```

My controller is simply calling

```<code>@comments = Comment.all(:order => "created_at DESC")
</code>```

答:
I would do all that in the controller. Views shouldn't be doing that logic. You say you don't want to only limit to 10, because you want all and do some filter. You can just:</p>

```<code>@comments = Comment.all(:joins => :workout, :conditions => {:workouts =>{:user_id => current_user.id}}, :order => "created_at DESC", :limit => 10)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am wondering if there is a way to complete this hack that I am trying to do with my Ruby on Rails app. I'm having trouble with some associations and I can't find the solution. You can see that question here.

In the mean time I am wanting to limit the display of records to a number like 10 but I don't want to do it in the controller through the :limit => 10 manner because I need to loop through all the records. I'm not even sure if this is possible but thought I would ask.

My view code is:

<% @comments.each do |comment| %>
  <% if comment.workout.user_id == current_user.id %>

    <%= link_to (comment.user.username), comment.user %>

    <%= time_ago_in_words(comment.created_at) %>

    <%= link_to (comment.workout.title), comment.workout %>

    <%= sanitize(simple_format(comment.body), :tags => %w(p)) %>
  <% end %>
<% end %>

My controller is simply calling

@comments = Comment.all(:order => "created_at DESC")

Body:
I would do all that in the controller. Views shouldn't be doing that logic. You say you don't want to only limit to 10, because you want all and do some filter. You can just:

@comments = Comment.all(:joins => :workout, :conditions => {:workouts =>{:user_id => current_user.id}}, :order => "created_at DESC", :limit => 10)


问:
Spinning Image in Windows Forms (C#)
I'm working in a music player, where I want the album art of the current song to be spinning in a circular picture box, just a vynil turntable.

I already have the circular picturebox, I made one attempt to make it spin, but it is spinning roughly, it doesn't look smooth. So I don't know if I am using the wrong parameters or if something is wrong in my code.

Used code from here:
Rotating image around center C#

Hope you can help. Thanks in advance.

答:
WinForms graphical API is very limited and thats why the whole platform is obsolete. WPF is more capable for graphical presentation because there is a hardware acceleration and DirectX behind that.
My opinion if you are creating entertaining solutions use at minimum WPF. If your aim is purely business then WinForms is more than enough.</p>

Title: Spinning Image in Windows Forms (C#)


问:
List Comprehension with Instances
I am trying out list comprehension and I am stuck with the below problem.

```<code>class Programmer():
    def __init__(self, name, years_at_umich=1, programs_written=0):
        self.name = name
        self.seniority = years_at_umich
        self.bonus_points = random.randrange(1000)
        self.programs_written = programs_written

    def shout(self, phrase_to_shout):
        print phrase_to_shout  # print is for ppl!

    def __str__(self):
        return "My name is {}, and I've been at UMich for about {} years.".format(self.name,self.seniority)

    def year_at_umich(self):
        return self.seniority

prog_tups = zip(names, seniority,programs_written)
print prog_tups
</code>```

prints output

```<code>[('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
</code>```

I am trying to use list Comprehension to create a list of Programmer instances out of the prog_tups list from above and save that list in the variable programmers.

My current code is below, I am not getting a traceback, but nothing happens:

```<code>programmers = [item for item in prog_tups]
</code>```

答: If I understand your question correctly, you want to have a list of only the names. Seeing as the names are the first element in the tuples, a simple solution would be programmers = [item[0] for item in prog_tuples] to obtain only the names. To see if this works, simply print() it.

Title: List Comprehension with Instances

Body:
I am trying out list comprehension and I am stuck with the below problem.

class Programmer():
    def __init__(self, name, years_at_umich=1, programs_written=0):
        self.name = name
        self.seniority = years_at_umich
        self.bonus_points = random.randrange(1000)
        self.programs_written = programs_written

    def shout(self, phrase_to_shout):
        print phrase_to_shout  # print is for ppl!

    def __str__(self):
        return "My name is {}, and I've been at UMich for about {} years.".format(self.name,self.seniority)

    def year_at_umich(self):
        return self.seniority

prog_tups = zip(names, seniority,programs_written)
print prog_tups

prints output

[('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]

I am trying to use list Comprehension to create a list of Programmer instances out of the prog_tups list from above and save that list in the variable programmers.

My current code is below, I am not getting a traceback, but nothing happens:

programmers = [item for item in prog_tups]


问:
Prelude.head: empty list in if statement
I'm writing a function and it throws Prelude.head empty list if I use the variable newBoard where I have sortBoard in the if-else it throws this error. If I use the original board character it doesn't throw this error.

```<code>foo :: [[Char]] -> [(Int, Int)] -> [(Int, (Int, Int))] -> Int -> [(Int,Int)]-> [Int]-> [[Char]]
foo [] _ _ _ _ _ = []
foo board [] _ _ _ [] = board
foo board spot array number startArray move = nextStep
    where
        newBoard        = set board (head spot) ('1')
        tailSpot        = tail spot
        nextStep =
            if tailSpot == []
                then if (tail move) == []
                        then newBoard
                    else sortBoard newBoard array 1 [] (tail move)
            else (foo newBoard tailSpot array 1 [] move)
</code>```

For explination on this code, I have a game board and need to enter '1' in certain spots which are given by the variable spot. If I have gone through all the spots(tailSpot) and there are no more sections I need to change(move) it should just return the new board. If I still have sections I need to change, I exit this function and go back to finding the spots in that section so I can come back and switch them. If I still have a section and spots left, I keep going through this function until all spots are changed.

答:
Problem is here:

```<code>newBoard        = set board (head spot) ('1')
</code>```

You're calling head on spot list. But spot may be empty list. Your pattern matching is non-exhaustive enough. Here foo board [] _ _ _ [] = board you check that spot and move both empty simultaneosly. While one of them may be empty while the other one has at least one element.

Try to structure your code in more modular manner making imposible states unrepresentable. Most likely your code can be refactored to avoid situations when only one list is empty, if one one of two can happen: both lists are empty or both has at least one element.

Body:
I'm writing a function and it throws Prelude.head empty list if I use the variable newBoard where I have sortBoard in the if-else it throws this error. If I use the original board character it doesn't throw this error.

foo :: [[Char]] -> [(Int, Int)] -> [(Int, (Int, Int))] -> Int -> [(Int,Int)]-> [Int]-> [[Char]]
foo [] _ _ _ _ _ = []
foo board [] _ _ _ [] = board
foo board spot array number startArray move = nextStep
    where
        newBoard        = set board (head spot) ('1')
        tailSpot        = tail spot
        nextStep =
            if tailSpot == []
                then if (tail move) == []
                        then newBoard
                    else sortBoard newBoard array 1 [] (tail move)
            else (foo newBoard tailSpot array 1 [] move)

For explination on this code, I have a game board and need to enter '1' in certain spots which are given by the variable spot. If I have gone through all the spots(tailSpot) and there are no more sections I need to change(move) it should just return the new board. If I still have sections I need to change, I exit this function and go back to finding the spots in that section so I can come back and switch them. If I still have a section and spots left, I keep going through this function until all spots are changed.

Body:
Problem is here:

newBoard        = set board (head spot) ('1')

You're calling head on spot list. But spot may be empty list. Your pattern matching is non-exhaustive enough. Here foo board [] _ _ _ [] = board you check that spot and move both empty simultaneosly. While one of them may be empty while the other one has at least one element.

Try to structure your code in more modular manner making imposible states unrepresentable. Most likely your code can be refactored to avoid situations when only one list is empty, if one one of two can happen: both lists are empty or both has at least one element.


问:
Is C strongly typed?
To quote Wikipedia:

Two commonly used languages that
  support many kinds of implicit
  conversion are C and C++, and it is
  sometimes claimed that these are
  weakly typed languages. However,
  others argue that these languages
  place enough restrictions on how
  operands of different types can be
  mixed, that the two should be regarded
  as strongly typed languages.

Is there a more definitive answer?

答:
Plenty of good answers here. I want to bring up an important point from Real World Haskell:

It is useful to be aware that many language communities have their own definitions of a
  “strong type”. Nevertheless, we will speak briefly and in broad terms about the notion of strength in type systems.

(snip)

The fireworks around type systems have their roots in ordinary English, where people attach notions of value to the words “weak” and “strong”: we usually think of strength as better than weakness. Many more programmers speak plain English than academic jargon, and quite often academics really are throwing brickbats at whatever type system doesn't suit their fancy. The result is often that popular Internet pastime, a flame war.

So, look at the answers about C and C++, but remember that 'strong' and 'weak' do not map to 'good' and 'bad'.

OwnerDisplayName: Sydius

Title: Is C strongly typed?

LastEditorDisplayName: Sydius

OwnerDisplayName: slim


问:
maintain different versions of the code simultaneously using git
I got a code that I'm required to optimize. I would like to maintain a set of versions of the code (each version can be described as a composition of some features, optimizations) simultaneously. Eventually, I'll decide which version is the best one. I do not want to merge these versions into fewer versions. However, I would like to be able to make a (minor) modification to a (big) source file which may divert across the versions and I want this modification to write through more than one (possibly all) versions. How can I achieve that with git?

For example let us consider 3 versions: v1, v2, v3 and source code file source.cpp which has lots of code that is different across all versions but class A method aMethod() is identical. I would like to update the method and write the update to versions v1 and v2 only.

How can I do that?

If I modify source.cpp, for example, in v1, than merge it to v2 there will be a merge conflict (because source.cpp is different in v1, v2). Is there any way to avoid the conflict? If not, what is the best way to deal with the merge conflict int this case?
By the way, I don't want to increase code granularity so that the aMethod() will be placed in a dedicated file, because there is already lots of source code written and there will be too much overhead for doing this for any such modification that I describe.

Thanks in advance,

Daniel

答:
It would be ok to test the various alternatives in a single source file.

As you noted, git merging is designed to make versions converge, which is particularly useful when distributed teams want to work without stepping on each other toes.

It doesn't help you keep files distinct. cherry-pick can fill the gap, but unlike the darcs equivalent it doesn't use the history, and may not work in many cases. Introducing your minor changes into topic branches could work, but you would need to make them dependent on an early, common revision and only merge from them, not into them.

Since you control everything, you can test diverging algorithms while keeping them compatible and in sync, and you don't need multiple branches.


问:
Visual Studio Code Formatting fail on save
I've started learning React Native.

I'm using Visual Studio Code as my editor.

I've set up the boiler plate and started the app. But whenever I change a .js file and hit save, VSCode is messing up all the formatting.

I thought I could sort this in the settings.json file but after googling for a while and playing around I can't find the correct setting.

Is this a bug or am I doing something wrong?

Setting file is default one:

UPDATE: I re-installed vscode. Then set up a basic js file with a react native tag and a html tag. I added in:

```<code>"editor.formatOnSave": false,
"javascript.format.enable": false
</code>```

To my settings.json file and the problem still occurs:

The problem is having tags in a js file, I just don't know how to tell vscode to ignore them?

答:
I found out what this was by looking though the extensions. Thanks to @wgj for the hint.

Turns out it was the JS-CSS-HTML formatter. I looked through the instructions and have removed the auto save for now. I'll have to work out the specific settings for this.

It uses js-beautify so if anyone knows the settings I should be looking at would be much appreciated.

Body:
I've started learning React Native.

I'm using Visual Studio Code as my editor.

I've set up the boiler plate and started the app. But whenever I change a .js file and hit save, VSCode is messing up all the formatting.

I thought I could sort this in the settings.json file but after googling for a while and playing around I can't find the correct setting.

Is this a bug or am I doing something wrong?

Setting file is default one:

UPDATE: I re-installed vscode. Then set up a basic js file with a react native tag and a html tag. I added in:

"editor.formatOnSave": false,
"javascript.format.enable": false

To my settings.json file and the problem still occurs:

The problem is having tags in a js file, I just don't know how to tell vscode to ignore them?


问:
A segment of code I made in Python 3 does not work
The following segment of code does not work properly.

Error:

'<' not supported between instances of 'str' and 'int'

Code:

```<code>name = input()
age = input()
if name == ('alice'):
    print('hello alice')
elif age < 12:
    print('you arent alice, kiddo')
elif age > 2000:
    print ('now thats just crazy you cant be that old')
elif age > 70:
    print ('are too old to be alice')
</code>```

PS: I'm new to programming

答:
You should explicitly cast the result of the second line, as in</p>

```<code>age = int(input())
</code>```

Body:
The following segment of code does not work properly.

Error:

'<' not supported between instances of 'str' and 'int'

Code:

name = input()
age = input()
if name == ('alice'):
    print('hello alice')
elif age < 12:
    print('you arent alice, kiddo')
elif age > 2000:
    print ('now thats just crazy you cant be that old')
elif age > 70:
    print ('are too old to be alice')

PS: I'm new to programming

Body:
You should explicitly cast the result of the second line, as in

age = int(input())


问:
Codeigniter Youtube videos is not coming
I try to show a youtube video in my cms project using codeigniter. But its not working.. I insert the youtube url in one table path in my mysql database and i just call that url using codeigniter view area under iframe tag.. But its not showing i check it in the Browser inspect the video url is showing but below of the  tag  this is generated automatically. Can any one help me..

This is my view code..

```<code><div class="container">
        <div class="row">
            <?php foreach($advertisement as $ad) { ?>
          <table>
    <td>
  <iframe src="<?php echo $ad->url?>"
   width="560" height="315" frameborder="0" ></iframe>
   </td>
   </table>

            <?php
            } ?>
     </div>
</div>
</code>```

This is my Controller Code

```<code>  public function advertisement(){
        $data['advertisement'] = $this->modelHome->populateAds();

        $this->load->view('layouts/head',$data);
        $this->load->view('commercial',$data);
        $this->load->view('layouts/footer');
    }
</code>```

This is my modal code

```<code> public function populateAds(){
        $this->db->select('*');
        $this->db->from('advertisement');
        $this->db->where('status','approved');
        $this->db->order_by('id','DESC');
        $query=$this->db->get();
         if ($query->num_rows() > 0) {
            return $query->result();
        }
     }
</code>```

This is my Table

答:
Your code looks ok.
Problem is with your data in database. If you look at the only record you have in your table, it has status approve not approved. And your model is selecting only rows with status approved.

Body:
I try to show a youtube video in my cms project using codeigniter. But its not working.. I insert the youtube url in one table path in my mysql database and i just call that url using codeigniter view area under iframe tag.. But its not showing i check it in the Browser inspect the video url is showing but below of the  tag  this is generated automatically. Can any one help me..

This is my view code..

            <?php foreach($advertisement as $ad) { ?>

  <iframe src="<?php echo $ad->url?>"
   width="560" height="315" frameborder="0" >

            <?php
            } ?>

This is my Controller Code

  public function advertisement(){
        $data['advertisement'] = $this->modelHome->populateAds();

        $this->load->view('layouts/head',$data);
        $this->load->view('commercial',$data);
        $this->load->view('layouts/footer');
    }

This is my modal code

 public function populateAds(){
        $this->db->select('*');
        $this->db->from('advertisement');
        $this->db->where('status','approved');
        $this->db->order_by('id','DESC');
        $query=$this->db->get();
         if ($query->num_rows() > 0) {
            return $query->result();
        }
     }

This is my Table


问:
Android - Camera API takes too much time to capture and save image
I am trying to use Camera API for my app. When I click take photo button, the UI hangs for about 10 seconds before responding further.

I found a post on SO here, but the solution wasn't much specific. I think it is a problem of multi-threading. I am a beginner in android development and not proficient with multi-threading.

UploadPrescription.java :

```<code>package com.example.ayusch.medomo;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.ShareCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.util.Size;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class UploadPrescription extends Fragment {
    private static final int REQUEST_EXTERNAL_STORAGE_PERMISSION = 2;
    private Camera mCamera = null;
    private CameraPreview mCameraPreview;
    private final int REQUEST_CAMERA_PERMISSION = 1;
    private FrameLayout preview;
    private File pictureFile;
    private FileOutputStream fos;
    private byte[] byteArray;

    public UploadPrescription() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_upload_prescription, container, false);
        preview = (FrameLayout) root.findViewById(R.id.camera_preview);

        setPreview();

        Button captureButton = (Button) root.findViewById(R.id.button_capture);
        captureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("ayusch", "inside on click");
                mCamera.takePicture(null, null, mPicture);
            }

        });
        return root;
    }

    private void setPreview() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                setup();
            } else {

                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {

                    Toast.makeText(getContext(), "Permission needed to use camera", Toast.LENGTH_LONG).show();
                }

                requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
            }
        } else {
            setup();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setup();
            } else {
                Toast.makeText(getContext(), "Camera Permission not granted", Toast.LENGTH_LONG).show();
                return;
            }
        } else if (requestCode == REQUEST_EXTERNAL_STORAGE_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                proceedtowrite();
            } else {
                Toast.makeText(getContext(), "Storage permission not granted", Toast.LENGTH_LONG).show();
                return;
            }
        }
    }

    public void setup() {

        mCamera = getCameraInstance();
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.set("jpeg-quality", 70);
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        parameters.setPictureFormat(ImageFormat.JPEG);
        List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
        Camera.Size size = sizes.get(Integer.valueOf((sizes.size() - 1) / 2)); //choose a medium resolution
        parameters.setPictureSize(size.width, size.height);
        mCamera.setParameters(parameters);
        mCameraPreview = new CameraPreview(getContext(), mCamera);
        preview.addView(mCameraPreview);
    }

    private Camera getCameraInstance() {

        Camera camera = null;
        try {
            camera = Camera.open(0);

        } catch (Exception e) {
            e.printStackTrace();
            // cannot get camera or does not exist
        }
        return camera;
    }

    Camera.PictureCallback mPicture = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Log.i("ayusch", "inside onPictureTaken");

            pictureFile = getOutputMediaFile();

            if (pictureFile == null) {
                Log.i("ayusch", "Null Picture file, returning...");
                return;
            }
            try {
                fos = new FileOutputStream(pictureFile);

                ////////////////////////////////////
                Bitmap realImage = BitmapFactory.decodeByteArray(data, 0, data.length);

                ExifInterface exif = new ExifInterface(pictureFile.toString());

                Log.d("ayusch", exif.getAttribute(ExifInterface.TAG_ORIENTATION));
                if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("6")) {
                    realImage = rotate(realImage, 90);
                } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("8")) {
                    realImage = rotate(realImage, 270);
                } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("3")) {
                    realImage = rotate(realImage, 180);
                } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("0")) {
                    realImage = rotate(realImage, 90);
                }
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                realImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byteArray = stream.toByteArray();

                ////////////////////////////////////
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        proceedtowrite();
                    } else {

                        if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                            Toast.makeText(getContext(), "Permission needed to store and upload Prescription", Toast.LENGTH_LONG).show();
                        }

                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE_PERMISSION);
                    }
                } else {
                    proceedtowrite();
                }
            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }
    };

    public void proceedtowrite() {
        try {
            fos.write(byteArray);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent i = new Intent(getActivity(), PrescriptionUpload.class);
        i.putExtra("prescription", pictureFile);
        startActivity(new Intent(i));
    }

    public static Bitmap rotate(Bitmap bitmap, int degree) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Matrix mtx = new Matrix();
        //       mtx.postRotate(degree);
        mtx.setRotate(degree);

        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
    }

    private static File getOutputMediaFile() {
        Log.i("ayusch", "Getting output media file");
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraApp");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
        Log.i("ayusch", "Filename = " + mediaFile);
        return mediaFile;
    }

    @Override
    public void onPause() {

        super.onPause();
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCameraPreview.getHolder().removeCallback(mCameraPreview);
            mCamera.stopPreview();
            mCamera.release();

        }
    }

    @Override
    public void onResume() {

        super.onResume();
        try {
            mCameraPreview.getHolder().removeCallback(mCameraPreview);
            setPreview();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
</code>```

CameraPreview.java :

```<code>package com.example.ayusch.medomo;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

/**
 * Created by Ayusch on 09-Feb-17.
 */
public class CameraPreview extends SurfaceView implements
        SurfaceHolder.Callback {
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;

    // Constructor that obtains context and camera
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
        super(context);

        this.mCamera = camera;
        this.mSurfaceHolder = this.getHolder();
        this.mSurfaceHolder.addCallback(this);
        this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {

        try {

            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.setDisplayOrientation(90);
            mCamera.startPreview();
        } catch (IOException e) {
            // left blank for now
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        Log.i("ayusch", "Inside surfaceDestroyed");
        mCamera.stopPreview();
        mCamera.release();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
                               int width, int height) {

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (Exception e) {
            // intentionally left blank for a test
        }
    }
}
</code>```

MainActivity.java :

```<code>package com.example.ayusch.medomo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CAMERA_PERMISSION = 1;
    Toolbar toolbar;
    TabLayout tabLayout;
    ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragments(new UploadPrescription(), "Upload Prescription");
        viewPagerAdapter.addFragments(new OrderByName(), "Enter Medicine Name");
        viewPagerAdapter.addFragments(new Contact(), "Contact Us");
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);

    }

}
</code>```

Also, during the hang time if I press the button again, app crashes :

```<code>02-10 19:57:31.481 966-966/com.example.ayusch.medomo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.example.ayusch.medomo, PID: 966
                                                                       java.lang.RuntimeException: Camera is being used after Camera.release() was called
                                                                           at android.hardware.Camera.native_takePicture(Native Method)
                                                                           at android.hardware.Camera.takePicture(Camera.java:1523)
                                                                           at android.hardware.Camera.takePicture(Camera.java:1468)
                                                                           at com.example.ayusch.medomo.UploadPrescription$1.onClick(UploadPrescription.java:73)
                                                                           at android.view.View.performClick(View.java:5714)
                                                                           at android.widget.TextView.performClick(TextView.java:10926)
                                                                           at android.view.View$PerformClick.run(View.java:22589)
                                                                           at android.os.Handler.handleCallback(Handler.java:739)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:7325)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

It is due to the line mCamera.takePicture(null, null, mPicture); in the onClick method of UploadPrescription.java

I have been trying to get my head around it since 2 days without any success. Please Help !!

Thanks in advance

答:
```<code>     ByteArrayOutputStream stream = new ByteArrayOutputStream();
     realImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
     byteArray = stream.toByteArray();
</code>```

Bitmap#compress is extremely inefficient for PNG format (lack of hardware acceleration etc). Try either resizing the bitmap prior to saving, compressing to JPEG or dumping raw bitmap using native io.

Body:
I am trying to use Camera API for my app. When I click take photo button, the UI hangs for about 10 seconds before responding further.

I found a post on SO here, but the solution wasn't much specific. I think it is a problem of multi-threading. I am a beginner in android development and not proficient with multi-threading.

UploadPrescription.java :

package com.example.ayusch.medomo;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.ShareCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.util.Size;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class UploadPrescription extends Fragment {
    private static final int REQUEST_EXTERNAL_STORAGE_PERMISSION = 2;
    private Camera mCamera = null;
    private CameraPreview mCameraPreview;
    private final int REQUEST_CAMERA_PERMISSION = 1;
    private FrameLayout preview;
    private File pictureFile;
    private FileOutputStream fos;
    private byte[] byteArray;

    public UploadPrescription() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_upload_prescription, container, false);
        preview = (FrameLayout) root.findViewById(R.id.camera_preview);

        setPreview();

        Button captureButton = (Button) root.findViewById(R.id.button_capture);
        captureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("ayusch", "inside on click");
                mCamera.takePicture(null, null, mPicture);
            }

        });
        return root;
    }

    private void setPreview() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                setup();
            } else {

                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {

                    Toast.makeText(getContext(), "Permission needed to use camera", Toast.LENGTH_LONG).show();
                }

                requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
            }
        } else {
            setup();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setup();
            } else {
                Toast.makeText(getContext(), "Camera Permission not granted", Toast.LENGTH_LONG).show();
                return;
            }
        } else if (requestCode == REQUEST_EXTERNAL_STORAGE_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                proceedtowrite();
            } else {
                Toast.makeText(getContext(), "Storage permission not granted", Toast.LENGTH_LONG).show();
                return;
            }
        }
    }

    public void setup() {

        mCamera = getCameraInstance();
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.set("jpeg-quality", 70);
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        parameters.setPictureFormat(ImageFormat.JPEG);
        List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
        Camera.Size size = sizes.get(Integer.valueOf((sizes.size() - 1) / 2)); //choose a medium resolution
        parameters.setPictureSize(size.width, size.height);
        mCamera.setParameters(parameters);
        mCameraPreview = new CameraPreview(getContext(), mCamera);
        preview.addView(mCameraPreview);
    }

    private Camera getCameraInstance() {

        Camera camera = null;
        try {
            camera = Camera.open(0);

        } catch (Exception e) {
            e.printStackTrace();
            // cannot get camera or does not exist
        }
        return camera;
    }

    Camera.PictureCallback mPicture = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Log.i("ayusch", "inside onPictureTaken");

            pictureFile = getOutputMediaFile();

            if (pictureFile == null) {
                Log.i("ayusch", "Null Picture file, returning...");
                return;
            }
            try {
                fos = new FileOutputStream(pictureFile);

                ////////////////////////////////////
                Bitmap realImage = BitmapFactory.decodeByteArray(data, 0, data.length);

                ExifInterface exif = new ExifInterface(pictureFile.toString());

                Log.d("ayusch", exif.getAttribute(ExifInterface.TAG_ORIENTATION));
                if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("6")) {
                    realImage = rotate(realImage, 90);
                } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("8")) {
                    realImage = rotate(realImage, 270);
                } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("3")) {
                    realImage = rotate(realImage, 180);
                } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("0")) {
                    realImage = rotate(realImage, 90);
                }
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                realImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byteArray = stream.toByteArray();

                ////////////////////////////////////
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        proceedtowrite();
                    } else {

                        if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                            Toast.makeText(getContext(), "Permission needed to store and upload Prescription", Toast.LENGTH_LONG).show();
                        }

                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE_PERMISSION);
                    }
                } else {
                    proceedtowrite();
                }
            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }
    };

    public void proceedtowrite() {
        try {
            fos.write(byteArray);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent i = new Intent(getActivity(), PrescriptionUpload.class);
        i.putExtra("prescription", pictureFile);
        startActivity(new Intent(i));
    }

    public static Bitmap rotate(Bitmap bitmap, int degree) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Matrix mtx = new Matrix();
        //       mtx.postRotate(degree);
        mtx.setRotate(degree);

        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
    }

    private static File getOutputMediaFile() {
        Log.i("ayusch", "Getting output media file");
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraApp");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
        Log.i("ayusch", "Filename = " + mediaFile);
        return mediaFile;
    }

    @Override
    public void onPause() {

        super.onPause();
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCameraPreview.getHolder().removeCallback(mCameraPreview);
            mCamera.stopPreview();
            mCamera.release();

        }
    }

    @Override
    public void onResume() {

        super.onResume();
        try {
            mCameraPreview.getHolder().removeCallback(mCameraPreview);
            setPreview();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

CameraPreview.java :

package com.example.ayusch.medomo;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

/**
 * Created by Ayusch on 09-Feb-17.
 */
public class CameraPreview extends SurfaceView implements
        SurfaceHolder.Callback {
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;

    // Constructor that obtains context and camera
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
        super(context);

        this.mCamera = camera;
        this.mSurfaceHolder = this.getHolder();
        this.mSurfaceHolder.addCallback(this);
        this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {

        try {

            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.setDisplayOrientation(90);
            mCamera.startPreview();
        } catch (IOException e) {
            // left blank for now
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        Log.i("ayusch", "Inside surfaceDestroyed");
        mCamera.stopPreview();
        mCamera.release();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
                               int width, int height) {

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (Exception e) {
            // intentionally left blank for a test
        }
    }
}

MainActivity.java :

package com.example.ayusch.medomo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CAMERA_PERMISSION = 1;
    Toolbar toolbar;
    TabLayout tabLayout;
    ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragments(new UploadPrescription(), "Upload Prescription");
        viewPagerAdapter.addFragments(new OrderByName(), "Enter Medicine Name");
        viewPagerAdapter.addFragments(new Contact(), "Contact Us");
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);

    }

}

Also, during the hang time if I press the button again, app crashes :

02-10 19:57:31.481 966-966/com.example.ayusch.medomo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.example.ayusch.medomo, PID: 966
                                                                       java.lang.RuntimeException: Camera is being used after Camera.release() was called
                                                                           at android.hardware.Camera.native_takePicture(Native Method)
                                                                           at android.hardware.Camera.takePicture(Camera.java:1523)
                                                                           at android.hardware.Camera.takePicture(Camera.java:1468)
                                                                           at com.example.ayusch.medomo.UploadPrescription$1.onClick(UploadPrescription.java:73)
                                                                           at android.view.View.performClick(View.java:5714)
                                                                           at android.widget.TextView.performClick(TextView.java:10926)
                                                                           at android.view.View$PerformClick.run(View.java:22589)
                                                                           at android.os.Handler.handleCallback(Handler.java:739)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:7325)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

It is due to the line mCamera.takePicture(null, null, mPicture); in the onClick method of UploadPrescription.java

I have been trying to get my head around it since 2 days without any success. Please Help !!

Thanks in advance

Body:
     ByteArrayOutputStream stream = new ByteArrayOutputStream();
     realImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
     byteArray = stream.toByteArray();

Bitmap#compress is extremely inefficient for PNG format (lack of hardware acceleration etc). Try either resizing the bitmap prior to saving, compressing to JPEG or dumping raw bitmap using native io.


问:
For comma-separated
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma (e.g. "Cars, Vehicle, Large Dog, Bed" but not "Cars, Vehicle, Tiger)

An example of what I mean is this, these would be valid tags:

```<code>boy, man,girl, woman,tyrannosaurus rex, lion
</code>```

And these would be invalid tags:

```<code>hat, cat, rat, c3po, @gmail
</code>```

Because there are invalid characters in "@gmail".

It should also be able to accept just a single tag, as long as the characters are alphanumeric.

答:
A separate question is being answered here. How to do the same thing but allow tags with at most two words?

```<code>/^\s*[a-z0-9]+(\s+[a-z0-9]+)?(\s*,\s*[a-z0-9]+(\s+[a-z0-9]+)?)*\s*$/
</code>```

Tested.

Title: For comma-separated

Body:
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma (e.g. "Cars, Vehicle, Large Dog, Bed" but not "Cars, Vehicle, Tiger)

An example of what I mean is this, these would be valid tags:

boy, man,girl, woman,tyrannosaurus rex, lion

And these would be invalid tags:

hat, cat, rat, c3po, @gmail

Because there are invalid characters in "@gmail".

It should also be able to accept just a single tag, as long as the characters are alphanumeric.

Body:
A separate question is being answered here. How to do the same thing but allow tags with at most two words?

/^\s*[a-z0-9]+(\s+[a-z0-9]+)?(\s*,\s*[a-z0-9]+(\s+[a-z0-9]+)?)*\s*$/

Tested.


问:
Why are .out files hexadecimal instead of binary
From my knowledge, when you compile a file, say a .cpp file, it should transform it to a binary file in order for the machine to understand it. However, after compiling the file and obtaining the .out file, I see that inside it is a hexadecimal code instead of a binary. Can please somebody explain to me what I'm missing?</p>

答: Sublime Text is automatically detecting the file as a binary image and showing you the file with the hexadecimal viewer.</p>


问:
How to filter RDD relying on hash map?
I'm new to using spark and scala but I have to solve the following problem:
I have one ORC file containing rows which I have to check against a certain condition comming from a hash map.

I build the hash map (filename,timestamp) with 120,000 entries this way (getTimestamp returns an Option[Long] type):

```<code>val tgzFilesRDD = sc.textFile("...")
val fileNameTimestampRDD = tgzFilesRDD.map(itr => {
    (itr, getTimestamp(itr))
})
val fileNameTimestamp = fileNameTimestampRDD.collect.toMap
</code>```

And retrieve the RDD with 6 million entries like this:

```<code>val sessionDataDF = sqlContext.read.orc("...")
case class SessionEvent(archiveName: String, eventTimestamp: Long)
val sessionEventsRDD = sessionDataDF.as[SessionEvent].rdd
</code>```

And do the check:

```<code>val sessionEventsToReport = sessionEventsRDD.filter(se => {
    val timestampFromFile = fileNameTimestamp.getOrElse(se.archiveName, None)
    se.eventTimestamp < timestampFromFile.getOrElse[Long](Long.MaxValue)
})
</code>```

Is this the right and performant way to do it? Is there a caching recommended?
Will the Map fileNameTimestamp get shuffled to the clusters where the parititons where processed?

答:
The fileNameTimestamp Map you collected exists on Spark Master Node. In order to be referenced efficiently like this in a query, the worker nodes need to have access to it. This is done by broadcasting.

In essence, you rediscovered Broadcast Hash Join: You are left joining sessionEventsRDD with tgzFilesRDD to gain access to the optional timestamp and then you filter accordingly.

When using RDDs, you need to explicitly code the joining strategy. Dataframes/Datasets API has a query optimiser that can make the choice for you. You can also explicitly ask the API to use the above broadcast join technique behind the scenes. You can find examples for both approaches here.

Let me know if this is clear enough :)

Title: How to filter RDD relying on hash map?

Body:
I'm new to using spark and scala but I have to solve the following problem:
I have one ORC file containing rows which I have to check against a certain condition comming from a hash map.

I build the hash map (filename,timestamp) with 120,000 entries this way (getTimestamp returns an Option[Long] type):

val tgzFilesRDD = sc.textFile("...")
val fileNameTimestampRDD = tgzFilesRDD.map(itr => {
    (itr, getTimestamp(itr))
})
val fileNameTimestamp = fileNameTimestampRDD.collect.toMap

And retrieve the RDD with 6 million entries like this:

val sessionDataDF = sqlContext.read.orc("...")
case class SessionEvent(archiveName: String, eventTimestamp: Long)
val sessionEventsRDD = sessionDataDF.as[SessionEvent].rdd

And do the check:

val sessionEventsToReport = sessionEventsRDD.filter(se => {
    val timestampFromFile = fileNameTimestamp.getOrElse(se.archiveName, None)
    se.eventTimestamp < timestampFromFile.getOrElse[Long](Long.MaxValue)
})

Is this the right and performant way to do it? Is there a caching recommended?
Will the Map fileNameTimestamp get shuffled to the clusters where the parititons where processed?