text:
Q: Failing to catch Errno::ECONNRESET in Ruby code In my Rails 3.1 project, deployed to Heroku, I have a rake task that generates a few hundred thousand small PNGs based on records in the database and uploads the results to S3 using fog, one file at a time. (Before I was using heroku, the task saved the files locally and everything worked fine.) When I run the task using heroku run:detached, it runs for a while, and uploads a bunch of files, but eventually fails with Connection reset by peer (Errno::ECONNRESET). What's weird about this is that I've modified the script to catch and retry that exception like so:
file_exists = false
retry_count = 10
begin
  file_exists = directory.files.head(filekey)
rescue Errno::ECONNRESET => e
  if retry_count > 0 then
    logger.warning("Connection reset: #{e.inspect}")
    retry_count -= 1
    sleep(1)
    retry
  else
    raise
  end
end

According to the stack trace, file_exists = directory.files.head(filekey) is the line of my code that leads to the exception, so I feel like I'm missing something about Ruby exception handling. I'd love to know what I'm doing wrong, since I'm not 100% sure if this is a problem with my begin/rescue block, the way fog handles network errors, or what.
Here's the complete stack trace:
Nov 07 12:08:01 ... app/run.1:  Connection reset by peer (Errno::ECONNRESET)
Nov 07 12:08:01 ... app/run.1:  /app/vendor/ruby-1.8.7/lib/ruby/1.8/openssl/buffering.rb:36:in `sysread'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/ruby-1.8.7/lib/ruby/1.8/openssl/buffering.rb:36:in `fill_rbuff'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/ruby-1.8.7/lib/ruby/1.8/openssl/buffering.rb:68:in `read'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/excon-0.16.7/lib/excon/socket.rb:121:in `read'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/ruby-1.8.7/lib/ruby/1.8/timeout.rb:67:in `timeout'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/excon-0.16.7/lib/excon/socket.rb:120:in `read'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/excon-0.16.7/lib/excon/ssl_socket.rb:79:in `read'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/excon-0.16.7/lib/excon/response.rb:21:in `parse'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/excon-0.16.7/lib/excon/connection.rb:275:in `request_kernel'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/excon-0.16.7/lib/excon/connection.rb:103:in `request'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/fog-1.6.0/lib/fog/core/connection.rb:20:in `request'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/fog-1.6.0/lib/fog/aws/storage.rb:392:in `request'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/fog-1.6.0/lib/fog/aws/requests/storage/head_object.rb:53:in `head_object'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/fog-1.6.0/lib/fog/aws/models/storage/files.rb:98:in `head'
Nov 07 12:08:01 ... app/run.1:  /app/lib/tasks/assets.rake:45
Nov 07 12:08:01 ... app/run.1:  /app/lib/tasks/assets.rake:37:in `each'
Nov 07 12:08:01 ... app/run.1:  /app/lib/tasks/assets.rake:37
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/activerecord-3.1.8/lib/active_record/relation/batches.rb:21:in `find_each'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/activerecord-3.1.8/lib/active_record/relation/batches.rb:21:in `each'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/activerecord-3.1.8/lib/active_record/relation/batches.rb:21:in `find_each'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/activerecord-3.1.8/lib/active_record/relation/batches.rb:69:in `find_in_batches'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/activerecord-3.1.8/lib/active_record/relation/batches.rb:20:in `find_each'
Nov 07 12:08:01 ... app/run.1:  /app/lib/tasks/assets.rake:35
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `call'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `execute'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `each'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `execute'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/task.rb:158:in `invoke_with_call_chain'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/ruby-1.8.7/lib/ruby/1.8/monitor.rb:242:in `synchronize'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/task.rb:144:in `invoke'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:116:in `invoke_task'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `top_level'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `each'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `top_level'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:88:in `top_level'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:66:in `run'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/gems/rake-0.9.2.2/bin/rake:33
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/bin/rake:23:in `load'
Nov 07 12:08:01 ... app/run.1:  /app/vendor/bundle/ruby/1.8/bin/rake:23
Nov 07 12:08:01 ... app/run.1:  Tasks: TOP => ...:make_outlines
Nov 07 12:08:02 ... heroku/run.1:  Process exited with status 1
Nov 07 12:08:02 ... heroku/run.1:  State changed from up to complete

A: perhaps try like this:
begin
  ...
rescue Errno::ECONNRESET => e
  ...
rescue => e
  ...
end


text:
Q: How to handle cursor if it throws exception in EJBs I have a callableStatment, upon execution I get the below error
    try{
callableStatement.executeQuery()
}
    catch (Throwable t) {
                throw new Exception(t);

            }
            finally {
                closeResultSet(rs);
                closeCallableStatement(callableStatement);
                closeConnection(dbConnection);

            }
javax.ejb.EJBTransactionRolledbackException: ORA-30926: unable to get a stable set of rows in the source tables

After some time I get Database Error of  "Too man open cursors"
I know that the procedure is throwing the error due to duplication, I want to know why the Cursors aren't closed as it seems finally block is not doing what I need and what is the proper way to close them

A: The return type of executeQuery() is ResultSet which you have not specified. Try givin it as
ResultSet rst = callableStatement.executeQuery();

Hope it helped. :)

A: I think you are executing a merge query and there is more than 1 row id returned. And this is the reason for that exception. Also when the first duplicate row is returned, there itself the exception is thrown. And before the query is even executed you are trying to close it. That should be the reason for the cursor not closing properly. Try adding a distinct keyword in your query to avoid duplicates. Eg: MERGE INTO table_1 a USING (SELECT distinct ta.ROWID row_id FROM table_1 a ,table_2 b ,table_3 c WHERE ) src ON ( a.ROWID = src.row_id ) WHEN MATCHED THEN ;As there is a rollback involved, it comes under System Exception. And Application Exceptions are not rolled back.

redpajama_set_name: RedPajamaStackExchange


text:
Q: win32com.client.DispatchWithEvents doesn't catch events and raises exception I have to connect to COM interface (specific implementation), call some methods, get responses in both synchronous and asynchronous way. I had to mask some specific interface/methods names while pasting code samples. If I use Dispatch method only, everything works fine:
#works fine in synchronous mode
myObj = win32com.client.Dispatch(myObjID)
myObj.MyMethod1(0)
myResp = myObj.myMethod2()
print "property1: " + myResp.property1 #works fine

Problem starts when I need to get some events (DispatchWithEvents). It causes Python to crash ! Low level networking exception is thrown: exceptions.EOFError: [Errno 10054] An existing connection was forcibly closed by the remote host. Code sample which results in crash:
#crashing code
class SomeEvents(object):
    def OnMethod1(self):
        print 'OnMethod1'

myObj = win32com.client.DispatchWithEvents(myObjID,SomeEvents)
myObj.MyMethod1(0) # CRASH OCCURS HERE!

I have checked what kind of object is actually returned by Dispatch and DispatchWithEvents:
Object returned by Dispatch:
<win32com.gen_py.myComInterface 1.0 Type Library.myComManager instance at 0x20508304>
['CLSID', 'MyMethod1', 'MyMethod2', 'MyMethod3', 'MyMethod4', 'MyMethod5', '_ApplyTypes_', '__doc__', '__eq__', '__getattr__', '__init__', '__iter__', '__module__', '__ne__', '__repr__', '__setattr__', '_get_good_object_', '_get_good_single_object_', '_oleobj_', '_prop_map_get_', '_prop_map_put_', 'coclass_clsid']

Object returned by DispatchWithEvents:
<win32com.client.COMEventClass instance at 0x20462352>
['__del__', '__doc__', '__getattr__', '__init__', '__module__', '__setattr__', '_obj_']

In both cases there are objects of different types returned. Object returned by DispatchWithEvents is COMEventClass and it doesn't contain MyMethod1, MyMethod2 etc. (is that a reason of crash? I would expect "Object has no attribute" exception)
I also tried to implement it by creating 2 different objects. As a result, there is no crash but also no events are caught. Code sample:
#doesn't crash but also doesn't catch any events
class SomeEvents(object):
    def OnMethod1(self):
        print 'OnMethod1'

myObj1 = win32com.client.Dispatch(myObjID)
myObj2 = win32com.client.DispatchWithEvents(myObjID,SomeEvents)
myObj1.MyMethod1(0)
myResp = myObj1.MyMethod2()
print "property1: " + str(myResp.property1) #property displayed correctly
#no 'OnMethod1' printout visible

I was implementing COM client using examples found on internet. Python version: 2.7.6 (32 bit) on WinXP SP3. I couldn't search for any similar problem (what surprised me a little bit). What am I doing wrong? Perhaps specific implementation of COM has bugs? I think that next step would be to implement COM client using VB and check if it has similar problems. What would you suggest?

A: Try connecting to Excel via DispatchWithEvents and trigger some events (look at the excel interop docs online) and see if your listener gets them. If that works then something is wrong with your COM object, or you may have to generate the type library. You can do that by first using your object with EnsureDispatch, you only need to do this once ever. After that, see if using  DispatchWithEvents your Python obj still missing MyMethod1 etc. If not, and the Excel (or any other production-quality COM server like Word or IE) COM instance events work, then there must be something wrong with your COM object.


