问:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'user0_.userId' in 'field list'
I am getting Error:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'user0_.userId' in 'field list'

Please check the code and reply to me .

Step 1: creating database table

```<code>CREATE TABLE `userlogin` (
  `email` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

example:

```<code>email = mahesh@gmail.com
pwd = 1234
</code>```

step 2: entity class

```<code>package com.ims.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="userlogin")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long userId;

    @Column(name="email")
    private String email;

    @Column(name="password")
    private String password;

//setter and getter methods
</code>```

step 3: bean class

```<code>package com.ims.bean;

import org.hibernate.validator.constraints.NotEmpty;

public class LoginBean {

    @NotEmpty
    private String emailid;
    @NotEmpty
    private String password;

    public String getEmail() {
        return emailid;
    }

    public void setEmail(String email) {
        this.emailid = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
</code>```

step 4: controller class

```<code>package com.ims.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ims.bean.LoginBean;
import com.ims.entity.User;
import com.ims.service.UserService;

@Controller
public class LoginController extends BaseController{

    @Autowired
    private UserService userService;

    @RequestMapping({"/","/home"})
    public String viewHomePage(Model model){
        model.addAttribute(new LoginBean());
        return "home";
    }
</code>```

step 5: service class

```<code>package com.ims.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ims.bean.LoginBean;
import com.ims.dao.UserDao;
import com.ims.entity.User;

@Service
@Transactional(propagation=Propagation.REQUIRED)
public class UserService {

    @Autowired
    private UserDao userDao;

    public boolean isUserExists(LoginBean loginBean){
        User user = userDao.findUser(loginBean);
        return user != null ? true: false;
    }

    public User findUser(LoginBean loginBean){
        User user = userDao.findUser(loginBean);
        return user;
    }
</code>```

step 6  dao class

```<code>package com.ims.dao;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ims.bean.LoginBean;
import com.ims.entity.User;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public User findUser(LoginBean loginBean){
         User user = null;
         Session session = sessionFactory.openSession();
         List<User> users = session.createQuery("from User where email = '"+loginBean.getEmail()+"' and password='"+loginBean.getPassword()+"'").list();
         if(users != null){
             user = users.get(0);
         }
        session.close();
         return user;
    }
</code>```

step 7  hibermate configuration file

```<code><hibernate-configuration>
  <session-factory>
    <!-- We're using MySQL database so the dialect needs to MySQL as well-->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

  </session-factory>
</hibernate-configuration>
</code>```

step 8: applicationcontext file

```<code><tx:annotation-driven />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://localhost:3306/agiledb" p:username="root"
        p:password="admin"
        p:initialSize="5"
        p:maxActive="10"
        p:maxWait="-1"
        p:testOnBorrow="true"
        p:validationQuery="select 1 as dbcp_connection_test"
        p:minIdle="1"  />

        <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource" p:configLocation="/WEB-INF/hibernate.cfg.xml"
        p:packagesToScan="com.ims.entity" />

        <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean>

</beans>
</code>```

step 9: project name - servlet.xml

```<code><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
</bean>
</code>```

答:
```<code>java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
</code>```

Exception is occurring because your query criteria list() is returning empty users list, and you are trying to access the 0 index.

Body:
I am getting Error:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'user0_.userId' in 'field list'

Please check the code and reply to me .

Step 1: creating database table

CREATE TABLE `userlogin` (
  `email` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

example:

email = mahesh@gmail.com
pwd = 1234

step 2: entity class

package com.ims.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="userlogin")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long userId;

    @Column(name="email")
    private String email;

    @Column(name="password")
    private String password;

//setter and getter methods

step 3: bean class

package com.ims.bean;

import org.hibernate.validator.constraints.NotEmpty;

public class LoginBean {

    @NotEmpty
    private String emailid;
    @NotEmpty
    private String password;

    public String getEmail() {
        return emailid;
    }

    public void setEmail(String email) {
        this.emailid = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

step 4: controller class

package com.ims.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ims.bean.LoginBean;
import com.ims.entity.User;
import com.ims.service.UserService;

@Controller
public class LoginController extends BaseController{

    @Autowired
    private UserService userService;

    @RequestMapping({"/","/home"})
    public String viewHomePage(Model model){
        model.addAttribute(new LoginBean());
        return "home";
    }

step 5: service class

package com.ims.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ims.bean.LoginBean;
import com.ims.dao.UserDao;
import com.ims.entity.User;

@Service
@Transactional(propagation=Propagation.REQUIRED)
public class UserService {

    @Autowired
    private UserDao userDao;

    public boolean isUserExists(LoginBean loginBean){
        User user = userDao.findUser(loginBean);
        return user != null ? true: false;
    }

    public User findUser(LoginBean loginBean){
        User user = userDao.findUser(loginBean);
        return user;
    }

step 6  dao class

package com.ims.dao;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.ims.bean.LoginBean;
import com.ims.entity.User;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public User findUser(LoginBean loginBean){
         User user = null;
         Session session = sessionFactory.openSession();
         List<User> users = session.createQuery("from User where email = '"+loginBean.getEmail()+"' and password='"+loginBean.getPassword()+"'").list();
         if(users != null){
             user = users.get(0);
         }
        session.close();
         return user;
    }

step 7  hibermate configuration file

<hibernate-configuration>
  <session-factory>

    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

  </session-factory>
</hibernate-configuration>

step 8: applicationcontext file

<tx:annotation-driven />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://localhost:3306/agiledb" p:username="root"
        p:password="admin"
        p:initialSize="5"
        p:maxActive="10"
        p:maxWait="-1"
        p:testOnBorrow="true"
        p:validationQuery="select 1 as dbcp_connection_test"
        p:minIdle="1"  />

        <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource" p:configLocation="/WEB-INF/hibernate.cfg.xml"
        p:packagesToScan="com.ims.entity" />

        <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean>

</beans>

step 9: project name - servlet.xml

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
</bean>

Body:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

Exception is occurring because your query criteria list() is returning empty users list, and you are trying to access the 0 index.


来源: stackexchange

问:
Set Report Size on Crystal report
i am using windows 10.

i am trying to create a report for continuous form (Half Of A4), i set manually from device and printer, so i set printer server like this.

then i change page setup on CR to vpc (name of paper where i create on printer server)  like this..

then i tried it with different way :

i preview the report, than print.

with out run my application. the print result was great. just like i want.

i run my application, preview my report with Crystal REport viewer tools, but my report become landscape. not protrait.

see...

what must i do?

答:
yes, after a week,finally i found the answer, we need to set default paper to our customer paper.

just that.

ContentLicense: CC BY-SA 3.0

Title: Set Report Size on Crystal report


问:
How to accept SOH character from TextField in JAVAFx
I have written  simple GUI screen that actually contains a JavaFx textField where the user enters a string and that String I have to pass to TCP client.

Now the problem is user enters a string that contains SOH as the delimiter.
SOH is nothing but "\u001". But when the user enters a String that contains this delimiters then it is removed and only the simple plain text is retrieved. How can I eliminate this. This unique character is very important for me.
For example my string is as follows:

```<code>8=FIX.4.2\u001 9=9 \u001 35=A \u001 34=1\u001 49=TTDS68AP
</code>```

Observer the above String where I have the \u001 character representing SOH. But when I entered this String in the TextField then the result is like:

```<code>8=FIX.4.29=9135=A34=149=TTDS68AP
</code>```

How can I get the SOH character too from the Text Field?

答:
Try adding the your encoding as argument.

```<code>System.setProperty("file.encoding", "yourEncoding");
</code>```

I think UTF-8 should work.

Body:
I have written  simple GUI screen that actually contains a JavaFx textField where the user enters a string and that String I have to pass to TCP client.

Now the problem is user enters a string that contains SOH as the delimiter.
SOH is nothing but "\u001". But when the user enters a String that contains this delimiters then it is removed and only the simple plain text is retrieved. How can I eliminate this. This unique character is very important for me.
For example my string is as follows:

8=FIX.4.2\u001 9=9 \u001 35=A \u001 34=1\u001 49=TTDS68AP

Observer the above String where I have the \u001 character representing SOH. But when I entered this String in the TextField then the result is like:

8=FIX.4.29=9135=A34=149=TTDS68AP

How can I get the SOH character too from the Text Field?

Body:
Try adding the your encoding as argument.

System.setProperty("file.encoding", "yourEncoding");

I think UTF-8 should work.


问:
ng-class not behaving properly
i have below lines of code with ng-repeat and ng-class:

```<code><div ng-repeat="invitee in invitedCollaborators" class="invite-collabs-emails">
     <input type="text" id="email-{{$index}}" validate-email="email.invalid" ng-class="{'collabs-email-required' : ((invitedCollaborators[{{$index}}].email == null || invitedCollaborators[{{$index}}].email ==''))}" class="collabs-email" placeholder="Enter email here" ng-required="true" ng-model="invitee.email"/>
     <a href ng-click="removeInvitee($index)" class="delete-invite">
       <img src="delete-invite.png">
     </a>
    </div>
<a href class="add-another-collabs-link" ng-click="addAnotherCollaborator()">Add another</a>
</code>```

ng-repeat is repeating the input box when we are adding another. ng-class has this conditional statement to add collabs-email-required class which adds red border color to show that input is required.

Now problem im facing is that when i add more than one input box and enter valid email in all of them and then remove one of the input box, the other input boxes show me red border color, even though they have valid email ids.

I tried adding the ternary operator in ng-class to make it work:

```<code>ng-class="{'collabs-email-required' : ((invitedCollaborators[{{$index}}].email == null || invitedCollaborators[{{$index}}].email =='')) ? 'collabs-email'}
</code>```

Here above problem gets resolved but then the input box doesnt show red colored border when it gets out of focus. It should have the red border when its out of focus and not filled with valid id (or not filled at all).

What condition am i missing? Please help. Thanks

答:
try this  </p>

```<code>  <div ng-repeat="invitee in invitedCollaborators" class="invite-collabs-emails">
         <input type="text" id="email-{{$index}}" validate-email="email.invalid" ng-class="{'collabs-email-required' : ((invitedCollaborators[$index].email == null || invitedCollaborators[$index].email ==''))}" class="collabs-email" placeholder="Enter email here" ng-required="true" ng-model="invitee.email"/>
         <a href ng-click="removeInvitee($index)" class="delete-invite">
           <img src="delete-invite.png">
         </a>
        </div>
    <a href class="add-another-collabs-link" ng-click="addAnotherCollaborator()">Add another</a>
</code>```

Title: ng-class not behaving properly

Body:
i have below lines of code with ng-repeat and ng-class:

     <input type="text" id="email-{{$index}}" validate-email="email.invalid" ng-class="{'collabs-email-required' : ((invitedCollaborators[{{$index}}].email == null || invitedCollaborators[{{$index}}].email ==''))}" class="collabs-email" placeholder="Enter email here" ng-required="true" ng-model="invitee.email"/>

Add another

ng-repeat is repeating the input box when we are adding another. ng-class has this conditional statement to add collabs-email-required class which adds red border color to show that input is required.

Now problem im facing is that when i add more than one input box and enter valid email in all of them and then remove one of the input box, the other input boxes show me red border color, even though they have valid email ids.

I tried adding the ternary operator in ng-class to make it work:

ng-class="{'collabs-email-required' : ((invitedCollaborators[{{$index}}].email == null || invitedCollaborators[{{$index}}].email =='')) ? 'collabs-email'}

Here above problem gets resolved but then the input box doesnt show red colored border when it gets out of focus. It should have the red border when its out of focus and not filled with valid id (or not filled at all).

What condition am i missing? Please help. Thanks

Body:
try this

  <div ng-repeat="invitee in invitedCollaborators" class="invite-collabs-emails">
         <input type="text" id="email-{{$index}}" validate-email="email.invalid" ng-class="{'collabs-email-required' : ((invitedCollaborators[$index].email == null || invitedCollaborators[$index].email ==''))}" class="collabs-email" placeholder="Enter email here" ng-required="true" ng-model="invitee.email"/>
         <a href ng-click="removeInvitee($index)" class="delete-invite">
           <img src="delete-invite.png">
         </a>
        </div>
    <a href class="add-another-collabs-link" ng-click="addAnotherCollaborator()">Add another</a>


问:
How to know that queue is removed?
I create a queue:

```<code>        _channel = rmqConnection.CreateModel();
        _channel.QueueDeclare("myqueue", false, false, false, null);
        _channel.BasicAcks += _channel_BasicAcks;
        _channel.BasicNacks += _channel_BasicNacks;
        _channel.BasicRecoverOk += _channel_BasicRecoverOk;
        _channel.BasicReturn += _channel_BasicReturn;
        _channel.CallbackException += _channel_CallbackException;
        _channel.FlowControl += _channel_FlowControl;
        _channel.ModelShutdown += _channel_ModelShutdown;
</code>```

and then i want to subscribe on event when (and if) queue will remove.
So, when i manual remove a queue for test this: i can not handle event.

How can i handle event about queue remove\destroy?

P.S. add some new code:

```<code>        var consumer = new EventingBasicConsumer(_channel);
        consumer.Received += OnMessageRecieved;
        consumer.ConsumerCancelled += Consumer_ConsumerCancelled;
        consumer.Registered += Consumer_Registered;
        consumer.Shutdown += Consumer_Shutdown;
        consumer.Unregistered += Consumer_Unregistered;
        _channel.BasicConsume(SharebleConst.RmqQueueName, false, consumer);
</code>```

When queue created, Consumer_Registered rises.
When i remove queue, Consumer_ConsumerCancelled rises

答:
There is not a way to get notified if a queue is deleted.

You could implement your own tool to do that, using a notification exchange and send a message each time you create or destroy a queue.

or in genral, send changing status messages

Title: How to know that queue is removed?

Body:
I create a queue:

        _channel = rmqConnection.CreateModel();
        _channel.QueueDeclare("myqueue", false, false, false, null);
        _channel.BasicAcks += _channel_BasicAcks;
        _channel.BasicNacks += _channel_BasicNacks;
        _channel.BasicRecoverOk += _channel_BasicRecoverOk;
        _channel.BasicReturn += _channel_BasicReturn;
        _channel.CallbackException += _channel_CallbackException;
        _channel.FlowControl += _channel_FlowControl;
        _channel.ModelShutdown += _channel_ModelShutdown;

and then i want to subscribe on event when (and if) queue will remove.
So, when i manual remove a queue for test this: i can not handle event.

How can i handle event about queue remove\destroy?

P.S. add some new code:

        var consumer = new EventingBasicConsumer(_channel);
        consumer.Received += OnMessageRecieved;
        consumer.ConsumerCancelled += Consumer_ConsumerCancelled;
        consumer.Registered += Consumer_Registered;
        consumer.Shutdown += Consumer_Shutdown;
        consumer.Unregistered += Consumer_Unregistered;
        _channel.BasicConsume(SharebleConst.RmqQueueName, false, consumer);

When queue created, Consumer_Registered rises.
When i remove queue, Consumer_ConsumerCancelled rises


问:
bootstrap slide show text is not displayed
I am developing a slideshow image with text for my home page.image is working properly but the text is not displaying. I used bootstrap with PHP and mysqli I tried the code below I pasted it. please go through the coding and find the good solution for me why the text is not displaying. please fix this problem</p>

```<code> <?php  include("includes/db.php");  ?>
<div class="main-slider-area home-4-main-slaider-area entire-home-main-slider home-5-main-slaider-area">
                    <!-- Main Slider -->

                        <div class="main-slider">
                            <div class="slider">

                                <div id="mainSlider" class="nivoSlider slider-image">
                                               <?php

                                                $get_slides = "select * from slider LIMIT 0,1";

                                                $run_slides = mysqli_query($con,$get_slides);

                                                while($row_slides=mysqli_fetch_array($run_slides)){

                                                    $slide_name = $row_slides['slide_name'];
                                                    $slide_text = $row_slides['slide_text'];

                                                    $slide_url = $row_slides['slide_url'];

                                                    echo "

                                                        <div class='item active'>

                                                        <a><img src='img/slider/$slide_name' ></a>

                                                        </div>

                                                        ";

                                                ?>

                                                <?php

                                                $get_slides = "select * from slider LIMIT 1,3 ";

                                                $run_slides = mysqli_query($con,$get_slides);

                                                while($row_slides = mysqli_fetch_array($run_slides)) {

                                                    $slide_name = $row_slides['slide_name'];
                                                    $slide_text = $row_slides['slide_text'];

                                                    $slide_url = $row_slides['slide_url'];

                                                    echo "

                                                        <div class='item'>

                                                        <a><img src='img/slider/$slide_name' alt='main slider' title='#htmlcaption1' ></a>

                                                        </div>

                                                        ";

                                                ?>

                                </div>

                                <!-- Slider Caption One -->
                                <div id="htmlcaption1" class="nivo-html-caption slider-caption-1">
                                    <div class="slider-progress"></div>
                                    <div class="slide-text">
                                        <div class="middle-text">
                                            <div class="cap-dec">
                                                <h1 class="cap-dec wow zoomInRight" data-wow-duration="1.1s" data-wow-delay="0s"><?php $slide_text; ?></h1>

                                            </div>
                                            <div class="cap-readmore wow zoomInRight" data-wow-duration=".9s" data-wow-delay=".5s">
                                                <a href="#"><?php $slide_url; ?></a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- Slider Caption Two -->
        <?php } }?>
                            </div>
                        </div><!-- End Main Slider -->
                    </div><!-- End Main Slider Area -->
</code>```

答:
It's because you are missing to  print $slider_text you have to print it within the
 which holds  image  .

```<code><div class="main-slider">
                        <div class="slider">

                            <div id="mainSlider" class="nivoSlider slider-image">
                                           <?php

                                            $get_slides = "select * from slider LIMIT 0,1";

                                            $run_slides = mysqli_query($con,$get_slides);

                                            while($row_slides=mysqli_fetch_array($run_slides)){

                                                $slide_name = $row_slides['slide_name'];
                                                $slide_text = $row_slides['slide_text'];

                                                $slide_url = $row_slides['slide_url'];

                                                echo "

                                                    <div class='item active'>

                                                    <a><img src='img/slider/$slide_name' ></a><p>$slider_text</p>

                                                    </div>";// here i print the $slider_text
  </div>
                                    </div>
                                </div>
</code>```

Body:
I am developing a slideshow image with text for my home page.image is working properly but the text is not displaying. I used bootstrap with PHP and mysqli I tried the code below I pasted it. please go through the coding and find the good solution for me why the text is not displaying. please fix this problem

 <?php  include("includes/db.php");  ?>

                                               <?php

                                                $get_slides = "select * from slider LIMIT 0,1";

                                                $run_slides = mysqli_query($con,$get_slides);

                                                while($row_slides=mysqli_fetch_array($run_slides)){

                                                    $slide_name = $row_slides['slide_name'];
                                                    $slide_text = $row_slides['slide_text'];

                                                    $slide_url = $row_slides['slide_url'];

                                                    echo "

                                                        ";

                                                ?>

                                                <?php

                                                $get_slides = "select * from slider LIMIT 1,3 ";

                                                $run_slides = mysqli_query($con,$get_slides);

                                                while($row_slides = mysqli_fetch_array($run_slides)) {

                                                    $slide_name = $row_slides['slide_name'];
                                                    $slide_text = $row_slides['slide_text'];

                                                    $slide_url = $row_slides['slide_url'];

                                                    echo "

                                                        ";

                                                ?>

<?php $slide_text; ?>

                                                <?php $slide_url; ?>

        <?php } }?>

Body:
It's because you are missing to  print $slider_text you have to print it within the <div> which holds  image  .

<div class="main-slider">
                        <div class="slider">

                            <div id="mainSlider" class="nivoSlider slider-image">
                                           <?php

                                            $get_slides = "select * from slider LIMIT 0,1";

                                            $run_slides = mysqli_query($con,$get_slides);

                                            while($row_slides=mysqli_fetch_array($run_slides)){

                                                $slide_name = $row_slides['slide_name'];
                                                $slide_text = $row_slides['slide_text'];

                                                $slide_url = $row_slides['slide_url'];

                                                echo "

                                                    <div class='item active'>

                                                    <a><img src='img/slider/$slide_name' ></a><p>$slider_text</p>

                                                    </div>";// here i print the $slider_text
  </div>
                                    </div>
                                </div>


问:
Can't import Divi layouts in Wordpress
Trying to import Divi layouts (.json files)
Getting this error:

```<code>This file cannot be imported. It may be caused by file_uploads being
disabled in your php.ini. It may also be caused by post_max_size or/and
upload_max_filesize being smaller than file selected. Please increase
it or transfer more substantial data at the time.
</code>```

This is not the case, however as I don't have a limit on either and I can upload anywhere else within my WP installation.

Does anyone have any idea what else would cause this error?

答:
I had the same issue.I googled and found the solution below.(Apology for not having a proper explanation!)

Solution:
Create a new file php.ini with the following text & save in website's root directory and it's done.

```<code>file_uploads = On
upload_max_filesize = 100M
post_max_size = 100M
</code>```

Title: Can't import Divi layouts in Wordpress

Body:
Trying to import Divi layouts (.json files)
Getting this error:

This file cannot be imported. It may be caused by file_uploads being
disabled in your php.ini. It may also be caused by post_max_size or/and
upload_max_filesize being smaller than file selected. Please increase
it or transfer more substantial data at the time.

This is not the case, however as I don't have a limit on either and I can upload anywhere else within my WP installation.

Does anyone have any idea what else would cause this error?

Body:
I had the same issue.I googled and found the solution below.(Apology for not having a proper explanation!)

Solution:
Create a new file php.ini with the following text & save in website's root directory and it's done.

file_uploads = On
upload_max_filesize = 100M
post_max_size = 100M


问:
Input date prefilled with current year
I have input date field and I want to prefilled it with current year only, so that whenever user want to update that field, he/she don't have to specify year each time, the field always prefilled with current year and user will edit date and month. If user want to edit year it is possible.

```<code><input type="date" />
</code>```

It is about year only, what i want to do is when specifically editing with keyboard, user shouldn't type year everytime, because in most of the cases the year will be current year.

答:
Best i could come up with is setting both min and max date. That way browser knows year can not be changed and are therefore prefilled.

```<code><input type="date" min="2017-01-01" max="2017-12-31">
</code>```

But then you are not able to change the year which is not what you want...

Otherwise I don't think this would be possible. But maybe you shouldn't bother so much. ppl might click the arrow button to select date anyway.
that is only two clicks away, the current year will be selected when clicking on a date. An alternativ is to click opt/alt + down key on chrome for Mac to get the date picker.

Title: Input date prefilled with current year

Body:
I have input date field and I want to prefilled it with current year only, so that whenever user want to update that field, he/she don't have to specify year each time, the field always prefilled with current year and user will edit date and month. If user want to edit year it is possible.

<input type="date" />

It is about year only, what i want to do is when specifically editing with keyboard, user shouldn't type year everytime, because in most of the cases the year will be current year.

Body:
Best i could come up with is setting both min and max date. That way browser knows year can not be changed and are therefore prefilled.

<input type="date" min="2017-01-01" max="2017-12-31">

But then you are not able to change the year which is not what you want...

Otherwise I don't think this would be possible. But maybe you shouldn't bother so much. ppl might click the arrow button to select date anyway.
that is only two clicks away, the current year will be selected when clicking on a date. An alternativ is to click opt/alt + down key on chrome for Mac to get the date picker.


问:
Why the Thread Executer itself is still in memory after being shutdown?
Using Java and App Server I deploy application that has a thread executer.

During un-deploy I request the executer to shutdown. This successfully cancels all the tasks. However via VisualVM I can still see a thread that represents the executer itself and it is in the wait sate. I don't keep any references to the executer as the whole application get undeployed. So if i repeat the deployment-undeployment cycle multiple times I can see how the threads number grows.

How do I get rid of them?

UPDATE:

code example

here is the code:

```<code>public void startScheduler()
{
    if (scheduledExecutor == null)
    {
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("My ScheduledExecutor"));
        processFuture = scheduledExecutor.scheduleAtFixedRate(new Runnable()
            {
                @Override
                public void run()
                {
                    startProcessor();
                }
            }, 0, 84600, TimeUnit.SECONDS);
    }
}

public void stopScheduler()
{

    if (processFuture != null)
    {
        processFuture.cancel(true);
        processFuture = null;
    }

    if (scheduledExecutor != null)
    {
        try
        {
            scheduledExecutor.shutdownNow();
            scheduledExecutor.awaitTermination(10, TimeUnit.SECONDS);
        }
        catch (InterruptedException ignored)
        {}
        finally
        {
            scheduledExecutor = null;
        }
    }

}
</code>```

答:
Could you please elaborate what you mean with "a thread that represents the executer itself". What is it's name/id/threadgroup? I don't think executor service creates such a thread.

Executors create new threads (using the configurable ThreadFactory). A Thread automatically inherits some properties of its parent, that is the Thread.currentThread(). The most problematic part of this behavior in a web application scenario with deploy/undeploy cycles however is the Thread's ContextClassLoader, which is inherited from the parent's thread. If your ContextClassLoader holds on to classes from within your web application archive, then the spawned Executors Thread will also have a reference to this ClassLoader. If the code which is executed by the Executor has e.g. ThreadLocals with classes from the WebappClassLoader, you may experience a ClassLoader leak problem.

ContentLicense: CC BY-SA 2.5

Body:
Using Java and App Server I deploy application that has a thread executer.

During un-deploy I request the executer to shutdown. This successfully cancels all the tasks. However via VisualVM I can still see a thread that represents the executer itself and it is in the wait sate. I don't keep any references to the executer as the whole application get undeployed. So if i repeat the deployment-undeployment cycle multiple times I can see how the threads number grows.

How do I get rid of them?

UPDATE:

code example

here is the code:

public void startScheduler()
{
    if (scheduledExecutor == null)
    {
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("My ScheduledExecutor"));
        processFuture = scheduledExecutor.scheduleAtFixedRate(new Runnable()
            {
                @Override
                public void run()
                {
                    startProcessor();
                }
            }, 0, 84600, TimeUnit.SECONDS);
    }
}

public void stopScheduler()
{

    if (processFuture != null)
    {
        processFuture.cancel(true);
        processFuture = null;
    }

    if (scheduledExecutor != null)
    {
        try
        {
            scheduledExecutor.shutdownNow();
            scheduledExecutor.awaitTermination(10, TimeUnit.SECONDS);
        }
        catch (InterruptedException ignored)
        {}
        finally
        {
            scheduledExecutor = null;
        }
    }

}


问:
SQL Server Query for account statement
How can I generate last three transactions from the below table?

```<code>Date        Tran        dr  cr  total
-------------------------------------
2017-04-13
2017-07-15
2017-07-15
2017-10-17
2017-10-17 abc              10  10
2017-11-12 def              10  20
2017-11-12 ghi          5       15
</code>```

I'm using SQL Server 2012

答:
if your requirement is to get the 3 transactions with the latest date. you can use either of the following.

Simple Order by :

```<code>select
top 3
* from YourTable
where isnull(Tran,'')<>''
order by [Date] desc
</code>```

using Row Number

```<code>;with cte
as
(
  select
   seqno = row_number() over(order by [date] desc),
  *
  from YourTable
where isnull(Tran,'')<>''
 )
 select
 * from cte
 where SeqNo <=3
order by SeqNo desc
</code>```

Title: SQL Server Query for account statement

Body:
How can I generate last three transactions from the below table?

Date        Tran        dr  cr  total
-------------------------------------
2017-04-13
2017-07-15
2017-07-15
2017-10-17
2017-10-17 abc              10  10
2017-11-12 def              10  20
2017-11-12 ghi          5       15

I'm using SQL Server 2012

Body:
if your requirement is to get the 3 transactions with the latest date. you can use either of the following.

Simple Order by :

select
top 3
* from YourTable
where isnull(Tran,'')<>''
order by [Date] desc

using Row Number

;with cte
as
(
  select
   seqno = row_number() over(order by [date] desc),
  *
  from YourTable
where isnull(Tran,'')<>''
 )
 select
 * from cte
 where SeqNo <=3
order by SeqNo desc


问:
import pyodbc not working in eclipse
I am new to python..
I am not able to import pyodbc
I am getting an error in eclipse (just for this import)
i install pyodbc

```<code>C:\Users\app_rahavm>pip install pyodbc
Requirement already satisfied: pyodbc in c:\users\app_rahavm\appdata\local\programs\python\python36-32\lib\site-packages
</code>```

python interpeter is also updated with the path:

and still i am getting

```<code>Unresolved import: pyodbc
</code>```

when i write this:

```<code>import pyodbc
</code>```

i also see this package under packages

click here to see

any ideas?

another thing i notice is that each install package has it's own .dist-info lib but i have only dist-info file which does not hav python files inside
see image here see content of lib here

答: Try pip freeze command to check whether the module is really present in the list of installed modules or not.

Title: import pyodbc not working in eclipse

Body:
I am new to python..
I am not able to import pyodbc
I am getting an error in eclipse (just for this import)
i install pyodbc

C:\Users\app_rahavm>pip install pyodbc
Requirement already satisfied: pyodbc in c:\users\app_rahavm\appdata\local\programs\python\python36-32\lib\site-packages

python interpeter is also updated with the path:

and still i am getting

Unresolved import: pyodbc

when i write this:

import pyodbc

i also see this package under packages

click here to see

any ideas?

another thing i notice is that each install package has it's own .dist-info lib but i have only dist-info file which does not hav python files inside
see image here see content of lib here


问:
Test if button selected based
I need to locate a button , which may or may not be selected.

I first find the xpath to the button, check is its selected, it is failing in this check   "Unable to locate element: {"method":"tag name","selector":"input"}"

What should my boolean line check be ?

```<code>  WebElement element =  driver.findElement(By.xpath("//i[contains(@class,'i-icon--plus-18-movie')]"));

    boolean isChecked = element.findElement(By.tagName("input")).isSelected();
        if(isChecked){
            System.out.println("is checked");
                 element.click();
        }

<age-question-button class="ng-scope ng-isolate-scope" state="qc.answer[question.name]" icon="plus-18-movie" active-text="The Customer is over 18" inactive-text="The Customer is NOT over 18" ng-repeat="question in qc.questionsList track by question.name" audit="cc.utils.audit(qc.answer[question.name] ? question.auditInactive : question.auditActive)">
<label class="c-option u-p-0 u-ml-md u-pull-left" tooltip-append-to-body="true" uib-tooltip="The Customer is NOT over 18">
<input class="ng-untouched ng-valid ng-dirty ng-valid-parse" ng-model="state" ng-change="audit()" style="" type="checkbox">
<i class="c-option__button i-icon i-icon--plus-18-movie"></i>
</label>
</age-question-button>
</code>```

答:
Please try to avoid multiple class in same path.
You can use like below

```<code>WebElement elem = driver.findElement(By.className("ng-isolate-scope"));
WebElement element =  elem.findElement(By.className("ng-valid-parse"));

boolean isChecked = element.findElement(By.tagName("input")).isSelected();
if(isChecked){
    System.out.println("is checked");
    element.click();
}
</code>```

IF you have multiple classes with same name you can use list and desired Index of that element.

```<code>WebElement elem = driver.findElement(By.className("ng-isolate-scope"));
List<WebElement> element =  elem.findElements(By.className("ng-valid-parse"));

boolean isChecked = element.get(indexOfyourdesiredELement).findElement(By.tagName("input")).isSelected();
if(isChecked){
       System.out.println("is checked");
       element.get(indexOfyourdesiredELement).click();
}
</code>```

You can also write like

```<code>boolean isChecked =  element.findElement(By.cssSelector("input[type='checkbox']")).isSelected();
</code>```

EDIT: Here is the updated solution . It will click on the checkbox if it is checked. You can reverse the logic by yourself.

```<code>WebElement element = driver.findElement(By.tagName("age-question-button"));
boolean isChecked =  element.findElement(By.cssSelector("input[type='checkbox']")).isSelected();
if(isChecked){
    System.out.println("is checked");
    element.click();
}
</code>```

If multiple age-question-button question are there follow this.

```<code>List<WebElement> element = driver.findElements(By.tagName("age-question-button"));

    for(int i = 0 ; i< element.size() ; i++){
        boolean isChecked =  element.get(i).findElement(By.cssSelector("input[type='checkbox']")).isSelected();
        if(isChecked){
              System.out.println("is checked and it will click on checkbox if it is checked");

               element.get(i).click();
        }
    }
</code>```

Title: Test if button selected based

Body:
I need to locate a button , which may or may not be selected.

I first find the xpath to the button, check is its selected, it is failing in this check   "Unable to locate element: {"method":"tag name","selector":"input"}"

What should my boolean line check be ?

  WebElement element =  driver.findElement(By.xpath("//i[contains(@class,'i-icon--plus-18-movie')]"));

    boolean isChecked = element.findElement(By.tagName("input")).isSelected();
        if(isChecked){
            System.out.println("is checked");
                 element.click();
        }

<age-question-button class="ng-scope ng-isolate-scope" state="qc.answer[question.name]" icon="plus-18-movie" active-text="The Customer is over 18" inactive-text="The Customer is NOT over 18" ng-repeat="question in qc.questionsList track by question.name" audit="cc.utils.audit(qc.answer[question.name] ? question.auditInactive : question.auditActive)">

<input class="ng-untouched ng-valid ng-dirty ng-valid-parse" ng-model="state" ng-change="audit()" style="" type="checkbox">

</age-question-button>

Body:
Please try to avoid multiple class in same path.
You can use like below

WebElement elem = driver.findElement(By.className("ng-isolate-scope"));
WebElement element =  elem.findElement(By.className("ng-valid-parse"));

boolean isChecked = element.findElement(By.tagName("input")).isSelected();
if(isChecked){
    System.out.println("is checked");
    element.click();
}

IF you have multiple classes with same name you can use list and desired Index of that element.

WebElement elem = driver.findElement(By.className("ng-isolate-scope"));
List<WebElement> element =  elem.findElements(By.className("ng-valid-parse"));

boolean isChecked = element.get(indexOfyourdesiredELement).findElement(By.tagName("input")).isSelected();
if(isChecked){
       System.out.println("is checked");
       element.get(indexOfyourdesiredELement).click();
}

You can also write like

boolean isChecked =  element.findElement(By.cssSelector("input[type='checkbox']")).isSelected();

EDIT: Here is the updated solution . It will click on the checkbox if it is checked. You can reverse the logic by yourself.

WebElement element = driver.findElement(By.tagName("age-question-button"));
boolean isChecked =  element.findElement(By.cssSelector("input[type='checkbox']")).isSelected();
if(isChecked){
    System.out.println("is checked");
    element.click();
}

If multiple age-question-button question are there follow this.

List<WebElement> element = driver.findElements(By.tagName("age-question-button"));

    for(int i = 0 ; i< element.size() ; i++){
        boolean isChecked =  element.get(i).findElement(By.cssSelector("input[type='checkbox']")).isSelected();
        if(isChecked){
              System.out.println("is checked and it will click on checkbox if it is checked");

               element.get(i).click();
        }
    }


问:
How can I scale the label size of ggplot2 plots in rmarkdown
Hello I am generating report with rmarkdown
I decided to use ggplot2 graphs as it seems that knitr rmarkdown ggplot2 works better together.

I'd like to globally increase the axis labels, tick label, title of my ggplot2 plots in the html_notebook document rmarkdown::render'ed.

Can I do this in the yaml or by setting something in a global chunk option ?

答:
You could use theme_update() in the setup chunk of your rmarkdown document to modify the active theme, overwriting the defaults for all subsequent plots. For example:

```<code>```{r setup, include=FALSE}
library(ggplot2)
theme_update(# axis labels
             axis.title = element_text(size = 30),
             # tick labels
             axis.text = element_text(size = 20),
             # title
             title = element_text(size = 50))

```
</code>```

Body:
You could use theme_update() in the setup chunk of your rmarkdown document to modify the active theme, overwriting the defaults for all subsequent plots. For example:

```{r setup, include=FALSE}
library(ggplot2)
theme_update(# axis labels
             axis.title = element_text(size = 30),
             # tick labels
             axis.text = element_text(size = 20),
             # title
             title = element_text(size = 50))

```


问:
Can you remove Identity from a primary key with Entity Framework 6?
I created a table via entity framework code-first with a primary key set to auto increment, but now I want to remove that auto-incrementing from the column.  I've tried doing that with both fluent API:

    public class ProductTypeMap: EntityTypeConfiguration<ProductType>
    {
        public ProductTypeMap()
        {
            // This is an enum effectively, so we need fixed IDs
            Property(x => x.ProductTypeId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }

    }
```
<p>And an annotation:</p>
<pre class="lang-cs prettyprint-override"><code>    public class ProductType
    {
        [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ProductTypeId { get; set; }
        public string ProductTypeName { get; set; }

    }
</code>```

And in both cases they produce the same migration code:

    public partial class removeproducttypeidentity : DbMigration
    {
        public override void Up()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }

        public override void Down()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: true));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }
    }
```
<p>However, when I run that migration on the database, the Identity Specification is not removed from the SQL Server 2008 database table?</p>
<p>I also tried explicitly turning off the Identity in the migration as follows, but that didn't do it either:</p>
<pre class="lang-cs prettyprint-override"><code>AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: false));
</code>```

Is there another way to tell SQL to remove the Identity?

答:
You can not use ALTER COLUMN to set whether a column is an identity column (How to alter column to identity(1,1)).

Instead, you have to:

(backup DB)

CREATE TMP_table with columns of original table, but ID column set to identity: false

SET IDENTITY_INSERT [TMP_Table] ON

copy data from original to TMP table

SET IDENTITY_INSERT [TMP_Table] OFF

DROP original table

Rename TMP_table to original table name (EXECUTE sp_rename)

Tip: change the column in SQL Management Studio and inspect the emitted script (SQL SERVER – Add or Remove Identity Property on Column).

ContentLicense: CC BY-SA 4.0

Body:
I created a table via entity framework code-first with a primary key set to auto increment, but now I want to remove that auto-incrementing from the column.  I've tried doing that with both fluent API:

    public class ProductTypeMap: EntityTypeConfiguration<ProductType>
    {
        public ProductTypeMap()
        {
            // This is an enum effectively, so we need fixed IDs
            Property(x => x.ProductTypeId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }

    }

And an annotation:

    public class ProductType
    {
        [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ProductTypeId { get; set; }
        public string ProductTypeName { get; set; }

    }

And in both cases they produce the same migration code:

    public partial class removeproducttypeidentity : DbMigration
    {
        public override void Up()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }

        public override void Down()
        {
            DropPrimaryKey("dbo.ProductTypes");
            AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: true));
            AddPrimaryKey("dbo.ProductTypes", "ProductTypeId");
        }
    }

However, when I run that migration on the database, the Identity Specification is not removed from the SQL Server 2008 database table?

I also tried explicitly turning off the Identity in the migration as follows, but that didn't do it either:

AlterColumn("dbo.ProductTypes", "ProductTypeId", c => c.Int(nullable: false, identity: false));

Is there another way to tell SQL to remove the Identity?


问:
In first class method included second class. I wanna use first class parent protected method in second class
I have a structure which I can't change.

Here is a example

File 1

```<code>class a
{
    protected function query(){}
}

class b extends a
{
    public function show()
    {
        include "File 2"
    }
}
</code>```

File 2

```<code>class c
{
    public function someFunction()
    {
        //Here I wanna use query method
    }
}
</code>```

I can extends b class for c. Is it right way?

答:
Yes, that will be right way if you want to use all public and protected methods of Class b in class c.

Else you can directly extend class c from class a to use protected function query of class a.

Body:
I have a structure which I can't change.

Here is a example

File 1

class a
{
    protected function query(){}
}

class b extends a
{
    public function show()
    {
        include "File 2"
    }
}

File 2

class c
{
    public function someFunction()
    {
        //Here I wanna use query method
    }
}

I can extends b class for c. Is it right way?


问:
Django South - turning a null=True field into a null=False field
My question is, what is the best practice for turning a null=True field into a null=False field using Django South. Specifically, I'm working with a ForeignKey.

答:
If you want to turn nullable ForeignKey into non-nullable one, then it can be problematic if you have any rows with NULL for that field (column). In such case you need to either remove or fix them - possibly with custom data migration, like diegueus9 mentioned in the other answer.

But if you don't have any rows with NULL in that column, e.g. because you put that null=True only in case you might need it in the future, then you should be able to do a simple automatic schema migration:

```<code>$ ./manage.py schemamigration myapp remove_null_from_fkey --auto
(...)
$ ./manage.py migrate myapp
</code>```

Body:
If you want to turn nullable ForeignKey into non-nullable one, then it can be problematic if you have any rows with NULL for that field (column). In such case you need to either remove or fix them - possibly with custom data migration, like diegueus9 mentioned in the other answer.

But if you don't have any rows with NULL in that column, e.g. because you put that null=True only in case you might need it in the future, then you should be able to do a simple automatic schema migration:

$ ./manage.py schemamigration myapp remove_null_from_fkey --auto
(...)
$ ./manage.py migrate myapp


问:
Python - Local variable referenced before assignment error - reading a CSV file
I have the following Python 2.7 code. The aim is to read the csv file and run through the script for each row in the CSV file.

The CSV file looks like this (no headers, all filenames in column A - one file name per row, not comma separated)

```<code>ftp_abc_REFRESH_a
ftp_dep_a
</code>```

The script works for the first file, but fails on the second file with the following error:

```<code>timestamp  = oupload.stat(file).st_atime
UnboundLocalError: local variable 'file' referenced before assignment
</code>```

Any help is appreciated. Thanks :)

The script:

```<code>def myscript(ofile):

    import time
    import pysftp
    import sys
    import os
    from datetime import datetime
    import calendar
    import zipfile
    import re

    oupload = pysftp.Connection(host="hostbcd", username="admin", password="abcs")

    d = datetime.utcnow()
    unixtime=calendar.timegm(d.utctimetuple())

    month = datetime.now().strftime("%m")

    string = ofile+month+".*\.txt$"

    possibleFiles = oupload.listdir("/")
    for filename in possibleFiles:
            filedate = re.search(string, filename)
            if filedate:
                file = filename

    timestamp  = oupload.stat(file).st_atime
    #if timestamp > unixtime - 54050 - 30 days
    if timestamp != unixtime:
        newtime=unixtime + 1800
        abmfile='filename_'
        zipname = abmfile+str(newtime)+'.sync.zip'
        create_zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
        oupload.get(file,file)
        oupload.close()
        newfilename = abmfile+str(newtime)+'.sync'
        os.rename(file, newfilename)
        create_zip.write(newfilename)
        create_zip.close()

    else:
        print "No files found"

import csv
with open("data.csv", 'r') as csv_file:
    reader = csv.reader(csv_file)

    for row in reader:
        ofile = row[0]
        result = myscript(ofile)
</code>```

答:
The error shows you pretty much everything :
UnboundLocalError: local variable 'file' referenced before assignment

This means you are trying to use something that has not been set earlier.

The only moment you would initialize file is into your if-statement if filedate. You are not passing the condition, hence the error and the un-initialiazed file object.

Body:
I have the following Python 2.7 code. The aim is to read the csv file and run through the script for each row in the CSV file.

The CSV file looks like this (no headers, all filenames in column A - one file name per row, not comma separated)

ftp_abc_REFRESH_a
ftp_dep_a

The script works for the first file, but fails on the second file with the following error:

timestamp  = oupload.stat(file).st_atime
UnboundLocalError: local variable 'file' referenced before assignment

Any help is appreciated. Thanks :)

The script:

def myscript(ofile):

    import time
    import pysftp
    import sys
    import os
    from datetime import datetime
    import calendar
    import zipfile
    import re

    oupload = pysftp.Connection(host="hostbcd", username="admin", password="abcs")

    d = datetime.utcnow()
    unixtime=calendar.timegm(d.utctimetuple())

    month = datetime.now().strftime("%m")

    string = ofile+month+".*\.txt$"

    possibleFiles = oupload.listdir("/")
    for filename in possibleFiles:
            filedate = re.search(string, filename)
            if filedate:
                file = filename

    timestamp  = oupload.stat(file).st_atime
    #if timestamp > unixtime - 54050 - 30 days
    if timestamp != unixtime:
        newtime=unixtime + 1800
        abmfile='filename_'
        zipname = abmfile+str(newtime)+'.sync.zip'
        create_zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
        oupload.get(file,file)
        oupload.close()
        newfilename = abmfile+str(newtime)+'.sync'
        os.rename(file, newfilename)
        create_zip.write(newfilename)
        create_zip.close()

    else:
        print "No files found"

import csv
with open("data.csv", 'r') as csv_file:
    reader = csv.reader(csv_file)

    for row in reader:
        ofile = row[0]
        result = myscript(ofile)


问:
Creating a nested array with unspecified number of columns
I'm trying to create a nested array that takes the user's input and stores it in the sub arrays. The number of subarrays is given by the user. I need the columns to be unspecified, and any number of elements can go in.

Is there a way to achieve this?

I tried:

```<code>puts "How many groups do you want to create?"
number_of_teams = gets.chomp
team_array = [Array.new(number_of_teams.to_i){Array.new()}]
</code>```

答: This is true for any Array. Ruby doesn't have the concept of an Array of a fixed number of elements. You don't even need to ask the user for the number of groups.

Body:
I'm trying to create a nested array that takes the user's input and stores it in the sub arrays. The number of subarrays is given by the user. I need the columns to be unspecified, and any number of elements can go in.

Is there a way to achieve this?

I tried:

puts "How many groups do you want to create?"
number_of_teams = gets.chomp
team_array = [Array.new(number_of_teams.to_i){Array.new()}]


问:
Refresh ng-repeat data
I have a big list containing all of my data, and I have another shorter list containing only the selected data.
Originally, all the data is selected so both lists are identical, and the user must uncheck the checkbox of the unwanted data, and then the unchecked data must disappear from the selected_data_list.

When the page is loaded, the two lists are being filled correctly. But when I uncheck the unwanted data, the selected_data_list is not updating.

I tried to use $scope.$apply(), but it gave me this error:

Error: $rootScope:inprog
  Action Already In Progress

Here is my code:

Complete list:

```<code><div ng-controller="BrainRegionsCtrl">

    <div ng-repeat="region in brain_regions">

        <label>

           <input type="checkbox"
              name="checkbox_brain_region__included"
              id="checkbox_brain_region_{/region.id/}"
              value="{/region.id/}"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">

           <b>{/region.name/}</b>

         </label>

    </div>
</div>
</code>```

Selected regions list:

```<code><div ng-controller="BrainRegionsCtrl">

    <label ng-repeat="region in selected_brain_regions">
        <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{/region.id/}">
        <b>{/region.name/}</b>
    </label>

 </div>
</code>```

Controller:

```<code>ngApp.controller('BrainRegionsCtrl', function ($scope, $http) {

    $scope.brain_regions = [];
    $scope.selected_brain_regions = [];

    $scope.update_selected_Brain_regions = function (region) {

        for (var i = 0; i < $scope.brain_regions.length; i++) {
            var current_region = $scope.brain_regions[i];
            if (current_region.id === region.id) {
                if (region.show) {
                    $scope.selected_brain_regions.push(current_region);
                }
                else {
                    $scope.selected_brain_regions.splice(i,1);
                }
            }
        }
        console.log($scope.selected_brain_regions);

    };

});
</code>```

Here is a jsfiddle
Thank you.

答:
Your issue because of index update, so try track by $index, should work.

```<code><label ng-repeat="region in selected_brain_regions track by $index">
    <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{{region.id}}">
    <b>{{region.name}}</b>
</label>
</code>```

Check out jsFiddle

Title: Refresh ng-repeat data

Body:
I have a big list containing all of my data, and I have another shorter list containing only the selected data.
Originally, all the data is selected so both lists are identical, and the user must uncheck the checkbox of the unwanted data, and then the unchecked data must disappear from the selected_data_list.

When the page is loaded, the two lists are being filled correctly. But when I uncheck the unwanted data, the selected_data_list is not updating.

I tried to use $scope.$apply(), but it gave me this error:

Error: $rootScope:inprog
  Action Already In Progress

Here is my code:

Complete list:

           <input type="checkbox"
              name="checkbox_brain_region__included"
              id="checkbox_brain_region_{/region.id/}"
              value="{/region.id/}"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">

           {/region.name/}

Selected regions list:

        <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{/region.id/}">
        {/region.name/}

Controller:

ngApp.controller('BrainRegionsCtrl', function ($scope, $http) {

    $scope.brain_regions = [];
    $scope.selected_brain_regions = [];

    $scope.update_selected_Brain_regions = function (region) {

        for (var i = 0; i < $scope.brain_regions.length; i++) {
            var current_region = $scope.brain_regions[i];
            if (current_region.id === region.id) {
                if (region.show) {
                    $scope.selected_brain_regions.push(current_region);
                }
                else {
                    $scope.selected_brain_regions.splice(i,1);
                }
            }
        }
        console.log($scope.selected_brain_regions);

    };

});

Here is a jsfiddle
Thank you.

Body:
Your issue because of index update, so try track by $index, should work.

<label ng-repeat="region in selected_brain_regions track by $index">
    <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{{region.id}}">
    <b>{{region.name}}</b>
</label>

Check out jsFiddle


问:
Consider 0 number of hits for omitted dates
In this example, I draw a chart from 4 pairs of date and number of visits. I can change dataGrouping.units to day or month with sum as approximation.

For the dates that don't appear in data, I want to consider their number of visits is 0. However, the current chart looks misleading.

One way to amend that is to prepare the data manually by myself, eg, by completing data by adding all the other dates with 0 as number of visits.

Does anyone know if HighCharts provides some parameters to customize this automatically? I tried pointInterval and pointIntervalUnit, it seems they have other purposes...

答:
It seems that you need to set xAxis.ordinal to true.

Live demo: http://jsfiddle.net/kkulig/hujdkL1L/

API reference: https://api.highcharts.com/highstock/xAxis.ordinal


问:
Textview inside Adapter not working
This code is not working correctly

```<code>  customViewHolder.increase.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

    Double rate=Double.parseDouble(customViewHolder.total.getText().toString());
    Log.e("rate",rate+"");
    Double newrate=rate-((Double.parseDouble(feedItem.getRate())-Double.parseDouble(feedItem.getDiscount()))*(minteger-1));
    Log.e("minusval",""+((Double.parseDouble(feedItem.getRate())-Double.parseDouble(feedItem.getDiscount()))*(minteger-1)));
    Double ratetext=newrate+(Double.parseDouble(feedItem.getRate())-Double.parseDouble(feedItem.getDiscount()))*minteger;
    Log.e("ratetext",ratetext+"");

    Double discrate=Double.parseDouble(customViewHolder.disctotal.getText().toString());
                        Double newdiscrate=discrate-(Double.parseDouble(feedItem.getDiscount())*(minteger-1));
                        Double disctext=newdiscrate+Double.parseDouble(feedItem.getDiscount())*minteger;

    Log.e("ratettttttttext",ratetext+"");
    customViewHolder.total.setText(""+ratetext);// not working
    ustomViewHolder.totalnew.setText(ratetext+"");// not working
    customViewHolder.disctotal.setText(disctext+"");// not working

    }
 });