text:
Q: FluentValidation: Comparing a value with an aggregate of values? I find FluentValidation straightforward when making simple rules for properties on a single class, but as soon as I need to compare values from collections (e.g. a List<T> property), it gets super-hairy. Assume the follwing two minimal classes:
public class PurchaseOrder
{
    public List<LineItem> LineItems { get; set; }
    public decimal Total { get; set; }

    public PurchaseOrder()
    {
        LineItems = new List<LineItem>();
    }
}

public class LineItem
{
    public decimal Price { get; set; }
}

And this class:
class Program
{
    static void Main(string[] args)
    {
        PurchaseOrder order = new PurchaseOrder();
        order.LineItems.Add(new LineItem() { Price = 12m });
        order.LineItems.Add(new LineItem() { Price = 14m });
        order.Total = 26m;

        PurchaseOrderValidator validator = new PurchaseOrderValidator();
        ValidationResult result = validator.Validate(order);
    }
}

How would PurchaseOrderValidator look like to make sure that the sum of all LineItem.Price equals the PurchaseOrder.Total? Here's a stub (although I'm not sure Must() is the way to go):
public class PurchaseOrderValidator : AbstractValidator<PurchaseOrder>
{
    public PurchaseOrderValidator()
    {
        RuleFor(x => x.Total).Must(MatchSumOfLineItems);
    }

    private bool MatchSumOfLineItems(decimal arg)
    {
        return true;
    }
}

A: Why not use .Equal()
public class PurchaseOrderValidator : AbstractValidator<PurchaseOrder>
{
    public PurchaseOrderValidator()
    {
        RuleFor(x => x.Total).Equal(x => x.LineItems.Sum(item => item.Price));
    }
}

A: Just create validation method that takes PurchaseOrder as input and do whatever you want with it
public class PurchaseOrderValidator : AbstractValidator<PurchaseOrder>
{
    public PurchaseOrderValidator()
    {
        RuleFor(x => x).Must(MatchSumOfLineItems);
    }

    private bool MatchSumOfLineItems(PurchaseOrder arg)
    {
        return arg.Total == arg.LineItems.Sum(i => i.Price);
    }
}

or if you want to add validation specifically for Total property you can use another Must overload accepts Func<decimal, PurchaseOrder, bool>
public class PurchaseOrderValidator : AbstractValidator<PurchaseOrder>
{
    public PurchaseOrderValidator()
    {
        RuleFor(x => x.Total).Must(MatchSumOfLineItems);
    }

    private bool MatchSumOfLineItems(PurchaseOrder order, decimal sum)
    {
        return sum == order.LineItems.Sum(i => i.Price);
    }
}


text:
Q: Is it correct for a HTTP app to accept a query string containing unencoded special chars and fail for an equivalent URL with special chars encoded? I've encountered a situation whereby a GET request for a URL where the query string contains unencoded special characters returns 200 OK for the URL as-is but returns a 400 Bad Request when the special characters are url-encoded.
A simplified example of such a URL is: http://example.com/??foo/bar+foobar
Note the double question mark such that the entire query string is a single key-value pair with a null value.
URL-encoding the query string key gives us: http://example.com/?%3Ffoo%2Fbar+foobar
A GET request for this URL containing encoded characters will return 400 Bad Request.
The application handling these URLs (a third party I don't control) appears to not like the query string key to contain url-encoded equivalents of non-alphanumeric characters.
I was under the assumption that http://example.com/??foo/bar+foobar and http://example.com/?%3Ffoo%2Fbar+foobar should be equivalent and consequently interchangeable. This may be an invalid assumption.
Are these two URLs equivalent and consequently interchangable?
Is it the application that handles these URLs at fault for not treating these URLs as equivalent or is it my application, which is applying url-encoding to query string keys and values, at fault for applying such encoding?


text:
Q: Angular2 Child Routing i have some problem.
let me explain
this is my html code

   ×
   {{ errorMessage }}

All Unread Report

       NIK
       Nama
       Topik
       Detail

      {{i+1}}
      {{item.sendername}}
      {{item.topic}}

        Edit

what i want is if i click that edit button link it will navigate to other component. but i always get error like this below

Uncaught (in promise): Error: Cannot match any routes. URL Segment:
  'edit/1' Error: Cannot match any routes. URL Segment: 'edit/1

this is my route config
{ path: 'dashboard_pool', component: DashboardPoolComponent,
  children:[
    { path: 'unread', component: PoolUnreadReportComponent,
      children:[
        {path:'detail/:id', component:PoolComplaintDetailComponent}
      ]
    },

how to resolve this? thanks :)

A: It's because using routerLink like that calls for a relative path.
If you want to go to the child, use
Edit

A: Try with:
// inside PoolUnreadReportComponent.html
Edit

// inside DashboardComponent.html
Edit

Avoid using manual concatenation of parameters and use an array to pass the values instead (the so called link parameters array). Angular takes care of the rest.
Some extra info about routing:

*

*../ means that you go one level up in the route tree

*./ means sybling

*/ means absolut path, [routerLink]="['/edit', item.id]" would be
root/edit/:id for example

For more info check the routing docs


text:
Q: Laravel: something is changing the method, what is it? I have a simple blade form mith post method and csrf token:
<form name="login" action="{{ route('login.do') }}" method="post" autocomplete="off">
    @csrf

        E-mail:
        <input type="email" name="email" required/>

        Password:
        <input type="password" name="password_check"/>

    <button class="gradient gradient-orange radius icon-sign-in" type="submit">Send</button>
</form>

and the route in routes/web.php:
Route::post('login', 'AuthController@login')->name('login.do');

when I submit the form, I get the error:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.

As you can see, the route and the form are ok, but something is messing it up and changing the method. It won't even get to the controller layer.
some infos:
-Laravel 8.12
-I have no customized middleware
-The htaccess and config/cors are default
-The route doesn't end with a slash nor is duplicated
-Whenever I do an alteration I clean the caches
-The APP_URL starts with http and SESSION_SECURE_COOKIE is set to false due to it
-The APP_ENV is production
What can it be? I've read it may be something in the server that's blocking the request and changing its method, so I'm not sure if the error is laravel or server related.

A: public function login(Request $request){

   dd($request->all());

}


text:
Q: Spring boot + MySQL Community Server I have been working on an application that uses Spring boot + MySQL Community Server as database.
My issue is if i use compound names like offeredServices i get this error on my browser:
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Aug 04 21:15:23 EEST 2017
There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

data.sql
INSERT INTO test(name, offeredServices) VALUES
  ('Test 1','Test 1'),
  ('Test 2','Test 2');

DROP DATABASE IF EXISTS v;
CREATE DATABASE v;
USE v;
CREATE TABLE test (
  id INT PRIMARY KEY auto_increment,
  name VARCHAR(40),
  serviceDescription VARCHAR(40)
);

But if i use short/simple name like nnnn it works
DROP DATABASE IF EXISTS v;
CREATE DATABASE v;
USE v;
CREATE TABLE test (
  id INT PRIMARY KEY auto_increment,
  name VARCHAR(40),
  nnnn VARCHAR(40)
);

INSERT INTO test(name, nnnn) VALUES
  ('Test 1','Test 1'),
  ('Test 2','Test 2');

From my class in java:
@Entity
@Table(name = "test")
public class Test {

    private int id;
    private String nnnn;
 public String getNnnn() {
        return nnnn;
    }
    public void setNnnn(String nnnn) {
        this.nnnn = nnnn;}

@Entity
@Table(name = "test")
public class Test {

    private int id;
    private String offeredServices;
 public String getOfferedServices() {
        return offeredServices;
    }
    public void setOfferedServices(String offeredServices) {
        this.offeredServices = offeredServices;}

My application.properties.
spring.datasource.url=jdbc:mysql://localhost:3306/v?autoReconnect=true&useSSL=false
spring.datasource.username=junior
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.port=8089

From my pom:
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

I am not much with:
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop

Because it ignore my initial values.
Using spring.jpa.hibernate.ddl-auto=update gives the following error.
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-08-05 10:26:32.951 ERROR 6528 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at com.example.EmployeeLocatorApplication.main(EmployeeLocatorApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [create table project (id integer not null auto_increment, name varchar(255), team_id integer not null, primary key (id)) ENGINE=InnoDB]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:59) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:420) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.createTable(SchemaMigratorImpl.java:236) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:167) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'project' already exists
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_131]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_131]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2497) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1540) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2595) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1468) ~[mysql-connector-java-5.1.41.jar:5.1.41]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    ... 32 common frames omitted

------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 9.998s
Finished at: Sat Aug 05 10:26:33 EEST 2017
Final Memory: 10M/155M
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project my-project: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

A: SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

SQLGrammarException is an exception related to sql syntax errors, but it doesn't give to much information of the root cause.
I was trying to replicate the same error using the same attribute names and table names and I found this:

*

*The Test table creation script is not related to the Test Java entity definition. There is a mismatch because test table create has a field called serviceDescription VARCHAR(40) but in the Test java class there is a totally diferent attribute name called offeredServices.

*The create table script has a field called name VARCHAR(40) but in the Test Java entity definition there is no name attribute.

Now lets assume that we have both components related the Database Table and the Java Entity Class.
like this
Create Test table
    DROP DATABASE IF EXISTS v;
    CREATE DATABASE v CHARACTER SET utf8 COLLATE utf8_bin;
    USE v;
    CREATE TABLE test (
      id INT PRIMARY KEY auto_increment,
      name VARCHAR(40),
      offeredServices VARCHAR(40)
    );

Test java class
@Entity
@Table(name = "test")
public class Test {

    @Id
    @GeneratedValue
    private int id;

    private String name;

    private String offeredServices;

    public String getOfferedServices() {
        return offeredServices;
    }

    public void setOfferedServices(String offeredServices) {
        this.offeredServices = offeredServices;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

data.sql
INSERT INTO test(name, offeredServices) VALUES
  ('Test 1','Test 1'),
  ('Test 2','Test 2');

Test repository
    public interface TestRepository extends JpaRepository<Test,Integer> {}

Spring Boot Class
@SpringBootApplication
public class MysqlerrordemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MysqlerrordemoApplication.class, args);
    }

    @Bean
    public CommandLineRunner runner( TestRepository testRepository){
        return (args) -> {
            testRepository.findAll().forEach(System.out::println);
        };
    }
}

When I run the application I have got the following error:
 SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'test0_.service_description' in 'field list'

This exception means that hibernate is converting the offeredServices attribute name (from camelCase) to offered_services column name (to SNAKE_CASE) because hibernate is using SpringNamingStrategy to generate table and column names.
To solve the problem just add a @Column(name="offeredservices") annotation to the offeredServices attribute.  The @Column(name="offeredservices") annotation tells to hibernate that dont try to convert the camelCase attribute name to SNAKE_CASE, just keep column name in lowercase.
This is the final version of Test java class.
@Entity
@Table(name = "test")
public class Test {

    @Id
    @GeneratedValue
    private int id;

    private String name;

    @Column(name="offeredservices")
    private String offeredServices;

    public String getOfferedServices() {
        return offeredServices;
    }

    public void setOfferedServices(String offeredServices) {
        this.offeredServices = offeredServices;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

To get a very clear answer about this go to the this post spring-boot-jpa-column-name-annotation-ignored
Please also keep the spring.jpa.hibernate.ddl-auto property to create-drop
spring.jpa.hibernate.ddl-auto=create-drop


text:
Q: Bundle install not work on rvm + ruby2.0.0 after install RVM and ruby2.0.0, running
$ bundle install

just get nothing response and halt. How can i track where have the problem?
Gemfile:

source "https://rubygems.org"
gem 'rails', '4.0.0

trying to list:

    $ bundle list
    Gems included by the bundle:
    * actionmailer (4.0.0)
    * actionpack (4.0.0)
    * activemodel (4.0.0)
    * activerecord (4.0.0)
    * activerecord-deprecated_finders (1.0.3)
    * activesupport (4.0.0)
    * arel (4.0.0)
    * atomic (1.1.14)
    * builder (3.1.4)
    * bundler (1.3.5)
    * erubis (2.7.0)
    * hike (1.2.3)
    * i18n (0.6.5)
    * mail (2.5.4)
    * mime-types (1.25)
    * minitest (4.3.2)
    * multi_json (1.8.0)
    * polyglot (0.3.3)
    * rack (1.5.2)
    * rack-test (0.6.2)
    * rails (4.0.0)
    * railties (4.0.0)
    * rake (10.1.0)
    * sprockets (2.10.0)
    * sprockets-rails (2.0.0)
    * thor (0.18.1)
    * thread_safe (0.1.3)
    * tilt (1.4.1)
    * treetop (1.4.15)
    * tzinfo (0.3.37)

I install RVM in my home directory without sudo. I even do rvm implode and re-install and just rvm install 2.0.0 and the bundle command halt.

$ rvm info

ruby-2.0.0-p247:

  system:
    uname:       "Linux localhost.localdomain 2.6.32-279.el6.x86_64 #1 SMP Wed Jun 13 18:24:36 EDT 2012 x86_64 x86_64 x86_64 GNU/Linux"
    system:      "redhat/6/x86_64"
    bash:        "/bin/bash => GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)"
    zsh:         " => not installed"

  rvm:
    version:      "rvm 1.22.11 (stable) by Wayne E. Seguin , Michal Papis  [https://rvm.io/]"
    updated:      "23 hours 31 minutes 28 seconds ago"
    path:         "/home/liangji/.rvm"

  ruby:
    interpreter:  "ruby"
    version:      "2.0.0p247"
    date:         "2013-06-27"
    platform:     "x86_64-linux"
    patchlevel:   "2013-06-27 revision 41674"
    full_version: "ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]"

  homes:
    gem:          "/home/liangji/.rvm/gems/ruby-2.0.0-p247"
    ruby:         "/home/liangji/.rvm/rubies/ruby-2.0.0-p247"

  binaries:
    ruby:         "/home/liangji/.rvm/rubies/ruby-2.0.0-p247/bin/ruby"
    irb:          "/home/liangji/.rvm/rubies/ruby-2.0.0-p247/bin/irb"
    gem:          "/home/liangji/.rvm/rubies/ruby-2.0.0-p247/bin/gem"
    rake:         "/home/liangji/.rvm/gems/ruby-2.0.0-p247@global/bin/rake"

  environment:
    PATH:         "/home/liangji/.rvm/gems/ruby-2.0.0-p247/bin:/home/liangji/.rvm/gems/ruby-2.0.0-p247@global/bin:/home/liangji/.rvm/rubies/ruby-2.0.0-p247/bin:/home/liangji/.rvm/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/liangji/bin"
    GEM_HOME:     "/home/liangji/.rvm/gems/ruby-2.0.0-p247"
    GEM_PATH:     "/home/liangji/.rvm/gems/ruby-2.0.0-p247:/home/liangji/.rvm/gems/ruby-2.0.0-p247@global"
    MY_RUBY_HOME: "/home/liangji/.rvm/rubies/ruby-2.0.0-p247"
    IRBRC:        "/home/liangji/.rvm/rubies/ruby-2.0.0-p247/.irbrc"
    RUBYOPT:      ""
    gemset:       ""

A: Oh man! it works now. I think maybe the only step used sudo is rvmsudo passenger-install-nginx-module. I don't run the command this time.


text:
Q: Android Adding AdView into HTML5WebView I am using HTML5WebView.
https://code.google.com/p/html5webview/source/browse/#svn%2Ftrunk%2FHTML5WebView%253Fstate%253Dclosed
I am adding Google AdView at the bottom of the HTML5WebView but AdView is showing over on top of the HTML5WebView. I would like HTML5WebView take only the rest of the screen after AdView is taken.
May I know how can I change my layout. I have tried so may way but no luck. Here is my latest result that AdView is overlapping HTML5WebView.
Thanks,
Alex
Here is my
custom_screen.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads">

    <FrameLayout android:id="@+id/fullscreen_custom_content"
        android:visibility="gone"
        android:background="@color/black"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"  >
        <ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="5dp"
            android:layout_gravity="center_vertical|center_horizontal"
            android:indeterminate="true"
               android:id="@+id/webViewProgressBar"/>

        <LinearLayout
            android:id="@+id/error_console"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
        />
        <FrameLayout android:id="@+id/main_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
        />
    </LinearLayout>

    <com.google.ads.AdView
             android:id="@+id/adView"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:layout_gravity="bottom"
             ads:adUnitId="a15302d1a9e05e7"
             ads:adSize="BANNER"
             ads:testDevices="TEST_EMULATOR"
             ads:loadAdOnCreate="true"/>

</FrameLayout>

HTML5WebView.java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

public class HTML5WebView extends WebView {

    private Context                                                         mContext;
    private MyWebChromeClient                                               mWebChromeClient;
    private View                                                            mCustomView;
    private FrameLayout                                                     mCustomViewContainer;
    private WebChromeClient.CustomViewCallback                              mCustomViewCallback;

    private FrameLayout                                                     mContentView;
    private FrameLayout                                                     mBrowserFrameLayout;
    private FrameLayout                                                     mLayout;
    private ProgressBar                                                     progressBar;
static final String LOGTAG = "HTML5WebView";

    @SuppressLint({ "SetJavaScriptEnabled", "SdCardPath" })
    @SuppressWarnings("deprecation")
    private void init(Context context) {
        mContext = context;
        Activity a = (Activity) mContext;

        mLayout = new FrameLayout(context);

        mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(a).inflate(R.layout.custom_screen, null);
        mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.main_content);
        mCustomViewContainer = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.fullscreen_custom_content);

        mLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
        progressBar = (ProgressBar) mBrowserFrameLayout.findViewById(R.id.webViewProgressBar);
        mWebChromeClient = new MyWebChromeClient();
        setWebChromeClient(mWebChromeClient);

        setWebViewClient(new MyWebViewClient(progressBar));

        // Configure the webview
        WebSettings s = getSettings();
        s.setBuiltInZoomControls(true);
        s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        s.setUseWideViewPort(true);
        s.setLoadWithOverviewMode(true);
        s.setSavePassword(true);
        s.setSaveFormData(true);
        s.setJavaScriptEnabled(true);

        // enable navigator.geolocation
        s.setGeolocationEnabled(true);
        s.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");

        // enable Web Storage: localStorage, sessionStorage
        s.setDomStorageEnabled(true);

        mContentView.addView(this);
    }

    public HTML5WebView(Context context) {
            super(context);
            init(context);
    }