</code>```

In this Adapter, inside onbindViewHolder my TextView not setting with the newvalue. Why it is happen?

答:
Try casting the View you get in onClick to your custom ViewHolder and change the values in that</p>

```<code>CustomViewHolder viewHolder = (CustomViewHolder) v;
viewHolder.total.setText(total);
</code>```

Title: Textview inside Adapter not working

Body:
This code is not working correctly

  customViewHolder.increase.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

    Double rate=Double.parseDouble(customViewHolder.total.getText().toString());
    Log.e("rate",rate+"");
    Double newrate=rate-((Double.parseDouble(feedItem.getRate())-Double.parseDouble(feedItem.getDiscount()))*(minteger-1));
    Log.e("minusval",""+((Double.parseDouble(feedItem.getRate())-Double.parseDouble(feedItem.getDiscount()))*(minteger-1)));
    Double ratetext=newrate+(Double.parseDouble(feedItem.getRate())-Double.parseDouble(feedItem.getDiscount()))*minteger;
    Log.e("ratetext",ratetext+"");

    Double discrate=Double.parseDouble(customViewHolder.disctotal.getText().toString());
                        Double newdiscrate=discrate-(Double.parseDouble(feedItem.getDiscount())*(minteger-1));
                        Double disctext=newdiscrate+Double.parseDouble(feedItem.getDiscount())*minteger;

    Log.e("ratettttttttext",ratetext+"");
    customViewHolder.total.setText(""+ratetext);// not working
    ustomViewHolder.totalnew.setText(ratetext+"");// not working
    customViewHolder.disctotal.setText(disctext+"");// not working

    }
 });

In this Adapter, inside onbindViewHolder my TextView not setting with the newvalue. Why it is happen?

Body:
Try casting the View you get in onClick to your custom ViewHolder and change the values in that

CustomViewHolder viewHolder = (CustomViewHolder) v;
viewHolder.total.setText(total);


问:
How to make good looking custom ui in mobile and tablet devices?
I'm looking for an intro into designing and making a custom and dynamic UI on mobile specific platforms. As I understand Nokia(Qt), Android, and iOS all use OpenGL ES (2.0?). I haven't looked into Windows phone 7 yet so not sure what that uses. So I think OpenGL would be a pretty good place to start. While OpenGL is mostly about 3D, I'm also open to 2d ways of creating dynamic UI.

I've never really been big on designing interfaces or coming up with cool concepts but now I have an idea for a mobile app that really needs a good looking user-interface. It's sort of a half app, half game type of thing. It really targets people in the gaming community who I think are used to a bit more polish and advanced UI. I could still probably get away with a simple UI(simple not being a bad thing) but I think I at least should learn some design techniques for future reference.

Of course I realise that excessive eye candy which hurts usability, like bloated graphics that slow down the mobile, are of no use at all. I'm trying to make a sleek UI that while looking good allows the user to interact well with the app effectively.

Any suggestions, resources, experience you can share would be most helpful.

EDIT: While I'm looking for ways to use 3D graphics, I'm more concerned with how to come up with a sleek UI in a mobile. I come from a mostly web developer background, with some experience in Photoshop(CSS is the furthest I've gone in designing). I have never really had to design a dynamic interface that reacted to touch and moved all around the screen with some laws of physics attached. There are lots of such effects, such as the carousal effect, which gives the user an enhanced experience. I have no idea how to incorporate these effects into a mobile device. For example, one of the things I need this app to do is take a glassy circular object(a button) that moves around, then turn it into a sort of convex glass lens so it's sort of zooming in on the image underneath to make it look like its actually a magnifying glass. I looked around and this effect is created by a "grid warp" or a "mesh warp". Suffice it to say I have no idea how to do it.

答:
This will help you not only with Windows Phone 7. WP7 uses DirectX 9, but not directly, you must pick XNA or Silverlight(no other options). Also these blog posts I find quite usefull.

For game, game related app I would stick to one design, and as you said start with OpenGL.


问:
Is C# LINQ OrderBy threadsafe when used with ConcurrentDictionary<Tkey, TValue>?
My working assumption is that LINQ is thread-safe when used with the System.Collections.Concurrent collections (including ConcurrentDictionary).

(Other Overflow posts seem to agree: link)

However, an inspection of the implementation of the LINQ OrderBy extension method shows that it appears not to be threadsafe with the subset of concurrent collections which implement ICollection (e.g. ConcurrentDictionary).

The OrderedEnumerable GetEnumerator (source here) constructs an instance of a Buffer struct (source here) which tries to cast the collection to an ICollection (which ConcurrentDictionary implements) and then performs a collection.CopyTo with an array initialised to the size of the collection.

Therefore, if the ConcurrentDictionary (as the concrete ICollection in this case) grows in size during the OrderBy operation, between initialising the array and copying into it, this operation will throw.

The following test code shows this exception:

(Note: I appreciate that performing an OrderBy on a thread-safe collection which is changing underneath you is not that meaningful, but I do not believe it should throw)

```<code>using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int loop = 0;
                while (true) //Run many loops until exception thrown
                {
                    Console.WriteLine($"Loop: {++loop}");

                    _DoConcurrentDictionaryWork().Wait();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private static async Task _DoConcurrentDictionaryWork()
        {
            var concurrentDictionary = new ConcurrentDictionary<int, object>();
            var keyGenerator = new Random();
            var tokenSource = new CancellationTokenSource();

            var orderByTaskLoop = Task.Run(() =>
            {
                var token = tokenSource.Token;
                while (token.IsCancellationRequested == false)
                {
                    //Keep ordering concurrent dictionary on a loop
                    var orderedPairs = concurrentDictionary.OrderBy(x => x.Key).ToArray(); //THROWS EXCEPTION HERE

                    //...do some more work with ordered snapshot...
                }
            });

            var updateDictTaskLoop = Task.Run(() =>
            {
                var token = tokenSource.Token;
                while (token.IsCancellationRequested == false)
                {
                    //keep mutating dictionary on a loop
                    var key = keyGenerator.Next(0, 1000);
                    concurrentDictionary[key] = new object();
                }
            });

            //Wait for 1 second
            await Task.Delay(TimeSpan.FromSeconds(1));

            //Cancel and dispose token
            tokenSource.Cancel();
            tokenSource.Dispose();

            //Wait for orderBy and update loops to finish (now token cancelled)
            await Task.WhenAll(orderByTaskLoop, updateDictTaskLoop);
        }
    }
}
</code>```

That the OrderBy throws an exception leads to one of a few possible conclusions:

1) My assumption about LINQ being threadsafe with concurrent collections is incorrect, and it is only safe to perform LINQ on collections (be they concurrent or not) which are not mutating during the LINQ query

2) There is a bug with the implementation of LINQ OrderBy and it is incorrect for the implementation to try and cast the source collection to an ICollection and try and perform the collection copy (and It should just drop through to its default behaviour iterating the IEnumerable).

3) I have misunderstood what is going on here...

Thoughts much appreciated!

答:
It's not stated anywhere that OrderBy (or other LINQ methods) should always use GetEnumerator of source IEnumerable or that it should be thread safe on concurrent collections. All that is promised is this method

Sorts the elements of a sequence in ascending order according to a
  key.

ConcurrentDictionary is not thread-safe in some global sense either. It's thread-safe with respect to other operations performed on it. Even more, documentation says that

All public and protected members of ConcurrentDictionary
  are thread-safe and may be used concurrently from multiple threads.
  However, members accessed through one of the interfaces the
  ConcurrentDictionary implements, including extension
  methods, are not guaranteed to be thread safe and may need to be
  synchronized by the caller.

So, your understanding is correct (OrderBy will see IEnumerable you pass to it is really ICollection, will then get length of that collection, allocate buffer of that size, then will call ICollection.CopyTo, and this is of course not thread safe on any type of collection), but it's not a bug in OrderBy because neither OrderBy nor ConcurrentDictionary ever promised what you assume.

If you want to do OrderBy in a thread safe way on ConcurrentDictionary, you need to rely on methods that are promised to be thread safe. For example:

```<code>// note: this is NOT IEnumerable.ToArray()
// but public ToArray() method of ConcurrentDictionary itself
// it is guaranteed to be thread safe with respect to other operations
// on this dictionary
var snapshot = concurrentDictionary.ToArray();
// we are working on snapshot so no one other thread can modify it
// of course at this point real contents of dictionary might not be
// the same as our snapshot
var sorted = snapshot.OrderBy(c => c.Key);
</code>```

If you don't want to allocate additional array (with ToArray), you can use Select(c => c) and it will work in this case, but then we are again in moot territory and relying on something to be safe to use in situation it was not promised to (Select will also not always enumerate your collection. If collection is array or list - it will shortcut and use indexers instead). So you can create extension method like this:

```<code>public static class Extensions {
    public static IEnumerable<T> ForceEnumerate<T>(this ICollection<T> collection) {
        foreach (var item in collection)
            yield return item;
    }
}
</code>```

And use it like this if you want to be safe and don't want to allocate array:

```<code>concurrentDictionary.ForceEnumerate().OrderBy(c => c.Key).ToArray();
</code>```

In this case we are forcing enumeration of ConcurrentDictionary (which we know is safe from documentation) and then pass that to OrderBy knowing that it cannot do any harm with that pure IEnumerable. Note that as correctly pointed out in comments by mjwills, this is not exactly the same as ToArray, because ToArray produces snapshot (locks collection preventing modifications while building array) and Select \ yield does not acquire any locks (so items might be added\removed right when enumeration is in progress). Though I doubt it  matters when doing things like described in question - in both cases after OrderBy is completed - you have no idea whether your ordered results reflect current state of collection or not.

Body:
My working assumption is that LINQ is thread-safe when used with the System.Collections.Concurrent collections (including ConcurrentDictionary).

(Other Overflow posts seem to agree: link)

However, an inspection of the implementation of the LINQ OrderBy extension method shows that it appears not to be threadsafe with the subset of concurrent collections which implement ICollection (e.g. ConcurrentDictionary).

The OrderedEnumerable GetEnumerator (source here) constructs an instance of a Buffer struct (source here) which tries to cast the collection to an ICollection (which ConcurrentDictionary implements) and then performs a collection.CopyTo with an array initialised to the size of the collection.

Therefore, if the ConcurrentDictionary (as the concrete ICollection in this case) grows in size during the OrderBy operation, between initialising the array and copying into it, this operation will throw.

The following test code shows this exception:

(Note: I appreciate that performing an OrderBy on a thread-safe collection which is changing underneath you is not that meaningful, but I do not believe it should throw)

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int loop = 0;
                while (true) //Run many loops until exception thrown
                {
                    Console.WriteLine($"Loop: {++loop}");

                    _DoConcurrentDictionaryWork().Wait();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private static async Task _DoConcurrentDictionaryWork()
        {
            var concurrentDictionary = new ConcurrentDictionary<int, object>();
            var keyGenerator = new Random();
            var tokenSource = new CancellationTokenSource();

            var orderByTaskLoop = Task.Run(() =>
            {
                var token = tokenSource.Token;
                while (token.IsCancellationRequested == false)
                {
                    //Keep ordering concurrent dictionary on a loop
                    var orderedPairs = concurrentDictionary.OrderBy(x => x.Key).ToArray(); //THROWS EXCEPTION HERE

                    //...do some more work with ordered snapshot...
                }
            });

            var updateDictTaskLoop = Task.Run(() =>
            {
                var token = tokenSource.Token;
                while (token.IsCancellationRequested == false)
                {
                    //keep mutating dictionary on a loop
                    var key = keyGenerator.Next(0, 1000);
                    concurrentDictionary[key] = new object();
                }
            });

            //Wait for 1 second
            await Task.Delay(TimeSpan.FromSeconds(1));

            //Cancel and dispose token
            tokenSource.Cancel();
            tokenSource.Dispose();

            //Wait for orderBy and update loops to finish (now token cancelled)
            await Task.WhenAll(orderByTaskLoop, updateDictTaskLoop);
        }
    }
}

That the OrderBy throws an exception leads to one of a few possible conclusions:

1) My assumption about LINQ being threadsafe with concurrent collections is incorrect, and it is only safe to perform LINQ on collections (be they concurrent or not) which are not mutating during the LINQ query

2) There is a bug with the implementation of LINQ OrderBy and it is incorrect for the implementation to try and cast the source collection to an ICollection and try and perform the collection copy (and It should just drop through to its default behaviour iterating the IEnumerable).

3) I have misunderstood what is going on here...

Thoughts much appreciated!

Body:
It's not stated anywhere that OrderBy (or other LINQ methods) should always use GetEnumerator of source IEnumerable or that it should be thread safe on concurrent collections. All that is promised is this method

Sorts the elements of a sequence in ascending order according to a
  key.

ConcurrentDictionary is not thread-safe in some global sense either. It's thread-safe with respect to other operations performed on it. Even more, documentation says that

All public and protected members of ConcurrentDictionary
  are thread-safe and may be used concurrently from multiple threads.
  However, members accessed through one of the interfaces the
  ConcurrentDictionary implements, including extension
  methods, are not guaranteed to be thread safe and may need to be
  synchronized by the caller.

So, your understanding is correct (OrderBy will see IEnumerable you pass to it is really ICollection, will then get length of that collection, allocate buffer of that size, then will call ICollection.CopyTo, and this is of course not thread safe on any type of collection), but it's not a bug in OrderBy because neither OrderBy nor ConcurrentDictionary ever promised what you assume.

If you want to do OrderBy in a thread safe way on ConcurrentDictionary, you need to rely on methods that are promised to be thread safe. For example:

// note: this is NOT IEnumerable.ToArray()
// but public ToArray() method of ConcurrentDictionary itself
// it is guaranteed to be thread safe with respect to other operations
// on this dictionary
var snapshot = concurrentDictionary.ToArray();
// we are working on snapshot so no one other thread can modify it
// of course at this point real contents of dictionary might not be
// the same as our snapshot
var sorted = snapshot.OrderBy(c => c.Key);

If you don't want to allocate additional array (with ToArray), you can use Select(c => c) and it will work in this case, but then we are again in moot territory and relying on something to be safe to use in situation it was not promised to (Select will also not always enumerate your collection. If collection is array or list - it will shortcut and use indexers instead). So you can create extension method like this:

public static class Extensions {
    public static IEnumerable<T> ForceEnumerate<T>(this ICollection<T> collection) {
        foreach (var item in collection)
            yield return item;
    }
}

And use it like this if you want to be safe and don't want to allocate array:

concurrentDictionary.ForceEnumerate().OrderBy(c => c.Key).ToArray();

In this case we are forcing enumeration of ConcurrentDictionary (which we know is safe from documentation) and then pass that to OrderBy knowing that it cannot do any harm with that pure IEnumerable. Note that as correctly pointed out in comments by mjwills, this is not exactly the same as ToArray, because ToArray produces snapshot (locks collection preventing modifications while building array) and Select \ yield does not acquire any locks (so items might be added\removed right when enumeration is in progress). Though I doubt it  matters when doing things like described in question - in both cases after OrderBy is completed - you have no idea whether your ordered results reflect current state of collection or not.


问:
OOP - inheritance [Java]
bb refers Derived  class, when i call show() method,  but when i print bb.b  - is prints Base class property .
Why is this happening?

```<code>class Base {
    int b=10;
    public void show() {

        System.out.println("Base show() called");

    }
}