    public HTML5WebView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(context);
    }

    public HTML5WebView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init(context);
    }

    public FrameLayout getLayout() {
            return mLayout;
    }

public boolean inCustomView() {
            return (mCustomView != null);
    }

public void hideCustomView() {
            mWebChromeClient.onHideCustomView();
    }

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((mCustomView == null) && canGoBack()){
                    goBack();
                    return true;
            }
    }
    return super.onKeyDown(keyCode, event);
}

    private class MyWebChromeClient extends WebChromeClient {
        private Bitmap          mDefaultVideoPoster;
        private View            mVideoProgressView;

        @Override
        public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
        {
                //Log.i(LOGTAG, "here in on ShowCustomView");
            HTML5WebView.this.setVisibility(View.GONE);

            // if a view already exists then immediately terminate the new one
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }

            mCustomViewContainer.addView(view);
            mCustomView = view;
            mCustomViewCallback = callback;
            mCustomViewContainer.setVisibility(View.VISIBLE);
        }

        @Override
        public void onHideCustomView() {

                if (mCustomView == null)
                        return;

                // Hide the custom view.
                mCustomView.setVisibility(View.GONE);

                // Remove the custom view from its container.
                mCustomViewContainer.removeView(mCustomView);
                mCustomView = null;
                mCustomViewContainer.setVisibility(View.GONE);
                mCustomViewCallback.onCustomViewHidden();

                HTML5WebView.this.setVisibility(View.VISIBLE);

        //Log.i(LOGTAG, "set it to webVew");
        }

        @Override
        public Bitmap getDefaultVideoPoster() {
                //Log.i(LOGTAG, "here in on getDefaultVideoPoster");
                if (mDefaultVideoPoster == null) {
                        mDefaultVideoPoster = BitmapFactory.decodeResource(
                                        getResources(), R.drawable.default_video_poster);
            }
                return mDefaultVideoPoster;
        }

        @Override
        public View getVideoLoadingProgressView() {
                //Log.i(LOGTAG, "here in on getVideoLoadingPregressView");

        if (mVideoProgressView == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
        }
        return mVideoProgressView;
        }

         @Override
         public void onReceivedTitle(WebView view, String title) {
            ((Activity) mContext).setTitle(title);
         }

         @Override
         public void onProgressChanged(WebView view, int newProgress) {
                 ((Activity) mContext).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);
         }

         @Override
         public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
             callback.invoke(origin, true, false);
         }
    }

    private class MyWebViewClient extends WebViewClient {
        private ProgressBar progressBar;
        public MyWebViewClient(ProgressBar progressBar) {
            this.progressBar=progressBar;
            progressBar.setVisibility(View.VISIBLE);
        }
        @Override

        public void onPageFinished(WebView view, String url) {

             // TODO Auto-generated method stub

             super.onPageFinished(view, url);

             progressBar.setVisibility(View.GONE);

        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i(LOGTAG, "shouldOverrideUrlLoading: "+url);
            // don't override URL so that stuff within iframe can work properly
            // view.loadUrl(url);
            return false;
        }

    }

    static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
    new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

A: Wrap your LinearLayout and AdView like so:
<LinearLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"  >

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"  >
        <ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="5dp"
            android:layout_gravity="center_vertical|center_horizontal"
            android:indeterminate="true"
               android:id="@+id/webViewProgressBar"/>

        <LinearLayout
            android:id="@+id/error_console"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
        />
        <FrameLayout android:id="@+id/main_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
        />
    </LinearLayout>

    <com.google.ads.AdView
             android:id="@+id/adView"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             ads:adUnitId="a15302d1a9e05e7"
             ads:adSize="BANNER"
             ads:testDevices="TEST_EMULATOR"
             ads:loadAdOnCreate="true"/>

</LinearLayout>


text:
Q: Copy CStringArray data to unsigned char array I have CStringArray data and I want to assign all data in unsigned char array.
CStringArray m_arrSecurityAES;
unsigned char private_key[16];
m_arrSecurityAES contains data as (00, 01....0E 0F).

I want to assign this data in private_key in Hex format as (0x00, 0x01, ..., 0x0E, 0x0F).
Can someone please help me how to assign it?

A: You want this:
  CStringArray m_arrSecurityAES;
  m_arrSecurityAES.Add(_T("00"));
  m_arrSecurityAES.Add(_T("01"));
  m_arrSecurityAES.Add(_T("0A"));  // only three values in this sample

  unsigned char private_key[16];

  for (int i = 0; i < m_arrSecurityAES.GetSize(); i++)
  {
    private_key[i] = (unsigned char)_tcstoul(m_arrSecurityAES[i].GetString(), NULL, 16);
  }


text:
Q: About database design: How should I classify some date information? New to database and confused by some concept so I come to seek help.
Wanna to design a database about package delivery company, which needs to  keep track of packages.
There are a few of entities: delivery company, warehouse, conveyance(like plane), shipper, and receiver. The company need to know the where and when package is at any time, and check the situation of the warehouse or plane, like what they've delivered last month.
Tried to add a current time column to the package entity but if so it can't be tracked at any time, and the company can't check the concrete situation of the warehouse or conveyance.
Thought of adding a time entity including columns: time, ID of package, posistion. But I wonder if it's reasonable since the entities I've seen (like students, teachers and workers) are kinda different from this and it's hard to describe in the E-R diagram. Is this thought reasonable or is there any better advice?
Not a English native speaker if my expression is confusing you may ask, thank you. :)

A: You can use this schema as a skeleton. It should work for you. On every update on the package table you should insert a row to package_history with updated values (maybe using a trigger).
You can reach not just the current place and time information but also the whole history of a package by querying the package_history table.
Maybe you can add a new table for city/province information, it's up to you.
I haven't specified the datatypes but I think it's understandable.
package
-------
id PK
package_name
from
to
place_id FK
status_id FK

place
------
id PK
city
place_name (delivery company, warehouse, conveyance(like plane), shipper, and receiver)

status
-----
id PK
status_name (waiting, in process, ready to deliver etc...)

package_history
-------------
id PK
package_id FK
place_id FK
status_id FK
status_datetime
additional_notes


text:
Q: ActionLink to submit Model value I want my Ajax.ActionLink to pass a viewModel property to action.
Here is my ViewModel
public class ViewModel
    {
        public string Searchtext { get; set; }
    }

My .cshtml
@Ajax.ActionLink("Bottom3", "Bottom3",new { name = Model.Searchtext}, new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "pointsDiv"
})

 using(Html.BeginForm("Bottom3", "Home", FormMethod.Get))
     {
         @Html.TextBoxFor(x => x.Searchtext)
         <button type="submit">Search</button>
     }

}

My Controller action:
public PartialViewResult Bottom3(string name)
        {
            var model = db.XLBDataPoints.OrderBy(x => x.DataPointID).Take(3).ToList();

            return PartialView("Partial1", model);
        }

But the name parameter passed to the action is always null. How do I solve this?

A: In your code... you have 2 different ways of posting to the server: the link and the form button.
The problem is that the ActionLink has no way to get the value from the input in client side... just the original value.
If you press the Search button, you will see a value posted.
Now, you can use some jQuery to modify a standard ActionLink (not the Ajax.ActionLink):
https://stackoverflow.com/a/1148468/7720
Or... you can transform your Form in order to do a Ajax post instead of a normal one:
https://stackoverflow.com/a/9051612/7720

A: I did this for a model of mine like so.  I ONLY supported the HttpPost method.  So add the HttpMethod="POST" to your Ajax.ActionLink
    [HttpPost]
    public ActionResult Accounts(ParametricAccountsModel model)
    {
        if (model.Accounts == null)
        {
            GetAccountsForModel(model);
        }
        if (model.AccountIds == null)
        {
            model.AccountIds = new List<int>();
        }
        return View(model);
    }

On the razor view
@Ajax.ActionLink(
        "Add Account to Order", "Accounts", "Parametric", null,
        new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "...", HttpMethod = "POST" },
        new { @id = "AddParametricAccountLink" })

The model has a list of selected account ids.  So in javascript, I modified the href of the action link dynamically.
function UpdateParametricAccountAction() {
    var originalLink = '/TradeNCashMgmt/Parametric/Accounts';
    var append = '';
    var numberOfRows = $('#ParametricAccounts').find('.parametric-account-  row').size();
    for (var i = 0; i < numberOfRows; i++) {
        if (i != 0) {
            append += '&';
        }
        else {
            append = '?';
        }
        var idValue = $('#NotionalTransactionsAccountId_' + i).val();
        append += 'AccountIds%5B' + i + '%5D=' + idValue;
    }

    $('#AddParametricAccountLink').attr('href', originalLink + append);
}

Since the model binder looks for parameter names in the query string and form submission, it will pick up values using the href. So I posted a model object using the querystring on my Ajax.ActionLink.  Not the cleanest method, but it works.


text:
Q: How to center imageview on actionbar with icons inflated by menu My imageview was centering when I had one icon to the right and a back button to the left, but now with two icons on the right it is offset by one of the icons, was wondering if I can do something in xml to keep the imageview centered?
Here is my xml and I tried layout gravity center, and gravity center neither worked.
<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@drawable/action_bar_background"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:src="@drawable/logo"
                android:layout_gravity="center"
                android:adjustViewBounds="true"/>
        </android.support.v7.widget.Toolbar>

Here is the menu file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_comments"
        android:orderInCategory="100"
        android:title="@string/action_comments"
        android:icon="@drawable/ic_action_refresh"
        app:showAsAction="always" />
    <item
        android:id="@+id/action_share"
        android:orderInCategory="100"
        android:title="@string/action_share"
        android:icon="@drawable/ic_action_refresh"
        app:showAsAction="always" />
</menu>


text:
Q: Why isn't my addOnSuccesListener working? I'm trying to get any user that has "like" or "dislike" as string value besides myself, but my code is simply jumping of to the end of the function without executing the code inside. What do I have to change? I tried in another project to test and it worked fine, I just did a copy and paste with the function and now it isn't working.
Sorry for my poor english, I'm brazillian.
private void getMyIdEqualLike() {
        Query query = usersReferenceDb.document(userCardViewID).collection("connections").whereEqualTo(myUId, "like");
        query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                uConnectID = queryDocumentSnapshots.getDocuments().toString();
            }
        });
    }

The getDocuments() function it's supposed to return a list with a documentSnapshot of my user if it's equal to "like" and if it isn't then returns "[]" as empty list, but I'm getting null from uConnectID variable, so I debugged it step by step and I saw that it stops at "query.get().addOnSuccessListener..." and jump right to the end of it's function.

A: Use addOnCompleteListener and check if the query.get() is completing successfully or not.
Your code has onSuccessListener which will only be triggered if the call was successful.


text:
Q: Reload Powershell Console I am trying a script that installs several applications.
choco install nvm;
nvm install 12;

These commands works fine when they ran in separate sessions. After executing
choco install nvm;
I have to restart the powershell console and execute the second command. How to overcome this?
As far I searched I came to know that I have to use 'dotsource'.
But I dont know to do this. Any help?


text:
Q: Questions regarding MVC design architecture of a Cocoa app
*

*My goal

Make an app with one window. The root view of the window will be a couple of images with 4 buttons. Each of these 4 buttons will display a different (main) view. Each main view will display other (sub)views and each main and sub views should be capable of "going back" to the root view.

*

*What I have done (it is based on Apple's ViewController project)

*

*I created 1 NSWindowController and 4 NSViewController with their respected XIB files.

*The AppDelegate alloc/init an NSWindowController object with the nib containing the window and the root view, then calls showWindow method on it.

*My subclass of NSWindowController has two ivars: one NSView representing the root view  bound in IB, and one NSViewController representing the current view controller.

*I bound the 4 buttons to the method which changes the view depending on the button tag.

Here is how Apple's ViewController project implements it http://pastie.org/private/zmqpzgnudgovagwigal8dq
Nonetheless, this doesn't work for me, it just add the view on top of the root view.
As you see, I'm a bit lost, feel free to share your ideas!

A: One approach is to use NSBox.  The full code for this demo is on github.  See the link at the bottom.
Getting Started
Start a new project in Xcode using the Cocoa Application template.  Use the prefix appropriate to you.  I'll use SOD for StackOverflowDemo.
Before doing anything else, make a couple of small changes to the files that were added to your project automatically as part of the template:

*

*MainMenu.xib: delete the NSWindow.

*SODAppDelegate.h: delete the line: @property (assign) IBOutlet NSWindow *window;
To simplify your example, let's say you want to have a single window with a column of clickable items (for simplicity, let's say buttons) on the left hand side.
SODWindowController
Start by adding an NSWindowController subclass to your project.  Be sure to include a corresponding XIB.  Open SODWindowController.xib, add four buttons (I used square buttons) to the left hand side of the window and add an NSBox, filling the rest of the window.  At this point, you'll have something a bit like this.

I set the contentView of the box to be a layer-hosting view whose layer had a background color of [NSColor greenColor].  I did this because, otherwise, you wouldn't be able to see the box at all.  The box has been configured so that it will be used only for swapping views in and out of.  To configure your box like this, in Interface Builder, select the NSBox and, in the Attributes Inspector, set the Title Position to be None and set the Border Type to be None.
Now in SODWindowController.m, replace the stub for initWithWindow:
- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
    }

    return self;
}

with a different designated initializer:
- (id)init
{
    self = [super initWithWindowNibName:@"SODWindowController"];
    {

    }
    return self;
}

This will allow you to avoid having to retype (and potentially mistype XIB's name.
Additionally, add a class extension for SODWindowController just after the line
#import "SODWindowController.h"

in SODWindowController.m, giving yourself an IBOutlet to the NSBox:
@interface SODWindowController ()
@property (nonatomic, strong, readwrite) IBOutlet NSBox *box;
@end

In Interface Builder, open SODWindowController.xib and set the box outlet to point to the NSBox you added.
Add SODWindowController to SODAppDelegate
Now, add a SODWindowController to SODAppDelegate: add the lines to SODAppDelegate.m just below #import "SODAppDelegate.h":
#import "SODWindowController.h"

@interface SODAppDelegate ()
@property (nonatomic, strong, readwrite) SODWindowController *windowController;
@end

Now we can set our window up to be created on -[NSApplication applicationDidFinishLaunching:]:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    self.windowController = [[SODWindowController alloc] init];
    //notice that we don't have to do anything awkward like use initWithWindowNibName:
    [self.windowController showWindow:nil];
}

At this point, when we run the app, we will see our window.
Great, but what about the different views for the four different buttons and the history so that the user can go back?
SODViewControllers
For each of the four views, create an NSViewController subclass.  I'll call mine SODCoffeeViewController, SODTeaViewController, SODJavaViewController and SODMeViewController.
In each of them, replace the automatically generated designated initializer stub
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Initialization code here.
    }

    return self;
}

with
- (id)init
{
    self = [super initWithNibName:@"SODCoffeeViewController" bundle:nil];
    if (self) {
    }
    return self;
}