class Derived extends Base {

    int b=20;
    public void show() {

        System.out.println("Derived show() called");

    }

}

public class MainClass {

    public static void main(String[] args) {

        Base bb = new Derived();;

        bb.show();
        System.out.println(bb.b);

    }

}
</code>```

output :

Derived show() called

10

答:
You output is 10because you explicitly access variable b in class Base.

Beside the technical aspect doing so this is not OOP since it violates the most important OO principle: information hiding / encapsulation.

Title: OOP - inheritance [Java]

Body:
bb refers Derived  class, when i call show() method,  but when i print bb.b  - is prints Base class property .
Why is this happening?

class Base {
    int b=10;
    public void show() {

        System.out.println("Base show() called");

    }
}

class Derived extends Base {

    int b=20;
    public void show() {

        System.out.println("Derived show() called");

    }

}

public class MainClass {

    public static void main(String[] args) {

        Base bb = new Derived();;

        bb.show();
        System.out.println(bb.b);

    }

}

output :

Derived show() called

10


问:
How to assign a variable in the WHERE clause of a sub-query in SQL Server
```<code>SELECT
    Total_Males, SETTLEMENT_ID, URI, _PARENT_AURI
FROM
    (SELECT
         COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
         t2._PARENT_AURI
     FROM
         PScData t1
     INNER JOIN
         PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
     WHERE
         t1.SETTLEMENT_ID = '11102002002001'
         AND t2.SEX = '1'
     GROUP BY
         t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp
</code>```

This is the query that I have written. In the WHERE clause, where I have given the exact value - '11102002002001' - I want to compare with each SETTLEMENT_ID from t1. How can I do this? Please provide some solution.

Further, the query is returning count in two rows i.e: count against two different ids right now. How can I add the result of two different ids to get the sum of these two rows returned by the sub-query?

答:
Try With , </p>

```<code>Select
Total_Males, SETTLEMENT_ID , URI, _PARENT_AURI
from
(Select
COUNT(t2.SEX) as Total_Males ,t1.SETTLEMENT_ID  , t1.URI, t2._PARENT_AURI
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 where
  t1.SETTLEMENT_ID in (SELECT DISTINCT SETTLEMENT_ID FROM PScData)
  AND t2.SEX = '1'
 Group By
t1.SETTLEMENT_ID ) tmp
</code>```

Body:
SELECT
    Total_Males, SETTLEMENT_ID, URI, _PARENT_AURI
FROM
    (SELECT
         COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
         t2._PARENT_AURI
     FROM
         PScData t1
     INNER JOIN
         PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
     WHERE
         t1.SETTLEMENT_ID = '11102002002001'
         AND t2.SEX = '1'
     GROUP BY
         t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp

This is the query that I have written. In the WHERE clause, where I have given the exact value - '11102002002001' - I want to compare with each SETTLEMENT_ID from t1. How can I do this? Please provide some solution.

Further, the query is returning count in two rows i.e: count against two different ids right now. How can I add the result of two different ids to get the sum of these two rows returned by the sub-query?

Body:
Try With ,

Select
Total_Males, SETTLEMENT_ID , URI, _PARENT_AURI
from
(Select
COUNT(t2.SEX) as Total_Males ,t1.SETTLEMENT_ID  , t1.URI, t2._PARENT_AURI
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 where
  t1.SETTLEMENT_ID in (SELECT DISTINCT SETTLEMENT_ID FROM PScData)
  AND t2.SEX = '1'
 Group By
t1.SETTLEMENT_ID ) tmp


问:
How can i get background colour decimals?

I'm trying to read background color which i set in decimals e.g rgb(44.9, 19.373737, 255)
using this code

```<code>$("p").css("background-color")
</code>```

but when used it keeps rounding it into rgb(45, 19, 255)

all i want to achieve is to get it in decimals

This is the sample code:

```<code><script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Background color = " + $("p").css("background-color"));
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:rgb(44.9, 19.373737, 255)">This is a paragraph.</p>

<button>Return background-color of p</button>
</code>```

答:
rgb() uses 8 bit color and 2^8 = 256. Therefore, you can only use integers ranging from 0 to 255.

The issue seems to be with your backend logic which is generating decimal point values. You can round off the values before storing or using it.

Body:
I'm trying to read background color which i set in decimals e.g rgb(44.9, 19.373737, 255)
using this code

$("p").css("background-color")

but when used it keeps rounding it into rgb(45, 19, 255)

all i want to achieve is to get it in decimals

This is the sample code:

This is a heading

This is a paragraph.

<button>Return background-color of p</button>


问:
RND generator on SIM card: is it available outside (for Android for instance)?
Fuzzy question here.

I know that some smart-cards (including SIM cards) can contain random number generator. But I cannot get any information about that. Is it possible to get random numbers outside of SIM card? For instance, I want to create Android App, which asks SIM card somehow (using APDU commands for example) for random number, then app uses it as intended. Is it possible? I mean, is this generator accessible outside? And if so, what the command should be used?
I'll be very grateful for any hints and links.

答:
If you can install a Java Card Applet on the SIM card then you can use the methods of RandomData to retrieve data from the SIM card. Note that normally you will have to use the deprecated methods / constants as a lot of the functions were created specifically for Java Card version 3.0.5. You can use this functionality to create an APDU interface. Usually you would implement the ISO/IEC 7816-4 GET CHALLENGE APDU for this.

You can also cheat a bit if the card supports Global Platform: the GP INITIALIZE UPDATE platform INITIALIZE UPDATE APDU in the end returns a "Card challenge" as part of the response data. That way you can access the RNG, but only for 6 bytes at a time. Worse, the SIM card may think it is under attack and perform counter measures, which in the worst case could destroy your SIM, depending on the implementation.


问:
Matlab: Partly assign numbers into a symbolic matrix
I have a matrix with two different symbolic vector variables: S and K
I need to assign numbers to S but not to K. I don't know how to use for subs function in this way. Any suggestions? For example:

```<code>syms s1 s2 k1 k2 % symbols S and K vector
j1=s1*s2+s1*k1;
j2=k2*s1+k2*k1*s2*s1;
js=[j1, j2];
vars=[s1 s2];
M=jacobian(jcb,vars); % calculate the jacobian here, and the result
% should be a function of s1, s2, k1, k2
</code>```

I need to assign for example s1=2 and s1=3 ans get a matrix which is function of k1 and k2. My real equations have more than 30 variables (s1 .. s30) and about 40 parameters (k1,... k40)
Thanks

答:
You can use subs to perform multiple substitutions at once as follows:

```<code>subs(M, vars, [2, 3])
</code>```

Which is equivalent to:

```<code>subs(M, [s1 s2], [2, 3])
</code>```

Body:
I have a matrix with two different symbolic vector variables: S and K
I need to assign numbers to S but not to K. I don't know how to use for subs function in this way. Any suggestions? For example:

syms s1 s2 k1 k2 % symbols S and K vector
j1=s1*s2+s1*k1;
j2=k2*s1+k2*k1*s2*s1;
js=[j1, j2];
vars=[s1 s2];
M=jacobian(jcb,vars); % calculate the jacobian here, and the result
% should be a function of s1, s2, k1, k2

I need to assign for example s1=2 and s1=3 ans get a matrix which is function of k1 and k2. My real equations have more than 30 variables (s1 .. s30) and about 40 parameters (k1,... k40)
Thanks

Body:
You can use subs to perform multiple substitutions at once as follows:

subs(M, vars, [2, 3])

Which is equivalent to:

subs(M, [s1 s2], [2, 3])