although of course substituting in the appropriate NibName argument for each.  As before, this will prevent you from having to type `@"MyNibName" anywhere outside of the file which is associated with that Nib.
Add SODViewControllers to SODWindowController
Now, import all four of your view controllers into SODWindowController: add the lines
#import "SODCoffeeViewController.m"
#import "SODTeaViewController.m"
#import "SODJavaViewController.m"
#import "SODTeaViewController.m"

Our SODWindowController needs one of each of these objects.  The easiest thing to do add an NSArray property to our SODWindowController class extension
@property (nonatomic, strong, readwrite) NSArray *viewControllers;

and in the implementation of -[SODWindowController init] add the lines
- (id)init
{
    self = [super initWithWindowNibName:@"SODWindowController"];
    if (self) {
        NSMutableArray *mutableViewControllers = [NSMutableArray array];
        [mutableViewControllers addObject:[[SODCoffeeViewController alloc] init]];
        [mutableViewControllers addObject:[[SODTeaViewController alloc] init]];
        [mutableViewControllers addObject:[[SODJavaViewController alloc] init]];
        [mutableViewControllers addObject:[[SODMeViewController alloc] init]];
        self.viewControllers = [mutableViewControllers copy];
    }
    return self;
}

Now we have one view controller for each of the four views that we want to present, and they are ordered in an array just as they are the four buttons are on the window.  More importantly, they are ordered in the same way as the tags on our four buttons.  ...after we set their tags, that is.
Open SODWindowController.xib in Interface Builder and set the tag of the top button to 0, the second from the top to 1 and so forth.
Back in SODWindowController.m, add an IBAction to the SODWindowController class extension:
- (IBAction)showPane:(id)sender;

Define this method in the SODWindowController @implemention as follows:
- (void)showPane:(NSButton *)sender
{
    [self showPaneAtIndex:sender.tag];
}

And that's it!
...except of course for defining -[SODWindowController showPaneAtIndex:].  But before doing that, set the action of the four buttons in SODWindowController.xib to be showPane: on File's Owner.
With that done, define showPaneAtIndex: as follows:
- (void)showPaneAtIndex:(NSInteger)index
{
    NSViewController *viewController = (NSViewController *)self.viewController[(NSUInteger)index];
    [self.box setContentView:viewController.view];
}

Now, whenever any of the buttons is pressed, the view of the corresponding view controller will be set as the content view of the box.
Probably, we want the top-most view controller's view (the SODCoffeeViewController's) to be shown as soon as the window appears.  To make this happen, just replace the present definition of -windowDidLoad with
- (void)windowDidLoad
{
    [super windowDidLoad];
    [self showPaneAtIndex:0];
}

History
The history is actually the easiest part.  What we will do is keep track of an array or two of panes that are behind us (in the sense of the back button in a browser) and those that are before us (in the sense of the forward button).  To do this, we will add two mutable array properties to our SODWindowController class extension:
@property (nonatomic, strong, readwrite) NSMutableArray *panesBehind;
@property (nonatomic, strong, readwrite) NSMutableArray *panesBefore;

and initialize them in -init:
    ...
    self.viewControllers = [mutableViewControllers copy];

    self.panesBehind = [NSMutableArray array];
    self.panesBefore = [NSMutableArray array];
    }
    return self;
}

Now, we will need to push the index of each new pane that we visit onto self.panesBehind, so add the line
[self.panesBehind addObject:[NSNumber numberWithInteger:index]];

to your definition of -showPaneAtIndex:.
This allows us to define -goBack, -goForward and the helpers -canGoBack and -canGoForward as follows:
- (BOOL)canGoBack
{
    return self.panesBehind.count > 0;
}

- (void)goBack
{
    if (self.canGoBack) {
        NSNumber *presentPane = self.panesBehind.lastObject;
        [self.panesBehind removeLastObject];
        [self.panesBefore insertObject:presentPane atIndex:0];
        NSNumber *previousPane = self.panesBehind.lastObject;
        [self.panesBehind removeLastObject];
        [self showPaneAtIndex:previousPane.integerValue];
    }
}

- (BOOL)canGoForward
{
    return self.panesBefore.count > 0;
}

- (void)goForward
{
    if (self.canGoForward) {
        NSNumber *nextPane = [self.panesBefore objectAtIndex:0];
        [self.panesBefore removeObjectAtIndex:0];
        [self showPaneAtIndex:nextPane.integerValue];
    }
}

There is a small problem with this, though.  If we go forward from pane A to B to C to D then self.panesBehind looks like
A-->B-->C-->D

and self.panesBefore is empty.  But if we go back two panes, self.panesBehind looks like
A-->B

and self.panesBefore looks like
C-->D

If at this point we now go to pane E, self.panesBehind will look like
A-->B-->E

as we expect, but self.panesBefore will still look like
C-->D

which is not what we want.  For this reason, we add the line
[self.panesBefore removeAllObjects];

to the end of -showPane:.
To try these methods out, go ahead and declare them publicly in the @interface of SODWindowController in SODWindowController.h:
@interface SODWindowController : NSWindowController
- (void)goForward;
- (void)goBack;
@end

Then in MainMenu.xib add two menu items to the File menu for Forward and Back.  In SODAppDelegate.h declare two IBActions:
- (IBAction)forward:(id)sender;
- (IBAction)back:(id)sender;

And back in MainMenu.xib, set the action of the Forward menu item to be forward: on the First Responder and the action of the Back menu item to be back: on the First Responder.  Finally, define the two methods -[SODAppDelegate forward:] and -[SODAppDelegate back:] to call through to the corresponding methods on SODWindowController:
- (IBAction)forward:(id)sender
{
    [self.windowController goForward];
}

- (IBAction)back:(id)sender
{
    [self.windowController goBack];
}

To download the full source, visit https://github.com/natechan/ViewSwappingDemo.


text:
Q: Override toString method is not getting called from Companion Object I thought I can call methods of class once I created the object of that class through companion object. But I am not able to do that.
Below is my code:
class Employee(val id: Int, val initialBalance: Int) {
  val message = println("Object created with Id: " + id + " balance: " + initialBalance)

  def printEmployeeDetails = "Id: " + id + " InitialBalance: " + initialBalance
  override def toString = "Id: " + id + " InitialBalance: " + initialBalance
}

object Employee {
  private var id = 0

  def apply(initialBalance: Int) {
    new Employee(newUniqueId, initialBalance)
  }

  def newUniqueId() = {
    id += 1
    id
  }

}

object testEmployee extends App {
  val employee1 = Employee(100)
  employee1.printEmployeeDetails  //getting error, why?
  println(employee1)    // This line is printing (), why?
  val employee2 = Employee(200)
  println(employee2)    // This line is printing (), why?
}

Friends, can you help me to understand why it is behaving like this? Thanks.

A: I got it!!. The problem was in the line:
def apply(initialBalance: Int) {
    new Employee(newUniqueId, initialBalance)
}

I missed the equal sign and that is why I was missing the object link even though it was getting created. Now the change code is:
def apply(initialBalance: Int) = {
    new Employee(newUniqueId, initialBalance)
}

It is working perfectly fine now. Thanks.


text:
Q: Improve database design for online exam I am working on a multiple choice online test project here i have designed database to store result but looking for more optimized way.
Requirements:

*

*Every question have four options.

*Only one option can be selected and that needs to be stored in database.

My design:
tables:
students
  stud_id, name, email
tests
  test_id, testname, duration
questions
  que_id, question, opt1, opt2, opt3, opt4, answer, test_id
answers
  stud_id, que_id, answer
By this way answers can be stored but it increase the number of records as for every question solved by student new record will be added in answers table.
e.g.
One test consists 100 questions and 1000 students take that test, for every student there will be 100 records for each question and for 1000 students 100k records.
Is there any better way to do this where number of records will be less.

A: No, there is no better design, because the design has nothing to do with how many records will be in the tables. You will choose the same design, no matter whether you deal with ten students or ten thousand.
Your table design looks good. Don't worry about the number of records. A dbms is made to deal with large tables. And 100k records is still a small database. I wouldn't even change this design if there were billions of answers to store.

A: If you want to normalize the data, then I'd create the tables a little differently.
Your Student table looks fine.  Generally, I use a singular name for tables, rather than plural.
Student
-------
Student ID
Name
Email
...

Here's the Test table:
Test
----
Test ID
Test Name
...

We tie students to tests with a junction table.
StudentTest
-----------
Student ID
Test ID
Test Started Timestamp
Test Duration
...

The time and length of the test vary from student to student, so those columns are included on the StudentTest table.
The Question table.
Question
--------
Question ID
Question Text

And the Answer table.
Answer
------
Answer ID
Answer Text

Now here's where things get tricky.  You could assign questions to a test based on the ID, like this.
TestQuestion
------------
Test ID
Question ID

But if you do that, and someone changes the Question text after the test, then the Question ID is pointing to a different question than the question on the test.
To solve this problem, we create history tables like this:
QuestionHistory
---------------
QuestionHistory ID
Question Text

AnswerHistory
-------------
AnswerHistory ID
Answer Text

So, we create the TestQuestion table like this:
TestQuestion
------------
Test ID
QuestionHistory ID

And copy the questions as well as the answers to the history tables.
For similar reasons, we create the QuestionAnswer table like this:
QuestionAnswer
--------------
QuestionHistory ID
AnswerHistory ID
Is Correct Answer

Your code could make sure that each question has 4 possible answers.  The database allows for more or less than 4 possible answers.
Finally, we tie the student's answers to the test questions.
StudentQuestionAnswer
---------------------
Student ID
Test ID
QuestionHistory ID
AnswerHistory ID
Is Correct Answer

Yes, the Test ID column is duplicated here.  This is so you can query by the test as well as the student that took the test.
The Is Correct Answer field has a different meaning in the QuestionAnswer table and the StudentQuestionAnswer table.  In the QuestionAnswer table, the Is Correct Answer boolean points to the correct answer.  In the StudentQuestionAnswer table, the Is Correct Answer boolean signifies that the student answered the question correctly.
This should be a complete question / answer database.  You could tie tests to courses if you want.

A: Initial Response
Understanding the Data
You have done good work.  As far as the data is concerned, the design is correct, but incomplete.  There are two errors:

*

*opt1…opt4 is a repeating group, that breaks 2NF.  It must be placed in a separate table.

*

*Further, there seems to be no option name or descriptor, which is strange (what do you paint on the page, next to each radio button?)

*If you ever add a fifth option, that is now catered for; if you have questions with less than four options, that is now catered for.

*Conversely, you have a fixed set of columns, and if there are any such changes in the future, you have to change both the database and the existing code.  And the code will be horrendous (extra processing instead of direct SELECTs)

*Your answers table has no integrity.  As it stands, answers can be recorded against a question that the student was not asked, or for a test that the student did not sit.  Prevention of that type of error is ordinary fare in a Relational Database, and it is not possible in a Record Filing System.

*

*In these dark days of IT, this is a common trend.  People focus on the data values; they imagine the values in spreadsheet form, and they go directly to implementing object that contain those values.  Instead of understanding the data and what it means.

*answers(stud_id, que_id, answer) has no meaning, no integrity, unless the context of a student_test is asserted.

*The third item is not an error, because you did not give it as a requirement.  However, it seems to me that a question can be used in more than one test.  The way you have set it up, such questions will be duplicated (the whole point of a database is to Normalise it, such that there is no duplication).

*

*Of course, the consequence is an Associative Table, test_question.
Questions

By this way answers can be stored but it increase the number of records as for every question solved by student new record will be added in answers table.

Yes.  That is normal for a database.

Is there any better way to do this where number of records will be less.

For a Record Filing System, yes.  For a database, no.  Since you have tagged your question as database-design, I will assume that that is what you want.
A database is a collection of facts, not of records with related fields.  The facts are about the real world, limited to the scope of the database and app.
It is important to determine the discrete facts that we need, because subordinate facts depend on higher-order facts.  That is database design.  And we Normalise the data, as we progress, as part of one and the same exercise.  Normalisation has the purpose of eliminating duplication, otherwise you have Update Anomalies.  And we determine Relational Keys, as we progress, again as part of one and the same exercise.  Relational Keys provide the logical structure of a Relational database, ie. the logical integrity.

e.g. One test consists 100 questions and 1000 students take that test, for every student there will be 100 records for each question and for 1000 students 100k records.

Yes.  But that is expressed in ISAM record-processing terms.  In database terms, you cannot get around the fact that the database stores:

*

*facts about 100 questions

*facts about 1,000 students

*facts about 1,000 students times the 100 choices they made
You need to get your head around two things: the large number of discrete facts; and the use of compound Keys.  Both are essential to Relational databases.  If either of those are missing, or you implement them with reluctance, you will not have the integrity, power, or speed of a Relational database, you will have a pre-1970's ISAM Record Filing System.
Further, the SQL platforms, and to some degree the non-SQL platforms such as MySQL, are heavily optimised for processing sets of data (not record-by-record); heavy I/O and caching; etc.  If you implement the structures required for high concurrency, you will obtain even more performance.
Implementation
As far as the implementation is concerned, and particularly since you are concerned about performance, there are errors.  A restatement would be, the implementation should not be attempted until the data is understood and modelled correctly.
The problem across the board, is that you have added a surrogate (there is no such thing as "surrogate key", it is simply a surrogate, a physical record id). It is far to early in the modelling exercise; it hasn't progressed enough; the model is not stable, to add surrogates.

*

*Surrogates are always an additional column plus the underlying index.  Obviously that consumes resources, and has a cost on inserts and deletes.

*Surrogates do not provide row uniqueness, which is demanded in a relational database.

*The Relational Model demands that Keys are made up from the data.  Relational Keys provide row uniqueness.

*A surrogate isn't made up from the data.  Therefore it is not a Relational Key, and it does not provide any of the qualities of one.

*If a surrogate is used, it does not replace the Key, it is in addition to the Key. Which is why we evaluate the need for surrogates after, not before, modelling the data.  It is an implementation concern, not a modelling one.
Solution
Rather than going back and forth, let me provide the proposal, and you can discuss it.

*

*Student Test Data Model (Page 1 only, for those following the progression).

*If you are not used to the Notation, please be advised that every little tick, notch, and mark, the solid vs dashed lines, the square vs round corners, means something very specific.  Refer to the IDEF1X Notation.

*For test and question. I have left id columns in, but note that you will be much better off with short, meaningful codes.

*student_id is valid because both name and email are too large to migrate to the child tables.

*Please check the Verb Phrases carefully, they comprise a set of Predicates.  The remainder of the Predicates can be determined directly from the model.  If this is not clear, please ask.

*See if you can determine that this is a collection of facts, and each fact is discrete precisely because other facts depend on it; that it is not a collection of records with fields that are related.

Your answers table has no integrity.  As it stands, answers can be recorded against a question that the student was not asked, or for a test that the student did not sit.  Prevention of that type of error is ordinary fare in a Relational Database, and it is not possible in a Record Filing System.

*

*That is now prevented.  The answers table, now named student_response, now has some integrity.  A student is registered for a test in student_test, and the student_responses are constrained to student_test.
Please comment/discuss.
Response to Comments

I will add additional table subject (subject_id, subject_name) and add that subject_id in question table as FK is this okay?

Yes, by all means.  But that has consequences.  Some advice to make sure we do that properly, across the board:

*

*As explained, do not use surrogates (Record IDs) unless you absolutely have to.  Short Codes are much better for Identifiers, for both users and developers.

*

*If you would like more info on the problems related to ID columns, read this Answer.

*Subject is important.  It is the context in which (a) a question exists, and (b) a test exists.  They did exist as independent items (page 1 of the DM), but now they are subordinate to subject.  The addition substantially improves data integrity.

*The fact of a student registration and the fact of a student sitting for a test, are discrete and separate facts.

*Gratefully, that eliminated two surrogates question_id and test_id.  Short codes such as CHAR(2) are easier and more meaningful.

*Note the improvement in the table names, improved clarity.

*I have updated the Student Test Data Model (Page 2 only, for those following the progression).

*However, that exposes something (that is why we model data, paper is cheap, many drafts are normal).  If we evaluate the Predicates (readily visible in the Data Model, as detailed in the IDEF1X Notation document):
   each subject_test was taken by 0-to-n student_tests
   each student_test is [a taking of] 1 subject_test
   each student took 0-to-n student_tests
   each student_test is taken by 1 student

those Predicates are not accurate. A student can sit for a test in any subject.  Given the new subject table, I would think that we want students to be registered for subjects, and therefore student_test to be constrained to subjects that the student is registered for.

*

*If you would like to information on the important Relational concept of Predicates, and how it is used to both understand and verify the model, visit this Answer, scroll down until you find the Predicate section, and read that carefully.

*I have updated the Student Test Data Model (Page 3).  Now we have even more integrity, such that student_test is constrained to subjects that the student is registered for.  The relevant Predicates are:
  each student registered for 0-to-n student_subjects
  each student_subject is a registration of 1 student
  each subject attracted 0-to-n student_subjects
  each student_subject is an attraction of 1 subject

  each subject_test was taken by 0-to-n student_tests
  each student_test is [a taking of] 1 subject_test
  each student_subject took 0-to-n student_tests
  each student_test is taken by 1 student_subjects

*Now the data model appears to be complete.

*

*Context is everything in a database.

*The data hierarchies are plainly visible in the compounding of the Keys.

*Notice that it is the Relational Keys, in the child tables, that provide Relational Integrity with the parent tables, to every higher level (parent, grandparent) in the hierarchy.

*In case it is not obvious, notice the power of Relational Joins.  Something you cannot do with Record Filing Systems that have ID fields in every File.  Eg:
  - Join `student_response` directly to `subject` on `subject_code`, without having to navigate the two levels in-between

  - Join `student_response` directly to `student` on `student_id`, without having to navigate the two levels in-between

A: You can store the details for answer as a ~ separated record for the corresponding question id which is also a ~ separated. In this way for one student id there will be only one record. You can also decode the ans for a particular question id


text:
Q: Installing older version of Maven 2 on Ubuntu? Is there an easy way to use apt-get to install an older version of Maven 2 on Ubuntu Maverick?
I'd like to use 2.0.9.

A: Try downloading from launchpad: http://launchpadlibrarian.net/15563514/maven2_2.0.9-2_all.deb
Double-click on it and GDebi should do the rest.
This package is no longer maintained on LTS and newer versions. Be careful, I haven't tried it because I have a newer version.
Anyway, why would you use an older one?
More info here: https://launchpad.net/ubuntu/jaunty/+package/maven2


text:
Q: More space efficient than bitmap Do you have any suggestions for a data structure that occupies less space than the bitmap index for storing document ids? I have tried to illustrate how the data looks like. For each key (1,2,3,…., 100), you will have a set as a value.
I have tried to think in terms of the inverted index. But I read that bitmap is more space efficient. I have seen various works on bitmap but, I was wondering if there is any work besides that.

A: The classical answer to your question is the Elias-Fano structure. It is within half a bit per item of optimal, and does well on short lists like you have.


text:
Q: Installing phpmyadmin in Filezilla I'm making my first steps learning how to develop a Wordpress theme. I installed Wordpress in local, I designed a theme and now I'm learning how to export it to a live site.
I have the server address, the user and the password of my client. I downloaded filezilla, I logged in and I decided to make a subdirectory in his actual site to install the wordpress site. So it woud be something like this www.clientsite.com/wordpressnewsite.
The thing is that I suppose that I have to install phpMyAdmin in this subdirectory so like this I can import my database.
I downloaded phpMyAdmin, I saved all the files in my subdirectory and I created a config directory inside with all the permissions.
Now I tried to go to http://www.clientsite.com/wordpressnewsite/phpmyadmin/setup/ to continue the installation but it shows a white page without a message or something.
Do you have some recommendation?

A: Couple of things:

*

*Its likely if you use cpanel you already have phpmyadmin. its not advisable to leave it in a accessible web directory, or hackers gonna get you.

*If you have that phpmyadmin folder under your wordpress install its likely that it may not work as the htaccess file for wordpress is trying to send everything through wordpress.
In the phpmyadmin folder you could enter the following in the htaccess file.
RewriteEngine Off.


text:
Q: Obtener el nombre correspondiente al menor valor de edad Buenas tardes Amigos,
Les agradezco de antemano la ayudan que me puedan brindar, pues soy principiante en programación.
Resulta que tengo un diccionario con unos datos de nombres con sus respectivas edades y estaturas, y requiero obtener el dato de la menor EDAD y su nombre correspondiente.
Pero no he podido obtenerlo, no sé en qué estoy fallando.
for key in DATOS.values():

    if num > menor:
        num =(DATOS[key]["EDAD"])
        menor= num
        for key, num in DATOS.items():
              if  key in num:
                    Nomb=key
              print(Nomb)
   print(menor, Nomb)

A: Soy nuevo en este foro pero creo que puedo echarte una mano, suponiendo que tienes la siguiente estructura de datos este es el enfoque que yo le daría.
prueba = {"Ale":{"Edad":20},
          "Pedro":{"Edad":25},
          "Ana":{"Edad":26},
          "Raul":{"Edad":15}}

def encontrarMenor(diccionario):
    menor = 0
    for usuario in diccionario:
        if diccionario[usuario]["Edad"] < menor or not menor:
            menor = diccionario[usuario]["Edad"]
            nombre = usuario
    return(nombre,menor)

print(encontrarMenor(prueba))

Recorres el diccionario entero comprobando las edades y devolviendo el de menor edad, tenga en cuenta que en caso de que hubiera varias personas con la misma edad y quiera devolver una lista entera no podría así que lo solucionaría devolviendo una lista de los nombres y la edad de ellos.
def encontrarMenor2(diccionario):
    menor = 0
    nombres = []
    for usuario in diccionario:
        if diccionario[usuario]["Edad"] <= menor or not menor:
            menor = diccionario[usuario]["Edad"]
            nombres.append(usuario)
    return(nombres,menor)

print(encontrarMenor2(prueba))

A: Una manera muy buena de obtener el mínimo puede ser utilizar la función min, ya que está pensada para eso.
Para ello puedes combinarla con una función lambda en su argumento key que puedes modificar en función de la estructura de tu diccionario.
Ya que no has puesto la estructura que sigue tu diccionario, te pongo un par de ejemplos para que veas que puedes adaptarla a lo que necesitas:
dicc_1 = {'Juan': [20, 1.70],
          'Alvaro': [25, 1.75],
          'Elena': [22, 1.68],
          'Ana': [30, 1.73]}

menor_edad = min(dicc_1, key=lambda x: dicc_1[x][0])
menor_altura = min(dicc_1, key=lambda x: dicc_1[x][1])

print(menor_edad)  # Devuelve Juan
print(menor_altura)  # Devuelve Elena

Si quisieras en este caso obtener la edad de Juan por ejemplo, podrías poner:
print(dicc_1[menor_edad][0])  # Devuelve 20

Otro caso con un diccionario con estructura diferente:
dicc_2 = {'Juan': {'edad': 20, 'estatura': 1.70},
          'Alvaro': {'edad': 25, 'estatura': 1.75},
          'Elena': {'edad': 22, 'estatura': 1.68},
          'Ana': {'edad': 30, 'estatura': 1.73}}

menor_edad = min(dicc_1, key=lambda x: dicc_2[x]['edad'])
menor_altura = min(dicc_1, key=lambda x: dicc_2[x]['estatura'])

print(menor_edad)  # Devuelve Juan
print(menor_altura)  # Devuelve Elena

Solo tienes que adaptar la función lambda para que apunte al dato que quieres que sea el mínimo.


text:
Q: How to solve Path , file name too long while trying to publish in visual studio 2008 I am using Visual studio 2008,
I have created a C# console application as client for WCF web service, When I try to publish the client am getting the following error.
Error  105 Unable to copy file "bin\x64\Release\GameBoardWebServerServiceClient.exe.manifest" to "bin\x64\Release\app.publish\Application Files\GameBoardWebServerServiceClient_1_0_0_4\GameBoardWebServerServiceClient.exe.manifest". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.   C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets    3554
The problem is occuring here in Microsoft.Common.targets file
<!-- Copy files to publish folder -->
    <Copy
        SourceFiles=
            "@(_ApplicationManifestFinal);
            @(_DeploymentResolvedManifestEntryPoint);
            @(_DeploymentManifestFiles);
            @(ReferenceComWrappersToCopyLocal);
            @(ResolvedIsolatedComModules);
            @(_DeploymentLooseManifestFile)"
        DestinationFiles=
            "@(_ApplicationManifestFinal->'$(_DeploymentApplicationDir)%(TargetPath)');
            @(_DeploymentManifestEntryPoint->'$(_DeploymentApplicationDir)%(TargetPath)$(_DeploymentFileMappingExtension)');
            @(_DeploymentManifestFiles->'$(_DeploymentApplicationDir)%(TargetPath)$(_DeploymentFileMappingExtension)');
            @(ReferenceComWrappersToCopyLocal->'$(_DeploymentApplicationDir)%(FileName)%(Extension)$(_DeploymentFileMappingExtension)');
            @(ResolvedIsolatedComModules->'$(_DeploymentApplicationDir)%(FileName)%(Extension)$(_DeploymentFileMappingExtension)');
            @(_DeploymentLooseManifestFile->'$(_DeploymentApplicationDir)%(FileName)%(Extension)$(_DeploymentFileMappingExtension)')"
        SkipUnchangedFiles="true"
        OverwriteReadOnlyFiles="$(OverwriteReadOnlyFiles)"/>

    <Copy
        SourceFiles="@(_DeploymentManifestDependencies)"
        DestinationFiles="@(_DeploymentManifestDependencies->'$(_DeploymentApplicationDir)%(TargetPath)$(_DeploymentFileMappingExtension)')"
        SkipUnchangedFiles="true"
        OverwriteReadOnlyFiles="$(OverwriteReadOnlyFiles)"
        Condition="'%(_DeploymentManifestDependencies.DependencyType)'=='Install'"/>

    <Copy
        SourceFiles="@(_ReferenceScatterPaths)"
        DestinationFiles="@(_ReferenceScatterPaths->'$(_DeploymentApplicationDir)%(Filename)%(Extension)$(_DeploymentFileMappingExtension)')"
        SkipUnchangedFiles="true"
        OverwriteReadOnlyFiles="$(OverwriteReadOnlyFiles)"/>`

How to solve this ?
Is there any way to change the maximum size parameter or any such work around without having to reduce the filename


text:
Q: Java8: Reduce list of elements like sql group by After a stream().filter().map() on a List I have a data structure of type List<List<Object>> that looks like this:
[["1","a",20],
 ["1","b",10],
 ["2","a",10],
 ["2","b",30]]

What I want is to group by the value of the first element of the inner list, leave the middle element out and finally sum the last elements for each "group".
[["1", 30],
 ["2", 40]]

Sorry if this is obvious for some of you, but I have yet to find any example of how to achieve this. I assumed it could be done by Stream.reduce(U identity, BiFunction accumulator, BinaryOperator combiner) but so far I haven't succeeded. If someone could provide some example code for this, I believe it would be appreciated by many others too.

A: The following code may be of help:
List<List<Object>> originalList = Arrays.asList(
        Arrays.asList("1", "a", 20),
        Arrays.asList("1", "b", 10),
        Arrays.asList("2", "a", 10),
        Arrays.asList("2", "b", 30)
);

final Map<Object, Integer> collectedMap =
        originalList.stream()
                .collect(Collectors.groupingBy(
                        e -> e.get(0),
                        Collectors.summingInt(e -> (Integer) e.get(2))));

System.out.println(collectedMap);

The output is:

{1=30, 2=40}

Basically, what the code does is to group by the first value in the sublist (get(0)). Then it sums the integers by the use of summingInt. However, it groups the entire thing in a Map - if some other collection is required the stream must be slightly changed.
E.g. to collect the whole thing as a List:
final List<List<Object>> collectedList =
    collectedMap.entrySet()
             .stream()
             .map(e -> Arrays.asList(e.getKey(), e.getValue()))
             .collect(Collectors.toList());

System.out.println(collectedList);

Then, the output will be:

[[1, 30], [2, 40]]


text:
Q: Can this code be streamlined with less "with" "End With" statements>? I ask as it seems there is a better way than having a separate "With" "EndWith for each Column.
On the active sheet
For the entire Columns A1:C1 it is setting to autofit plus two blank spaces, and
for the entire Columns D1:G1 it is setting to autofit plus one blank space.
Sub AutoFitColumns()
Worksheets("TestSheet1").Activate

    With Range("A1").EntireColumn
        .AutoFit
        .ColumnWidth = .ColumnWidth + 2
    End With
    With Range("B1").EntireColumn
        .AutoFit
        .ColumnWidth = .ColumnWidth + 2
    End With
    With Range("C1").EntireColumn
        .AutoFit
        .ColumnWidth = .ColumnWidth + 2
    End With
    With Range("D1").EntireColumn
        .AutoFit
        .ColumnWidth = .ColumnWidth + 1
    End With
    With Range("E1").EntireColumn
        .AutoFit
        .ColumnWidth = .ColumnWidth + 1
    End With
    With Range("F1").EntireColumn
        .AutoFit
        .ColumnWidth = .ColumnWidth + 1
    End With
    With Range("G1").EntireColumn
        .AutoFit
        .ColumnWidth = .ColumnWidth + 1
    End With
End Sub

A: For example:
Sub AutoFitColumns()
    Dim c As Range
    For Each c In Worksheets("TestSheet1").Range("A1:G1").Cells
        With c.EntireColumn
            .AutoFit
            .ColumnWidth =  .ColumnWidth + IIf(c.Column <= 3, 2, 1)
        End With
    Next c
End Sub

A: Autofit Columns
Sub AutoFitColumns()

    Dim AutoFitProperties()
    AutoFitProperties = Array(VBA.Array("A1:C1", 2), VBA.Array("D1:G1", 1))

    With ThisWorkbook.Sheets("TestSheet1")
        Dim Afp, crg As Range
        For Each Afp In AutoFitProperties
            With .Range(Afp(0)).EntireColumn
                .AutoFit
                For Each crg In .Columns
                    crg.ColumnWidth = crg.ColumnWidth + Afp(1)
                Next crg
            End With
        Next Afp
    End With

End Sub


text:
Q: Full voice control for Mac What's an app that let's my control my Mac with voice commands, always on, with no keyboard and no mouse? I'm talking about an iMac mounted on a wall that is always listening for voice control commands.
The only app support really needed is a web browser -- I'm not asking to control photoshop with my voice or something!
But it must be a setup that never requires me to connect a keyboard or mouse, even if it crashes and needs a reboot.

A: If you want to totally control your Mac with your voice, I should strongly recommend to use dragon dictate 3 for mac from Nuance. But you need to know some Applescript to implement some user command.
You should also buy Plantronics microphone for quality based recognition.
Regards
Claude