问:
punctuation marks in javascript
can you guys plese help me to correct the punctuation marks in the javascript below? Found error when i paste in visual studio. I'm not familiar with javascript! Thanks guy...</p>

```<code>function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,”/”);
  imgname = imgname.replace(/\’/g,”\\’”);
  content = “<img src=\”" + String(imgname) + “\” border=\”0\” height=\”150\” weight=\”150\”>”;
  eval(‘document.getElementById(“imagepreview”).innerHTML=\” + content +”‘”);
  document.getElementById.imagepreview.style.visibility =’visible’;
}
</code>```

答:
This is because some of your quote characters are actually from a different character encoding, Use the following code:

```<code>function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,"/");
  imgname = imgname.replace(/\’/g,"\\'");
  content = "<img src=\"" + imgname + "\" border=\"0\" height=\"150\" weight=\"150\">";
  var image_preview = document.getElementById("imagepreview");
  image_preview.innerHTML = content;
  image_preview.style.visibility = 'visible';
}
</code>```

A couple of things:

You should reuse DOM result sets and elements as much as possible to avoid having to run a query against the DOM every time you need to reference an element or set of elements.

You should really try to avoid using the eval function as much as possible.

eval == EVIL

Title: punctuation marks in javascript

Body:
can you guys plese help me to correct the punctuation marks in the javascript below? Found error when i paste in visual studio. I'm not familiar with javascript! Thanks guy...

function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,”/”);
  imgname = imgname.replace(/\’/g,”\\’”);
  content = “”;
  eval(‘document.getElementById(“imagepreview”).innerHTML=\” + content +”‘”);
  document.getElementById.imagepreview.style.visibility =’visible’;
}

Body:
This is because some of your quote characters are actually from a different character encoding, Use the following code:

function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,"/");
  imgname = imgname.replace(/\’/g,"\\'");
  content = "<img src=\"" + imgname + "\" border=\"0\" height=\"150\" weight=\"150\">";
  var image_preview = document.getElementById("imagepreview");
  image_preview.innerHTML = content;
  image_preview.style.visibility = 'visible';
}

A couple of things:

You should reuse DOM result sets and elements as much as possible to avoid having to run a query against the DOM every time you need to reference an element or set of elements.

You should really try to avoid using the eval function as much as possible.

eval == EVIL


来源: stackexchange

问:
Convert xlsx file to csv using batch
How do you convert multiple xlsx files to csv files with a batch script?</p>

答:
Needs installed excel as it uses the Excel.Application com object.Save this as .bat file:

```<code>@if (@X)==(@Y) @end /* JScript comment
    @echo off

    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */

var ARGS = WScript.Arguments;

var xlCSV = 6;

var objExcel = WScript.CreateObject("Excel.Application");
var objWorkbook = objExcel.Workbooks.Open(ARGS.Item(0));
objExcel.DisplayAlerts = false;
objExcel.Visible = false;

var objWorksheet = objWorkbook.Worksheets(ARGS.Item(1))
objWorksheet.SaveAs( ARGS.Item(2), xlCSV);

objExcel.Quit();
</code>```

It accepts three arguments - the absolute path to the xlsx file, the sheet name and the absolute path to the target csv file:

```<code>call toCsv.bat "%cd%\Book1.xlsx" Sheet1 "%cd%\csv.csv"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Convert xlsx file to csv using batch

Body:
Needs installed excel as it uses the Excel.Application com object.Save this as .bat file:

@if (@X)==(@Y) @end /* JScript comment
    @echo off

    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */

var ARGS = WScript.Arguments;

var xlCSV = 6;

var objExcel = WScript.CreateObject("Excel.Application");
var objWorkbook = objExcel.Workbooks.Open(ARGS.Item(0));
objExcel.DisplayAlerts = false;
objExcel.Visible = false;

var objWorksheet = objWorkbook.Worksheets(ARGS.Item(1))
objWorksheet.SaveAs( ARGS.Item(2), xlCSV);

objExcel.Quit();

It accepts three arguments - the absolute path to the xlsx file, the sheet name and the absolute path to the target csv file:

call toCsv.bat "%cd%\Book1.xlsx" Sheet1 "%cd%\csv.csv"


问:
Laravel 5.4: Change DB according to sub domain in laravel
I am creating a SAAS application with a single laravel installation and multi tenant database.
So i have a main DB that is connected to laravel by default. the client can access the application through their sub-domain like: client1.example.com and client2.example.com

I am saving all info fo the client like domain and db name in the main db.

How can change the DB according to the subdomain

I tried with the following Code

in routes/web.php

```<code>Route::group(['domain' => '{account}'], function() {
    Route::get('/', function($account) {
        // This will return {account}, which you can pass along to what you'd like
        return $account;
    });

});
</code>```

in app/Providers\RouteServiceProvieder.php

```<code> public function boot(Router $router)
    {
        parent::boot($router);

        $router->bind('domain', function ($value) {
            //$hst=$request->getHost();
            $domain= Customer::where('sub_domain',$value)->first();
            if ($domain) {
                return $domain;
            }
            throw new Exception('error message');
        });

    }
</code>```

Then i have created a ServiceProvider ConfigServiceProvider

```<code><?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Request;

class ConfigServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register(Request $request)
    {
        $customer=$request->route('domain');
        //$customer = Request::route('domain');  // there are multiple ways of doing this
        //$customer = $request->route()->domain;
        config([
            'database.mysql.database' => $customer->customer_database,  //this is because I have same username and password for all the databases. If you have different username and passwords set them too.
        ]);
        DB::reconnect(); // this will help in reconnecting the database if the connection is already established. and import the DB facade.
    }
}
</code>```

But the code is not working?

The Error i am getting is

```<code>FatalThrowableError in ConfigServiceProvider.php line 25:
Type error: Too few arguments to function App\Providers\ConfigServiceProvider::register(), 0 passed in C:\xampp\htdocs\main\vendor\laravel\framework\src\Illuminate\Foundation\Application.php on line 568 and exactly 1 expected
</code>```

I am using Laravel 5.4. Can any one guide me how to do it correctly?

答:
Change

```<code>use Illuminate\Support\Facades\Request;
</code>```

to

```<code>use Illuminate\Http\Request;
</code>```

You can not use Facades for dependency/method injection. Hope it helps

Body:
I am creating a SAAS application with a single laravel installation and multi tenant database.
So i have a main DB that is connected to laravel by default. the client can access the application through their sub-domain like: client1.example.com and client2.example.com

I am saving all info fo the client like domain and db name in the main db.

How can change the DB according to the subdomain

I tried with the following Code

in routes/web.php

Route::group(['domain' => '{account}'], function() {
    Route::get('/', function($account) {
        // This will return {account}, which you can pass along to what you'd like
        return $account;
    });

});

in app/Providers\RouteServiceProvieder.php

 public function boot(Router $router)
    {
        parent::boot($router);

        $router->bind('domain', function ($value) {
            //$hst=$request->getHost();
            $domain= Customer::where('sub_domain',$value)->first();
            if ($domain) {
                return $domain;
            }
            throw new Exception('error message');
        });

    }

Then i have created a ServiceProvider ConfigServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Request;

class ConfigServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register(Request $request)
    {
        $customer=$request->route('domain');
        //$customer = Request::route('domain');  // there are multiple ways of doing this
        //$customer = $request->route()->domain;
        config([
            'database.mysql.database' => $customer->customer_database,  //this is because I have same username and password for all the databases. If you have different username and passwords set them too.
        ]);
        DB::reconnect(); // this will help in reconnecting the database if the connection is already established. and import the DB facade.
    }
}

But the code is not working?

The Error i am getting is

FatalThrowableError in ConfigServiceProvider.php line 25:
Type error: Too few arguments to function App\Providers\ConfigServiceProvider::register(), 0 passed in C:\xampp\htdocs\main\vendor\laravel\framework\src\Illuminate\Foundation\Application.php on line 568 and exactly 1 expected

I am using Laravel 5.4. Can any one guide me how to do it correctly?

Body:
Change

use Illuminate\Support\Facades\Request;

to

use Illuminate\Http\Request;

You can not use Facades for dependency/method injection. Hope it helps


问:
Delete from collection B based on results from collection A
I have 2 big collections, which are cross-used (small data is in collection A, while big binary data is in collection B). They all have the same key, now I want to delete everything from both collections based on something like:

```<code>db.A.remove({ field1: 10 })
</code>```

field1 only exists in collection A, but I need to delete the results with same key from collection B. So far I made a cursor with db.A.find() and delete everything in db.B one by one. It works, but is terribly slow on bigger collections like 50k+ items, hence it does like 100k operations to just delete items based on query. Is there a better way?
$in also has a limit for number of IDs, so I'm searching for some nice solution...

With the $in operator and Mongoose, i could came with something like:

```<code>var _ids = [];
A.find({ field1: 10 }).stream().on('data', function(data) {
  _ids.push(data._id);
}).once('close', function() {
  A.remove({ field1: 10 });
  B.remove({ _id: { $in: _ids } });
});
</code>```

It kinda works, but I'm afraid there will be a query limit hit with $in operator.

答:
I do not use Mongoose, but I can give you a possible solution in mongodb shell and I believe that you can make the appropriate code in Mongoose. You can make something like that: </p>

```<code>var _ids = db.A.distinct('_id',{field1: 10});
B.remove({_id:{$in:_ids}});
A.remove({field1:10});
</code>```

Body:
I have 2 big collections, which are cross-used (small data is in collection A, while big binary data is in collection B). They all have the same key, now I want to delete everything from both collections based on something like:

db.A.remove({ field1: 10 })

field1 only exists in collection A, but I need to delete the results with same key from collection B. So far I made a cursor with db.A.find() and delete everything in db.B one by one. It works, but is terribly slow on bigger collections like 50k+ items, hence it does like 100k operations to just delete items based on query. Is there a better way?
$in also has a limit for number of IDs, so I'm searching for some nice solution...

With the $in operator and Mongoose, i could came with something like:

var _ids = [];
A.find({ field1: 10 }).stream().on('data', function(data) {
  _ids.push(data._id);
}).once('close', function() {
  A.remove({ field1: 10 });
  B.remove({ _id: { $in: _ids } });
});

It kinda works, but I'm afraid there will be a query limit hit with $in operator.

Body:
I do not use Mongoose, but I can give you a possible solution in mongodb shell and I believe that you can make the appropriate code in Mongoose. You can make something like that:

var _ids = db.A.distinct('_id',{field1: 10});
B.remove({_id:{$in:_ids}});
A.remove({field1:10});


问:
How to Change Amazon S3 file URL Like s3.amazonaws.com/bucket/key from bucket.s3.amazonaws.com/key in Java?
Working with AmazonS3 bucket - After uploading file to bucket, we can get uploaded file URL using below code :

```<code>String fileDownloadUrl = AmzonS3Client.getUrl(bucketName, fileName);
</code>```

In Result it will give url like i.e : bucket.s3.amazonaws.com/key but I want s3.amazonaws.com/bucket/key. So Can anyone help me how can I solve this in java?

答:
Another Solution:

Create AmazonS3Client object using AmazonS3ClientBuilder with enablePathStyleAccess().

```<code>AmazonS3 client = AmazonS3ClientBuilder.standard()
        .enablePathStyleAccess()
        .withRegion(regionName)
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .build();
</code>```

Body:
Working with AmazonS3 bucket - After uploading file to bucket, we can get uploaded file URL using below code :

String fileDownloadUrl = AmzonS3Client.getUrl(bucketName, fileName);

In Result it will give url like i.e : bucket.s3.amazonaws.com/key but I want s3.amazonaws.com/bucket/key. So Can anyone help me how can I solve this in java?

Body:
Another Solution:

Create AmazonS3Client object using AmazonS3ClientBuilder with enablePathStyleAccess().

AmazonS3 client = AmazonS3ClientBuilder.standard()
        .enablePathStyleAccess()
        .withRegion(regionName)
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .build();


问:
connect mac os x php to oracle XE on vmware
I'm coding a mac app in XCode which switches between mySQL and Oracle databases. I have successfully managed to communicate with my mySQL database via PHP, but I'm at a loss on how to connect to my Oracle database (11g XE) running under WinXP in VMWare on my mac. I checked phpinfo and do have odbc installed with my version of PHP and I have my VMWare networking set to NAT. I'm kinda new to this. Any advice?

I've tried this script:

```<code><?php

$conn = odbc_connect('username', 'password', 'myHost/XE');

if (!$conn) {
trigger_error("Could not connect to database", E_USER_ERROR);
}

?>
</code>```

答:
You should install the Oracle client software, freely donwloadable from http://www.oracle.com/technetwork/database/10204macsoft-x86-64-092720.html

Ronald
http://ronr.blogspot.com

ContentLicense: CC BY-SA 2.5

Body:
I'm coding a mac app in XCode which switches between mySQL and Oracle databases. I have successfully managed to communicate with my mySQL database via PHP, but I'm at a loss on how to connect to my Oracle database (11g XE) running under WinXP in VMWare on my mac. I checked phpinfo and do have odbc installed with my version of PHP and I have my VMWare networking set to NAT. I'm kinda new to this. Any advice?

I've tried this script:

<?php

$conn = odbc_connect('username', 'password', 'myHost/XE');

if (!$conn) {
trigger_error("Could not connect to database", E_USER_ERROR);
}

?>


问:
Mysql querybuilder with multiple parameters values
I try to get multiple values from setParameters, but with the same 'key', litke this :

```<code>->where('d.type = :type')->setParameters(array('type'=> 7, 'type => '8'))
</code>```

But i have only result from '8', and not 7 + 8.

答:
Change your where condition as follows

```<code>->where('d.type IN (:types)')
->setParameter('types', array(7, 8))
</code>```

or

```<code>$qb = $this->createQueryBuilder('d');

// other parts of your query using $qb variable

->where($qb->expr()->in('d.type', array(7, 8));
</code>```

With first example, if array(7, 8) is a parameter variable (passed to function) and it's empty, no error will be raised.

In second, if array(7, 8) is a parameter variable (passed to function) and it's empty, an error will be raised (so you should check carefully before run the query.

Body:
I try to get multiple values from setParameters, but with the same 'key', litke this :

->where('d.type = :type')->setParameters(array('type'=> 7, 'type => '8'))

But i have only result from '8', and not 7 + 8.

Body:
Change your where condition as follows

->where('d.type IN (:types)')
->setParameter('types', array(7, 8))

or

$qb = $this->createQueryBuilder('d');

// other parts of your query using $qb variable

->where($qb->expr()->in('d.type', array(7, 8));

With first example, if array(7, 8) is a parameter variable (passed to function) and it's empty, no error will be raised.

In second, if array(7, 8) is a parameter variable (passed to function) and it's empty, an error will be raised (so you should check carefully before run the query.


问:
How to hide menu element with only CSS
I have these menu elements I am trying to hide but I cannot seem to only select the middle option called 'Contact'. I cannot edit the html directly so am using CSS to override the style.

Essentially I just want to hide the item called 'Contact' from appearing. How do I select it using CSS? I have put what I thought might work in the  section, but it's not really working. Any help would be greatly appreciated. Thanks in advance. (Here it is as well: https://jsfiddle.net/amhzv0Lw/4/)

Here's the menu code:

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .nav a[title:contact] {
        display: none;
    }
    </style>
    </head>
    <body>

    <ul class="nav navbar-nav navbar-left">
<li><a href="/www.example.com/" title="Home">Home</a></li>
<li><a href="/www.example.com/storepage.aspx" title="Contact">Contact</a></li>
<li><a href="https://www.example.com/login" title="Login">Login</a></li>

    </ul>

    </body>
    </html>
</code>```

答:
You can make use CSS nth-child selectors this way:

```<code>.nav li:nth-child(2) {
  display: none;
}
</code>```

Or may provide a CSS class to that "Contact" list-item, and hide it with CSS:

HTML

```<code><ul class="nav navbar-nav navbar-left">
  <li><a href="://www.example.com/" title="Home">Home</a></li>
  <li class="hide"><a href="://www.example.com/storepage.aspx" title="Contact">Contact</a></li>
  <li><a href="https://www.example.com/login" title="Login">Login</a></li>
</ul>
</code>```

CSS

```<code>.hide {
  display: none;
}
</code>```

.nav li:nth-child(2) {
  display: none;
}

.hide {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>With CSS nth-child selector</h3>

<ul class="nav navbar-nav navbar-left">
  <li>Home</li>
  <li>Contact</li>
  <li>Login</li>
</ul>

<h3>With CSS classes</h3>

<ul class="nav navbar-nav navbar-left">
  <li>Home</li>
  <li class="hide">Contact</li>
  <li>Login</li>
</ul></code>```

EDIT: Note that the below CSS will hide only the hyperlink, not the list-item:

```<code>.nav a[title=Contact] {
  display: none;
}
</code>```

Cheers!

Title: How to hide menu element with only CSS

Body:
I have these menu elements I am trying to hide but I cannot seem to only select the middle option called 'Contact'. I cannot edit the html directly so am using CSS to override the style.

Essentially I just want to hide the item called 'Contact' from appearing. How do I select it using CSS? I have put what I thought might work in the  section, but it's not really working. Any help would be greatly appreciated. Thanks in advance. (Here it is as well: https://jsfiddle.net/amhzv0Lw/4/)

Here's the menu code:

    <!DOCTYPE html>

Home

Contact

Login

Body:
You can make use CSS nth-child selectors this way:

.nav li:nth-child(2) {
  display: none;
}

Or may provide a CSS class to that "Contact" list-item, and hide it with CSS:

HTML

<ul class="nav navbar-nav navbar-left">
  <li><a href="://www.example.com/" title="Home">Home</a></li>
  <li class="hide"><a href="://www.example.com/storepage.aspx" title="Contact">Contact</a></li>
  <li><a href="https://www.example.com/login" title="Login">Login</a></li>
</ul>

CSS

.hide {
  display: none;
}

.nav li:nth-child(2) {
  display: none;
}

.hide {
  display: none;
}

<h3>With CSS nth-child selector</h3>

<ul class="nav navbar-nav navbar-left">
  <li><a href="/www.example.com/" title="Home">Home</a></li>
  <li><a href="/www.example.com/storepage.aspx" title="Contact">Contact</a></li>
  <li><a href="https://www.example.com/login" title="Login">Login</a></li>
</ul>

<h3>With CSS classes</h3>

<ul class="nav navbar-nav navbar-left">
  <li><a href="/www.example.com/" title="Home">Home</a></li>
  <li class="hide"><a href="/www.example.com/storepage.aspx" title="Contact">Contact</a></li>
  <li><a href="https://www.example.com/login" title="Login">Login</a></li>
</ul>

EDIT: Note that the below CSS will hide only the hyperlink, not the list-item:

.nav a[title=Contact] {
  display: none;
}

Cheers!


问:
Migrating from spring boot 1.3.8.RELEASE to 1.5.2.RELEASE - Neo4jDataAutoConfiguration overriding default sessionFactory
I had a working spring boot app and I am trying to migration from Spring boot 1.3.8.RELEASE to 1.5.2.RELEASE.  In my working 1.3.8.RELEASE track  I was using hibernate 5 already i.e. i had the the following dependency in y pom

```<code>     <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-java8</artifactId>
         <version>${hibernate.version}</version>
     </dependency>
</code>```

with Spring boot 1.5 this is not needed thus i change this to the default hibernate 5 dependency i.e. hibernate-core and removed the version declaration.

```<code><dependency>
     <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
</dependency>
</code>```

However i can not figure out why my test is saying:

```<code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
</code>```

I have definitely configured the session factory

```<code>@Profile("Development")
@Configuration
@EnableTransactionManagement
@Order(value=1)
public class PersistenceConfigDevelopment {

    @Bean
    public org.apache.commons.dbcp.BasicDataSource dataSourceReadWrite() {

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/testDB");
        dataSource.setUsername("admin");
        dataSource.setPassword("veryBigSecret!");
        dataSource.setInitialSize(20);
        dataSource.setMaxActive(-1);

        return dataSource;
    }

    @Bean
    public org.springframework.orm.hibernate5.LocalSessionFactoryBean sessionFactory() {

        org.springframework.orm.hibernate5.LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(this.dataSourceReadWrite());
        sessionFactory.setPackagesToScan("org.testApp");
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

       @Bean
       public  org.springframework.orm.hibernate5.HibernateTransactionManager  transactionManager() {
          HibernateTransactionManager txManager = new HibernateTransactionManager();
          txManager.setSessionFactory(sessionFactory().getObject());
          return txManager;
       }

       @Bean
       public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
          return new PersistenceExceptionTranslationPostProcessor();
       }

    @Bean
    public  Properties hibernateProperties() {

    return new Properties() {

        {
                setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
                setProperty("hibernate.chach.provider_class", "org.hibernate.cache.NoCacheProvider");
                setProperty("hibernate.show_sql", "true");
                setProperty("hibernate.hbm2ddl.auto", "create-drop");

                setProperty("hibernate.cache.use_second_level_cache", "false");
                setProperty("hibernate.cache.use_query_cache", "false");

                //isolation level
                setProperty("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_SERIALIZABLE));

             }
          };
       }

}
</code>```

here is how i start my spring boot 1.5.2 test:

```<code>@RunWith(SpringRunner.class)
@TestExecutionListeners(listeners={
                                    DependencyInjectionTestExecutionListener.class,
                                    DirtiesContextTestExecutionListener.class,
                                    WithSecurityContextTestExecutionListener.class
                                    }
        )
@SpringBootTest(
        classes = {
        SecurityWebApplicationInitializerDevelopment.class,
        SecurityConfigDevelopment.class,
        TomcatEmbededDevelopmentProfile.class,
        Internationalization.class,
        MVCConfigDevelopment.class,
        PersistenceConfigDevelopment.class,
        }

    )
@WebAppConfiguration
@ActiveProfiles(TestAppConfigurationProfiles.DEVELOPMENT_PROFILE)
@WithMockUser(username="alice",roles={"USER","ADMIN"} )
public class mainTests {
     ......
</code>```

for some reason Spring boot 1.5 does not find my session factory. But why? Do i use the wrong dependency? I have configured Hibernate5 session factory and transaction manager as a bean.

Here are part os my pom:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>

    </parent>

    <groupId>test</groupId>
    <artifactId>testApp</artifactId>
    <name>testApp</name>
    <version>1.0-SNAPSHOT</version>

    <properties>

        <hibernate.version>5.2.9.Final</hibernate.version>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <maven-compiler-plugin.version>3.6.1</maven-compiler-plugin.version>
        <maven-source-plugin.version>3.0.1</maven-source-plugin.version>
        <maven-javadoc-plugin.version>2.10.4</maven-javadoc-plugin.version>
        <maven-install-plugin.version>2.5.2</maven-install-plugin.version>
        <maven-assembly-plugin.version>3.0.0</maven-assembly-plugin.version>

        <java.version>1.8</java.version>

        <start-class>org.testApp.core.Application</start-class>

    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
        </dependency>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
        </dependency>

        <!-- Thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>

        <!-- Tomcat -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-websocket</artifactId>
        </dependency>

        <!-- Hibernate -->

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>

        <!-- Apache -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

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

      <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.3</version>
      </dependency>

      <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-neo4j</artifactId>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-gemfire</artifactId>
      </dependency>
      <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
      </dependency>
    </dependencies>

</project>
</code>```

here is how i start my App

```<code>@ComponentScan({"org.testApp.*"})
@Configuration
@EnableAutoConfiguration
@EnableWebSocket
@SpringBootApplication
public class Application extends SpringBootServletInitializer  {
...
</code>```

Addition 29 March 2017

After analyzing the startup config i found the line:

```<code>2017-03-29 10:45:01.084  INFO 11022 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'sessionFactory' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=persistenceConfigDevelopment; factoryMethodName=sessionFactory; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/testApp/config/persistence/PersistenceConfigDevelopment.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration; factoryMethodName=sessionFactory; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.class]]
</code>```

What i do not understand is why Neo4jDataAutoConfiguration.class is overriding my custom persistenceConfigDevelopment bean.

Moreover if I remove the @EnableAutoConfiguration and  @SpringBootApplication on my main Application class then the app start and the correct session factory is being successfully instantiated but then it fails since it can not find a bean InternalResourceViewResolver, but this is expected since usually @EnableAutoConfiguration is taking care of those beans.

```<code>`Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type` 'org.springframework.web.servlet.view.InternalResourceViewResolver' available
</code>```

答:
I found a solution to my problem i.e

removed anything from the pom that is referencing neo4j i.e.

```<code>  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-neo4j</artifactId>
  </dependency>
</code>```

then add to the main application class the following exclude:

```<code>@SpringBootApplication(exclude = JpaRepositoriesAutoConfiguration.class)
public class Application extends SpringBootServletInitializer  {
</code>```

I do not know yet where exactly the error is however i know for sure that when i remove the spring-data-neo4j all works well and all my test pass.

Body:
I had a working spring boot app and I am trying to migration from Spring boot 1.3.8.RELEASE to 1.5.2.RELEASE.  In my working 1.3.8.RELEASE track  I was using hibernate 5 already i.e. i had the the following dependency in y pom

     <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-java8</artifactId>
         <version>${hibernate.version}</version>
     </dependency>

with Spring boot 1.5 this is not needed thus i change this to the default hibernate 5 dependency i.e. hibernate-core and removed the version declaration.

<dependency>
     <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
</dependency>

However i can not figure out why my test is saying:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

I have definitely configured the session factory

@Profile("Development")
@Configuration
@EnableTransactionManagement
@Order(value=1)
public class PersistenceConfigDevelopment {

    @Bean
    public org.apache.commons.dbcp.BasicDataSource dataSourceReadWrite() {

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/testDB");
        dataSource.setUsername("admin");
        dataSource.setPassword("veryBigSecret!");
        dataSource.setInitialSize(20);
        dataSource.setMaxActive(-1);

        return dataSource;
    }

    @Bean
    public org.springframework.orm.hibernate5.LocalSessionFactoryBean sessionFactory() {

        org.springframework.orm.hibernate5.LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(this.dataSourceReadWrite());
        sessionFactory.setPackagesToScan("org.testApp");
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

       @Bean
       public  org.springframework.orm.hibernate5.HibernateTransactionManager  transactionManager() {
          HibernateTransactionManager txManager = new HibernateTransactionManager();
          txManager.setSessionFactory(sessionFactory().getObject());
          return txManager;
       }

       @Bean
       public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
          return new PersistenceExceptionTranslationPostProcessor();
       }

    @Bean
    public  Properties hibernateProperties() {

    return new Properties() {

        {
                setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
                setProperty("hibernate.chach.provider_class", "org.hibernate.cache.NoCacheProvider");
                setProperty("hibernate.show_sql", "true");
                setProperty("hibernate.hbm2ddl.auto", "create-drop");

                setProperty("hibernate.cache.use_second_level_cache", "false");
                setProperty("hibernate.cache.use_query_cache", "false");

                //isolation level
                setProperty("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_SERIALIZABLE));

             }
          };
       }

}

here is how i start my spring boot 1.5.2 test:

@RunWith(SpringRunner.class)
@TestExecutionListeners(listeners={
                                    DependencyInjectionTestExecutionListener.class,
                                    DirtiesContextTestExecutionListener.class,
                                    WithSecurityContextTestExecutionListener.class
                                    }
        )
@SpringBootTest(
        classes = {
        SecurityWebApplicationInitializerDevelopment.class,
        SecurityConfigDevelopment.class,
        TomcatEmbededDevelopmentProfile.class,
        Internationalization.class,
        MVCConfigDevelopment.class,
        PersistenceConfigDevelopment.class,
        }

    )
@WebAppConfiguration
@ActiveProfiles(TestAppConfigurationProfiles.DEVELOPMENT_PROFILE)
@WithMockUser(username="alice",roles={"USER","ADMIN"} )
public class mainTests {
     ......

for some reason Spring boot 1.5 does not find my session factory. But why? Do i use the wrong dependency? I have configured Hibernate5 session factory and transaction manager as a bean.

Here are part os my pom:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>

    </parent>

    <groupId>test</groupId>
    <artifactId>testApp</artifactId>
    <name>testApp</name>
    <version>1.0-SNAPSHOT</version>

    <properties>

        <hibernate.version>5.2.9.Final</hibernate.version>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <maven-compiler-plugin.version>3.6.1</maven-compiler-plugin.version>
        <maven-source-plugin.version>3.0.1</maven-source-plugin.version>
        <maven-javadoc-plugin.version>2.10.4</maven-javadoc-plugin.version>
        <maven-install-plugin.version>2.5.2</maven-install-plugin.version>
        <maven-assembly-plugin.version>3.0.0</maven-assembly-plugin.version>

        <java.version>1.8</java.version>

        <start-class>org.testApp.core.Application</start-class>

    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
        </dependency>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
        </dependency>

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

        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

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

      <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.3</version>
      </dependency>

      <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-neo4j</artifactId>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-gemfire</artifactId>
      </dependency>
      <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
      </dependency>
    </dependencies>

</project>

here is how i start my App

@ComponentScan({"org.testApp.*"})
@Configuration
@EnableAutoConfiguration
@EnableWebSocket
@SpringBootApplication
public class Application extends SpringBootServletInitializer  {
...

Addition 29 March 2017

After analyzing the startup config i found the line:

2017-03-29 10:45:01.084  INFO 11022 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'sessionFactory' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=persistenceConfigDevelopment; factoryMethodName=sessionFactory; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/testApp/config/persistence/PersistenceConfigDevelopment.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration; factoryMethodName=sessionFactory; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.class]]

What i do not understand is why Neo4jDataAutoConfiguration.class is overriding my custom persistenceConfigDevelopment bean.

Moreover if I remove the @EnableAutoConfiguration and  @SpringBootApplication on my main Application class then the app start and the correct session factory is being successfully instantiated but then it fails since it can not find a bean InternalResourceViewResolver, but this is expected since usually @EnableAutoConfiguration is taking care of those beans.

`Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type` 'org.springframework.web.servlet.view.InternalResourceViewResolver' available

Body:
I found a solution to my problem i.e

removed anything from the pom that is referencing neo4j i.e.

  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-neo4j</artifactId>
  </dependency>

then add to the main application class the following exclude:

@SpringBootApplication(exclude = JpaRepositoriesAutoConfiguration.class)
public class Application extends SpringBootServletInitializer  {

I do not know yet where exactly the error is however i know for sure that when i remove the spring-data-neo4j all works well and all my test pass.


问:
Android Square Picasso not load persian character image url
I want to create web application by square picasso, but if image url contains persian characters (ا،ب،ج،ی، ...) Picasso not load image.

This url not working:

```<code>        Picasso.with(mContext).load("http://www.shutterstock.ir/thumbs/10006/74601661-گربه-چشم-ابی-ولاغر-سیامی-در-یک-پس-زمینه-،-وکتور-سفید.jpg")
    .placeholder(R.drawable.ic_launcher)
    .error(R.drawable.face_top_image).noFade().resize(100, 100)
    .into(imageView);
</code>```

This url work

```<code>        Picasso.with(mContext).load("http://www.shutterstock.ir/thumbs/10006/74601661-%DA%AF%D8%B1%D8%A8%D9%87-%DA%86%D8%B4%D9%85-%D8%A7%D8%A8%DB%8C-%D9%88%D9%84%D8%A7%D8%BA%D8%B1-%D8%B3%DB%8C%D8%A7%D9%85%DB%8C-%D8%AF%D8%B1-%DB%8C%DA%A9-%D9%BE%D8%B3-%D8%B2%D9%85%DB%8C%D9%86%D9%87-%D8%8C-%D9%88%DA%A9%D8%AA%D9%88%D8%B1-%D8%B3%D9%81%DB%8C%D8%AF.jpg")
    .placeholder(R.drawable.ic_launcher)
    .error(R.drawable.face_top_image).noFade().resize(100, 100)
    .into(imageView);
</code>```

答:
just use from this function

```<code> public static String encodUrl(String url){
            String[] splitUrl = url.split("/");
            String imageName = splitUrl[splitUrl.length-1];//get name of file
            String mainUrl = url.replaceAll(imageName , "");//get url without file name bacause dont need to encode

            return (mainUrl + Uri.encode(imageName));
        }
</code>```

Body:
I want to create web application by square picasso, but if image url contains persian characters (ا،ب،ج،ی، ...) Picasso not load image.

This url not working:

        Picasso.with(mContext).load("http://www.shutterstock.ir/thumbs/10006/74601661-گربه-چشم-ابی-ولاغر-سیامی-در-یک-پس-زمینه-،-وکتور-سفید.jpg")
    .placeholder(R.drawable.ic_launcher)
    .error(R.drawable.face_top_image).noFade().resize(100, 100)
    .into(imageView);

This url work

        Picasso.with(mContext).load("http://www.shutterstock.ir/thumbs/10006/74601661-%DA%AF%D8%B1%D8%A8%D9%87-%DA%86%D8%B4%D9%85-%D8%A7%D8%A8%DB%8C-%D9%88%D9%84%D8%A7%D8%BA%D8%B1-%D8%B3%DB%8C%D8%A7%D9%85%DB%8C-%D8%AF%D8%B1-%DB%8C%DA%A9-%D9%BE%D8%B3-%D8%B2%D9%85%DB%8C%D9%86%D9%87-%D8%8C-%D9%88%DA%A9%D8%AA%D9%88%D8%B1-%D8%B3%D9%81%DB%8C%D8%AF.jpg")
    .placeholder(R.drawable.ic_launcher)
    .error(R.drawable.face_top_image).noFade().resize(100, 100)
    .into(imageView);

Body:
just use from this function

 public static String encodUrl(String url){
            String[] splitUrl = url.split("/");
            String imageName = splitUrl[splitUrl.length-1];//get name of file
            String mainUrl = url.replaceAll(imageName , "");//get url without file name bacause dont need to encode

            return (mainUrl + Uri.encode(imageName));
        }


问:
How to force a hook function in a properties getter?
This question is re-edited from scratch. After a lot trials, I find that the main problem is designing a protocol which guarantees to execute a hook function before its certain property is accessed.

```<code>protocol Foo {
    var bar: Int { get }
    func hook()
}
</code>```

And I want the following test to pass:

```<code>func testBarGetterShouldInvokeHooker() {
    class DummyFoo: Foo {
        var bar: Int = 0
        var invoked: Bool = false
        func hook() {
            invoked = true
        }
    }
    let foo = DummyFoo()
    _ = foo.bar
    XCTAssertTrue(foo.invoked)
}
</code>```

Yes, I want that hook function to be hooked up automatically, that is -- not relying on the implementation struct/class to hook it explicitly.

I think this might be achieved by writing some nice extensions.

答:
Let's start by saying that your code has some errors, the main one is: where are you calling hook()?

There are some basic consideration to do. To get the get of bar called, bar has to be a computed property. To make it more generic, you should implement this variable in the protocol extension (by conforming, the behavior will be implemented by default).
How to provide the Int value? With a method, or an another variable

```<code>protocol Foo {
    func getBarValue() -> Int
    var invoked: Bool { get set }
}

extension Foo {

    var bar: Int {
        mutating get {
            hook()
            return getBarValue()
        }
    }

    mutating func hook() {
        print("Hook called")
        invoked = true
    }
}
</code>```

The conform to the protocol

```<code>struct MyStruct: Foo {

    var invoked = false

    func getBarValue() -> Int {
        return 1
    }
}

var foo = MyStruct()
_ = foo.bar
</code>```

Body:
This question is re-edited from scratch. After a lot trials, I find that the main problem is designing a protocol which guarantees to execute a hook function before its certain property is accessed.

protocol Foo {
    var bar: Int { get }
    func hook()
}

And I want the following test to pass:

func testBarGetterShouldInvokeHooker() {
    class DummyFoo: Foo {
        var bar: Int = 0
        var invoked: Bool = false
        func hook() {
            invoked = true
        }
    }
    let foo = DummyFoo()
    _ = foo.bar
    XCTAssertTrue(foo.invoked)
}

Yes, I want that hook function to be hooked up automatically, that is -- not relying on the implementation struct/class to hook it explicitly.

I think this might be achieved by writing some nice extensions.

Body:
Let's start by saying that your code has some errors, the main one is: where are you calling hook()?

There are some basic consideration to do. To get the get of bar called, bar has to be a computed property. To make it more generic, you should implement this variable in the protocol extension (by conforming, the behavior will be implemented by default).
How to provide the Int value? With a method, or an another variable

protocol Foo {
    func getBarValue() -> Int
    var invoked: Bool { get set }
}

extension Foo {

    var bar: Int {
        mutating get {
            hook()
            return getBarValue()
        }
    }

    mutating func hook() {
        print("Hook called")
        invoked = true
    }
}

The conform to the protocol

struct MyStruct: Foo {

    var invoked = false

    func getBarValue() -> Int {
        return 1
    }
}

var foo = MyStruct()
_ = foo.bar


答:
There are two methods of doing this-

Method 1-  Targetting the li through nth-child selector property.

```<code>.nav li:nth-child(2) {
    display: none;
}
</code>```

Method 2- You can also target the li with title attribute.

```<code>.nav a[title=Contact] {
        display: none;
    }
</code>```

Title: How to hide menu element with only CSS

Body:
There are two methods of doing this-

Method 1-  Targetting the li through nth-child selector property.

.nav li:nth-child(2) {
    display: none;
}

Method 2- You can also target the li with title attribute.

.nav a[title=Contact] {
        display: none;
    }


问:
Delete comment link not working (acts_as_commentable)
In my Rails app, each post has a comment section where users can leave comments. I want each comment to have a delete link but I just can't get it to work. I am using the acts_as_commentable gem here.

posts/show.html.erb

```<code><% @comments.each do |comment| %>
  <p><strong><%= comment.user.username %></strong></p>
  <p class="comment"><%= comment.comment %><p>
  <%= link_to "Delete", [@post, comment], method: :delete %>
<% end %>
</code>```

I need help with this line

```<code><%= link_to("Delete", [@post, comment], method: :delete %>
</code>```

comments_controller.rb

```<code>def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comment_params)
  @comment.user_id = current_user.id
end

def destroy
  @comment = Comment.find(params[:id])
  redirect_to :back
end
</code>```

Thanks for your help! :)

答:
change destroy action something like this:

```<code>def destroy
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
  @comment.destroy
  redirect_to :back
end
</code>```

In this way you can make sure you are deleting comment related to specific post. It's rails proffered way you can look at it here .

Body:
In my Rails app, each post has a comment section where users can leave comments. I want each comment to have a delete link but I just can't get it to work. I am using the acts_as_commentable gem here.

posts/show.html.erb

<% @comments.each do |comment| %>

<%= comment.user.username %>

<%= comment.comment %>

  <%= link_to "Delete", [@post, comment], method: :delete %>
<% end %>

I need help with this line

<%= link_to("Delete", [@post, comment], method: :delete %>

comments_controller.rb

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comment_params)
  @comment.user_id = current_user.id
end

def destroy
  @comment = Comment.find(params[:id])
  redirect_to :back
end

Thanks for your help! :)

Body:
change destroy action something like this:

def destroy
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
  @comment.destroy
  redirect_to :back
end

In this way you can make sure you are deleting comment related to specific post. It's rails proffered way you can look at it here .


问:
Android: Add divider between items in RecyclerView
I am using RecyclerView with rounded corner, to make it rounded corner I used below XML:

view_rounded.xml:-

```<code><?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#008f8471"/>
    <stroke android:width="2dp" android:color="#ffffff" />
    <corners android:radius="10dp"/>
</shape>
</code>```

fragment_main.xml:-

```<code><android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/view_rounded"/>
</code>```

adapter_main.xml:-

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textTitle"
        style="@style/AppTheme.ListTextView"
        />

</LinearLayout>
</code>```

style.xml:-

```<code><style name="AppTheme.ListTextView" parent="android:Widget.Material.TextView">
  <item name="android:gravity">left</item>
  <item name="android:layout_width">match_parent</item>
  <item name="android:layout_height">wrap_content</item>
  <item name="android:textAllCaps">false</item>
  <item name="android:padding">10dp</item>
  <item name="android:textAppearance">@android:style/TextAppearance.DeviceDefault.Medium</item>
  <item name="android:textColor">@color/tabsScrollColor</item>
  <item name="android:textStyle">bold</item>
</style>
</code>```

Getting (without item separator):

Required (with item separator):

答:
This line of code worked for me:

```<code>recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.HORIZONTAL));
</code>```

For vertical line, pass second argument as DividerItemDecoration.VERTICAL.

Body:
I am using RecyclerView with rounded corner, to make it rounded corner I used below XML:

view_rounded.xml:-

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#008f8471"/>
    <stroke android:width="2dp" android:color="#ffffff" />
    <corners android:radius="10dp"/>
</shape>

fragment_main.xml:-

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/view_rounded"/>

adapter_main.xml:-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textTitle"
        style="@style/AppTheme.ListTextView"
        />

</LinearLayout>

style.xml:-

Getting (without item separator):

Required (with item separator):

Body:
This line of code worked for me:

recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.HORIZONTAL));

For vertical line, pass second argument as DividerItemDecoration.VERTICAL.


问:
How to insert a record in Sqlite?
please anybody tell me how to insert records in sqlite through objective c?</p>

答:
If you're using FMDB (and honestly if you don't you're crazy), then it's really simple:</p>

```<code>FMDatabase* db = [FMDatabase databaseWithPath:@"/path/to/my/database.db"];
if ([db open]) {
  [db executeUpdate:@"insert into myTable (col1, col2) values (?, ?)", @"foo", [NSNumber numberWithInt:42]];
  [db close];
}
</code>```

Title: How to insert a record in Sqlite?

Body:
If you're using FMDB (and honestly if you don't you're crazy), then it's really simple:

FMDatabase* db = [FMDatabase databaseWithPath:@"/path/to/my/database.db"];
if ([db open]) {
  [db executeUpdate:@"insert into myTable (col1, col2) values (?, ?)", @"foo", [NSNumber numberWithInt:42]];
  [db close];
}


问:
ORA-00904: "PARAMETER": invalid identifier
I get a error, when I execute my SQL:

select bd.name aaa,

          sum(p.nassistnum) HH,sum(case when p.vbdef4='~' then '0' else p.vbdef4 end) KK

          from ic_purchasein_b p,bd_marbasclass bd,bd_material_v m ,ic_purchasein_h h

          where   m.pk_source=p.cmaterialvid
          and p.cgeneralhid= h.cgeneralhid

          and  bd.code=substr(m.code,0,4)

          and m.creator='1001A210000000000IIQ'

          and h.vdef8='1001A2100000000FUD01'

          and h.ctrantypeid='1001A210000000002UXJ'

          and h.pk_org in (parameter('param3'))

                          and substr(h.dbilldate,1,10) >= parameter('param1')

                          and substr(h.dbilldate,1,10) <= parameter('param2')

          group by bd.name) group by aaa

  [Err] ORA-00904: "PARAMETER": invalid identifier

My SQL is:

```<code>select DISTINCT aaa,sum(HH) sum1,sum(KK) sum2 from
   (   select bd.name aaa,
        sum(p.nassistnum) HH,sum(case when p.vbdef4='~' then '0' else p.vbdef4 end) KK
        from ic_purchasein_b p,bd_marbasclass bd,bd_material_v m ,ic_purchasein_h h
        where   m.pk_source=p.cmaterialvid
        and p.cgeneralhid= h.cgeneralhid
        and  bd.code=substr(m.code,0,4)
        and m.creator='1001A210000000000IIQ'
        and h.vdef8='~'
        and (h.ctrantypeid='1001A210000000002UXJ' or h.ctrantypeid='1001A210000000002UW7' or h.ctrantypeid='1001A210000000002UY9')
        and h.pk_org in (parameter('param3'))
                        and substr(h.dbilldate,1,10) >= parameter('param1')
                        and substr(h.dbilldate,1,10) <= parameter('param2')
        group by bd.name
  UNION
    select bd.name aaa,
        sum(p.nassistnum) HH,sum(case when p.vbdef4='~' then '0' else p.vbdef4 end) KK
        from ic_purchasein_b p,bd_marbasclass bd,bd_material_v m ,ic_purchasein_h h
        where   m.pk_source=p.cmaterialvid
        and p.cgeneralhid= h.cgeneralhid
        and  bd.code=substr(m.code,0,4)
        and m.creator='1001A210000000000IIQ'
        and h.vdef8='1001A2100000000FUD01'
        and h.ctrantypeid='1001A210000000002UXJ'
        and h.pk_org in (parameter('param3'))
                        and substr(h.dbilldate,1,10) >= parameter('param1')
                        and substr(h.dbilldate,1,10) <= parameter('param2')
        group by bd.name) group by aaa
</code>```

But I don't know where is the error, why my PARAMETER is invalid identifier?

答:
ORA-00904 string: invalid identifier Cause: The column name entered is
  either missing or invalid.

Action: Enter a valid column name. A valid column name must begin with
  a letter, be less than or equal to 30 characters, and consist of only
  alphanumeric characters and the special characters $, _, and #. If it
  contains other characters, then it must be enclosed in double
  quotation marks. It may not be a reserved word.

You might simply have to re-check your column names and functions in the query.

Oracle's manual

And definitely take @Alex Poole's comment into account.

Body:
I get a error, when I execute my SQL:

select bd.name aaa,

          sum(p.nassistnum) HH,sum(case when p.vbdef4='~' then '0' else p.vbdef4 end) KK

          from ic_purchasein_b p,bd_marbasclass bd,bd_material_v m ,ic_purchasein_h h

          where   m.pk_source=p.cmaterialvid
          and p.cgeneralhid= h.cgeneralhid

          and  bd.code=substr(m.code,0,4)

          and m.creator='1001A210000000000IIQ'

          and h.vdef8='1001A2100000000FUD01'

          and h.ctrantypeid='1001A210000000002UXJ'

          and h.pk_org in (parameter('param3'))

                          and substr(h.dbilldate,1,10) >= parameter('param1')

                          and substr(h.dbilldate,1,10) <= parameter('param2')

          group by bd.name) group by aaa

  [Err] ORA-00904: "PARAMETER": invalid identifier

My SQL is:

select DISTINCT aaa,sum(HH) sum1,sum(KK) sum2 from
   (   select bd.name aaa,
        sum(p.nassistnum) HH,sum(case when p.vbdef4='~' then '0' else p.vbdef4 end) KK
        from ic_purchasein_b p,bd_marbasclass bd,bd_material_v m ,ic_purchasein_h h
        where   m.pk_source=p.cmaterialvid
        and p.cgeneralhid= h.cgeneralhid
        and  bd.code=substr(m.code,0,4)
        and m.creator='1001A210000000000IIQ'
        and h.vdef8='~'
        and (h.ctrantypeid='1001A210000000002UXJ' or h.ctrantypeid='1001A210000000002UW7' or h.ctrantypeid='1001A210000000002UY9')
        and h.pk_org in (parameter('param3'))
                        and substr(h.dbilldate,1,10) >= parameter('param1')
                        and substr(h.dbilldate,1,10) <= parameter('param2')
        group by bd.name
  UNION
    select bd.name aaa,
        sum(p.nassistnum) HH,sum(case when p.vbdef4='~' then '0' else p.vbdef4 end) KK
        from ic_purchasein_b p,bd_marbasclass bd,bd_material_v m ,ic_purchasein_h h
        where   m.pk_source=p.cmaterialvid
        and p.cgeneralhid= h.cgeneralhid
        and  bd.code=substr(m.code,0,4)
        and m.creator='1001A210000000000IIQ'
        and h.vdef8='1001A2100000000FUD01'
        and h.ctrantypeid='1001A210000000002UXJ'
        and h.pk_org in (parameter('param3'))
                        and substr(h.dbilldate,1,10) >= parameter('param1')
                        and substr(h.dbilldate,1,10) <= parameter('param2')
        group by bd.name) group by aaa

But I don't know where is the error, why my PARAMETER is invalid identifier?


问:
odoo 9 Automatically changing the selection field and radio button field depends on the changed other selection field
I need a help please.
So I wanted when I change the Internal Category (field name is categ_id) value to 500 final product,

and then the Routes field changes to :
Manufacture checked,
Make To Order checked,
Buy checked

and also the Value of Tracking field is changes as well to:
By Lots checked

How can I do that? Any suggestion ? Or my is it my question are not clear enough ?
Sorry for asking , I never done this before so yeah kind a confusing.
Here I got the picture the interface and the information about the field as well.

Routes field name
Tracking field name

Please anyone kindly to help me. I am so confused.

答:
You could achieve this by using api onchange in Odoo 9.

```<code>@api.onchange('categ_id')
def onchange_categ_id(self):
  for record in self:
    # I prefer to check by id, but here I show how to check by string name in case you want it
    if record.categ_id.name == '500 final product':
      # because route_ids is many2many field,
      # you need special commands to change the value
      # here I use (6, _, ids) to set value.
      # But before that, you have to get the ids of the routes you want from model stock.location.route
      # (you could use search method to get the ids)
      record.route_ids = [(6,0, list_of_id)]
      record.tracking = 'lot'
      ...
</code>```

You could refer to Odoo Doc to learn more about O2m and M2m commands

Body:
You could achieve this by using api onchange in Odoo 9.

@api.onchange('categ_id')
def onchange_categ_id(self):
  for record in self:
    # I prefer to check by id, but here I show how to check by string name in case you want it
    if record.categ_id.name == '500 final product':
      # because route_ids is many2many field,
      # you need special commands to change the value
      # here I use (6, _, ids) to set value.
      # But before that, you have to get the ids of the routes you want from model stock.location.route
      # (you could use search method to get the ids)
      record.route_ids = [(6,0, list_of_id)]
      record.tracking = 'lot'
      ...

You could refer to Odoo Doc to learn more about O2m and M2m commands


问:
Twilio in Node-Red - getting below error
below is the complete command prompt error

```<code>29 Mar 22:16:20 - [info] Windows_NT 10.0.14393 x64 LE
29 Mar 22:16:21 - [info] Loading palette nodes
29 Mar 22:16:22 - [info] Dashboard version 2.3.5 started at /ui
29 Mar 22:16:22 - [warn] ------------------------------------------------------
29 Mar 22:16:22 - [warn] [rpi-gpio] Info : Ignoring Raspberry Pi specific node
29 Mar 22:16:22 - [warn] [tail] Not currently supported on Windows.
29 Mar 22:16:22 - [warn] [tcp] Error: tcp in already registered
29 Mar 22:16:22 - [warn] [udp] Error: udp out already registered
29 Mar 22:16:22 - [warn] [twilio] Error: twilio-api already registered
29 Mar 22:16:22 - [warn] ------------------------------------------------------
29 Mar 22:16:22 - [info] Settings file  : \Users\Charles\.node-red\settings.js
29 Mar 22:16:22 - [info] User directory : \Users\Charles\.node-red
29 Mar 22:16:22 - [info] Flows file     : \Users\Charles\.node-red\flows_LAPTOP-9T4HPKBK.json
29 Mar 22:16:22 - [info] Creating new flow file
29 Mar 22:16:22 - [info] Server now running at http://127.0.0.1:1880/
29 Mar 22:16:22 - [info] Starting flows
29 Mar 22:16:22 - [info] Started flows
express deprecated res.send(status): Use res.sendStatus(status) instead .node-red\node_modules\node-red-bluemix-nodes\twilio\56-    twilio-cf.js:64:13
29 Mar 22:27:56 - [info] Stopping flows
29 Mar 22:27:56 - [info] Stopped flows
29 Mar 22:27:56 - [info] Waiting for missing types to be registered:
29 Mar 22:27:56 - [info]  - twilio-api
29 Mar 22:27:56 - [info]  - twilio out
29 Mar 22:28:45 - [info] Stopping flows
29 Mar 22:28:45 - [info] Stopped flows
29 Mar 22:28:45 - [info] Waiting for missing types to be registered:
29 Mar 22:28:45 - [info]  - twilio-api
29 Mar 22:28:45 - [info]  - twilio out
</code>```

I am just using inject and twilio to send an SMS from my allotted phone number to my registered phone number in Node-Red

答:
You appear to have multiple copies of the Twillio, TCP & UDP nodes installed.

I would guess you have installed the Twillio node both locally and globally. You need to remove one of them.

How you've ended up with 2 copies of the TCP and UDP nodes is stranger as these are core nodes

Body:
below is the complete command prompt error

29 Mar 22:16:20 - [info] Windows_NT 10.0.14393 x64 LE
29 Mar 22:16:21 - [info] Loading palette nodes
29 Mar 22:16:22 - [info] Dashboard version 2.3.5 started at /ui
29 Mar 22:16:22 - [warn] ------------------------------------------------------
29 Mar 22:16:22 - [warn] [rpi-gpio] Info : Ignoring Raspberry Pi specific node
29 Mar 22:16:22 - [warn] [tail] Not currently supported on Windows.
29 Mar 22:16:22 - [warn] [tcp] Error: tcp in already registered
29 Mar 22:16:22 - [warn] [udp] Error: udp out already registered
29 Mar 22:16:22 - [warn] [twilio] Error: twilio-api already registered
29 Mar 22:16:22 - [warn] ------------------------------------------------------
29 Mar 22:16:22 - [info] Settings file  : \Users\Charles\.node-red\settings.js
29 Mar 22:16:22 - [info] User directory : \Users\Charles\.node-red
29 Mar 22:16:22 - [info] Flows file     : \Users\Charles\.node-red\flows_LAPTOP-9T4HPKBK.json
29 Mar 22:16:22 - [info] Creating new flow file
29 Mar 22:16:22 - [info] Server now running at http://127.0.0.1:1880/
29 Mar 22:16:22 - [info] Starting flows
29 Mar 22:16:22 - [info] Started flows
express deprecated res.send(status): Use res.sendStatus(status) instead .node-red\node_modules\node-red-bluemix-nodes\twilio\56-    twilio-cf.js:64:13
29 Mar 22:27:56 - [info] Stopping flows
29 Mar 22:27:56 - [info] Stopped flows
29 Mar 22:27:56 - [info] Waiting for missing types to be registered:
29 Mar 22:27:56 - [info]  - twilio-api
29 Mar 22:27:56 - [info]  - twilio out
29 Mar 22:28:45 - [info] Stopping flows
29 Mar 22:28:45 - [info] Stopped flows
29 Mar 22:28:45 - [info] Waiting for missing types to be registered:
29 Mar 22:28:45 - [info]  - twilio-api
29 Mar 22:28:45 - [info]  - twilio out

I am just using inject and twilio to send an SMS from my allotted phone number to my registered phone number in Node-Red


问:
How to store data (notes, assignees) to recurring events generated using RRULE
I'm building a calendar application that allows users to create recurring events.

Instead of creating a new object in MongoDB for each recurring event, I am creating a single event object with a recurrence rule attached to it.

Then on the client I am 'expanding' the recurrence rule to create temporary objects for each recurrence of the event so they all display in the calendar.

That all works really well and prevents my DB from filling up with hundreds of objects any time an event recurs frequently. My question is: how can I then store data against each recurring event? For example, playing around with Google calendar I can create a recurring event and then add 'notes' to each recurrence. The notes can either be added to a single event or all events.

My thoughts so far are when a user wants to add 'notes', to add an EXDATE for the recurrence the user is editing, then create a new standalone event object for it.

I'm not sure if that's the best way to approach this though. Advice much appreciated.

答:
In terms of iCalendar representation, the correct way to model such exception is to have it be part of the same event (same UID), with an additional RECURRENCE-ID parameter. You should not add an EXDATE:

```<code>BEGIN:VEVENT
UID:XXX
DTSTART;TZID=zzz:20170401T090000
RRULE:FREQ=DAILY
...
END:VEVENT
BEGIN:VEVENT
UID:XXX
RECURRENCE-ID;TZID=zzz:20170405T090000
DTSTART;TZID=zzz:20170405T090000
...
END:VEVENT
</code>```

Please note that the RECURRENCE-ID of the exception should always correspond to the datetime as calculated from the RRULE, while the DTSTART of the exception may differ (e.g. if on one instance you move the time of the event from 9 to 10, the RECURRENCE-ID will be T090000 while the DTSTART would have T100000.

See also https://www.rfc-editor.org/rfc/rfc5546#section-4.4.2

Body:
In terms of iCalendar representation, the correct way to model such exception is to have it be part of the same event (same UID), with an additional RECURRENCE-ID parameter. You should not add an EXDATE:

BEGIN:VEVENT
UID:XXX
DTSTART;TZID=zzz:20170401T090000
RRULE:FREQ=DAILY
...
END:VEVENT
BEGIN:VEVENT
UID:XXX
RECURRENCE-ID;TZID=zzz:20170405T090000
DTSTART;TZID=zzz:20170405T090000
...
END:VEVENT

Please note that the RECURRENCE-ID of the exception should always correspond to the datetime as calculated from the RRULE, while the DTSTART of the exception may differ (e.g. if on one instance you move the time of the event from 9 to 10, the RECURRENCE-ID will be T090000 while the DTSTART would have T100000.

See also https://www.rfc-editor.org/rfc/rfc5546#section-4.4.2


问:
How do I call all comments for a post (workout in this case) where workout.user_id == current_user.id?
I have created a Ruby on Rails app where users can record their workouts and other users can comment on those workouts. I am using a Dashboard resource to aggregate information for current_user. I am trying to display recent comments on a current_user's workouts but can't seem to figure out how to do this correctly. I think I need a named_scope which I am not great at yet.

I essentially want the app to loop through the comments table but only return comments on Workouts where workout.user_id == to current_user.id.

/views/dashboard/index.html.erb

```<code><% @comments.each do |comment| %>
  <%= link_to (comment.user.username), comment.user %><br/>
  <%= time_ago_in_words(comment.created_at) %><br/>
  <%= link_to (comment.workout.title), comment.workout %><br/>
<% end %>
</code>```

dashboard_controller.rb

```<code>def index
  @comments = Comment.all(:order => "created_at DESC", :limit => 10)
  @workouts = Workout.all(:order => "created_at DESC", :limit => 10)
end
</code>```

*I don't think I need the @workouts line in their but put it anyway.

答:
The proper way to do is to put relations between your models, i.e. comment and workout. Each workout can have many comments, and each comment belongs to a workout. So:

```<code>class Comment < ActiveRecord::Base
      belongs_to :workout

      # rest of the model definitions
end
</code>```

and

```<code>class Workout < ActiveRecord::Base
      has_many :comments

      # rest of the model definitions
end
</code>```

Once you set it up like this, then you can call:

```<code><% @workout.comments do |comment| %>
   <!-- print comment here -->
<% end %>
</code>```

You can follow the example here.

Body:
I have created a Ruby on Rails app where users can record their workouts and other users can comment on those workouts. I am using a Dashboard resource to aggregate information for current_user. I am trying to display recent comments on a current_user's workouts but can't seem to figure out how to do this correctly. I think I need a named_scope which I am not great at yet.

I essentially want the app to loop through the comments table but only return comments on Workouts where workout.user_id == to current_user.id.

/views/dashboard/index.html.erb

<% @comments.each do |comment| %>
  <%= link_to (comment.user.username), comment.user %>

  <%= time_ago_in_words(comment.created_at) %>

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

<% end %>

dashboard_controller.rb

def index
  @comments = Comment.all(:order => "created_at DESC", :limit => 10)
  @workouts = Workout.all(:order => "created_at DESC", :limit => 10)
end

*I don't think I need the @workouts line in their but put it anyway.

Body:
The proper way to do is to put relations between your models, i.e. comment and workout. Each workout can have many comments, and each comment belongs to a workout. So:

class Comment < ActiveRecord::Base
      belongs_to :workout

      # rest of the model definitions
end

and

class Workout < ActiveRecord::Base
      has_many :comments

      # rest of the model definitions
end

Once you set it up like this, then you can call:

<% @workout.comments do |comment| %>
   <!-- print comment here -->
<% end %>

You can follow the example here.


问:
Eclipse "Show Proposal" key combination not working for Java or C
I recently downloaded Eclipse, and when I press Ctrl+Space, it does not show any proposal.

For example, if I have a variable named TotalElements and in another place in the code, when I type Tota and then press ctrl-space it should propose TotalElements.  However, it does not do this.

I have gone to windows -> preferences > java -> editor -> advance.  I have everything checked, and it still does not work.

Am I missing some plugins?

thanks in advance!

答:
Kindly make sure that your using correct explorer.
Below is the reference image for you. If 'J' icon is hollow than no proposal will display.


问:
How to use php serialize() and unserialize()
My problem is very basic.

I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.

EDIT:

```<code><?php

$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);

?>
</code>```

output:

```<code>Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
</code>```

I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?

答:
```<code><?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);
</code>```

Run this program its echo the output

```<code>a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
</code>```

Note: Set allowed_classes to false in unserialize for security reasons.

here

a=size of array

i=count of array number

s=size of array values

you can use serialize to store array of data in database
and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php

ContentLicense: CC BY-SA 4.0

Body:
My problem is very basic.

I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.

EDIT:

<?php

$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("

");
$b=serialize($a);
print_r($b);

?>

output:

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?

Body:
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);

Run this program its echo the output

a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}

Note: Set allowed_classes to false in unserialize for security reasons.

here

a=size of array

i=count of array number

s=size of array values

you can use serialize to store array of data in database
and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php


问:
jquery if checkbox checked add value true
How to make jquery click function if checkBox checked then status value set to 'true', if not cheked value set to 'false'?

if I check checkbox 1 , then status 1 set to true
if I check checkbox 2 , then status 2 set to true
if I check checkbox 3 , then status 3 set to true

  <input name="checkBox[]" type="checkbox" value="1"> Checkbox 1
   <input name="status[]" type="text" value="">

   <input name="checkBox[]" type="checkbox" value="2"> Checkbox 2
   <input name="status[]" type="text" value="">

  <input name="checkBox[]" type="checkbox" value="3"> Checkbox 3
   <input name="status[]" type="text" value="">

```

答:
Try this : </p>

```<code>$('input[type="checkbox"]').change(function() {
    if($(this).prop('checked')){
       $(this).parent().next().val("true");
    }else{
       $(this).parent().next().val("false");
    }
});
</code>```

Body:
Try this :

$('input[type="checkbox"]').change(function() {
    if($(this).prop('checked')){
       $(this).parent().next().val("true");
    }else{
       $(this).parent().next().val("false");
    }
});


问:
Multiple workers in Swift Command Line Tool
When writing a Command Line Tool (CLT) in Swift, I want to process a lot of data. I've determined that my code is CPU bound and performance could benefit from using multiple cores. Thus I want to parallelize parts of the code. Say I want to achieve the following pseudo-code:

```<code>Fetch items from database
Divide items in X chunks
Process chunks in parallel
Wait for chunks to finish
Do some other processing (single-thread)
</code>```

Now I've been using GCD, and a naive approach would look like this:

```<code>let group = dispatch_group_create()
let queue = dispatch_queue_create("", DISPATCH_QUEUE_CONCURRENT)
for chunk in chunks {
    dispatch_group_async(group, queue) {
        worker(chunk)
    }
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
</code>```

However GCD requires a run loop, so the code will hang as the group is never executed. The runloop can be started with dispatch_main(), but it never exits. It is also possible to run the NSRunLoop just a few seconds, however that doesn't feel like a solid solution. Regardless of GCD, how can this be achieved using Swift?

答:
Swift 3 minimal implementation of Aaron Brager solution, which simply combines autoreleasepool and RunLoop.current.run(...) until you break the loop:

```<code>var shouldExit = false
doSomethingAsync() { _ in
    defer {
        shouldExit = true
    }
}
autoreleasepool {
    var runLoop = RunLoop.current
    while (!shouldExit && (runLoop.run(mode: .defaultRunLoopMode, before: Date.distantFuture))) {}
}
</code>```

Body:
When writing a Command Line Tool (CLT) in Swift, I want to process a lot of data. I've determined that my code is CPU bound and performance could benefit from using multiple cores. Thus I want to parallelize parts of the code. Say I want to achieve the following pseudo-code:

Fetch items from database
Divide items in X chunks
Process chunks in parallel
Wait for chunks to finish
Do some other processing (single-thread)

Now I've been using GCD, and a naive approach would look like this:

let group = dispatch_group_create()
let queue = dispatch_queue_create("", DISPATCH_QUEUE_CONCURRENT)
for chunk in chunks {
    dispatch_group_async(group, queue) {
        worker(chunk)
    }
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)

However GCD requires a run loop, so the code will hang as the group is never executed. The runloop can be started with dispatch_main(), but it never exits. It is also possible to run the NSRunLoop just a few seconds, however that doesn't feel like a solid solution. Regardless of GCD, how can this be achieved using Swift?

Body:
Swift 3 minimal implementation of Aaron Brager solution, which simply combines autoreleasepool and RunLoop.current.run(...) until you break the loop:

var shouldExit = false
doSomethingAsync() { _ in
    defer {
        shouldExit = true
    }
}
autoreleasepool {
    var runLoop = RunLoop.current
    while (!shouldExit && (runLoop.run(mode: .defaultRunLoopMode, before: Date.distantFuture))) {}
}


问:
slidify embeds plotly plots as images rather than as normal interactive plots
I am trying to include some plots built using plotly in slides generated from .Rmd using slidify.

The problem is that the plots are rendered as images instead of being interactive.

On the same .Rmd file if instead of using slidify to produce html slides I use knitr to produce an ordinary html pages the plotly plots are interactive.

To produce the slides (with plot images instead of desired normal itneractive plot) I am using slidify with the following commands:

```<code>slidify("a.Rmd"); browseURL("b.html")
</code>```

To produce the normal html page (that correctly shows the interactive plotly plots) I am using:

```<code>rmarkdown::render("a.Rmd"); browseURL("a.html")
</code>```

答:
you can save your widget

htmlwidgets::saveWidget(as.widget(p), file = "plot.html")

then insert it in the slidify in an iframe, more info here

https://plot.ly/r/embedding-plotly-graphs-in-HTML/

Body:
I am trying to include some plots built using plotly in slides generated from .Rmd using slidify.

The problem is that the plots are rendered as images instead of being interactive.

On the same .Rmd file if instead of using slidify to produce html slides I use knitr to produce an ordinary html pages the plotly plots are interactive.

To produce the slides (with plot images instead of desired normal itneractive plot) I am using slidify with the following commands:

slidify("a.Rmd"); browseURL("b.html")

To produce the normal html page (that correctly shows the interactive plotly plots) I am using:

rmarkdown::render("a.Rmd"); browseURL("a.html")


问:
React / Redux conditionally applying style
In my React & Redux App, I am trying to show/hide a div based on state returned by Redux. Here is my code:

```<code><div
    className="notify-success"
    style={{  ({this.props.terms}) ? "" : "display: 'none'" }}
>
    Saved successfully!
</div>
</code>```

But its not working for me, instead throwing an error!

答:
try using classnames for better practice

```<code>  classNames('foo', 'bar'); // => 'foo bar'
  classNames('foo', { bar: true }); // => 'foo bar'
  classNames({ 'foo-bar': true }); // => 'foo-bar'
  classNames({ 'foo-bar': false }); // => ''
  classNames({ foo: true }, { bar: true }); // => 'foo bar'
  classNames({ foo: true, bar: true }); // => 'foo bar'
</code>```

refer this linkclassnames

this will return you className generated you can put this in render method and as your variable changes this will get updated as you want.

Body:
In my React & Redux App, I am trying to show/hide a div based on state returned by Redux. Here is my code:

    Saved successfully!

But its not working for me, instead throwing an error!

Body:
try using classnames for better practice

  classNames('foo', 'bar'); // => 'foo bar'
  classNames('foo', { bar: true }); // => 'foo bar'
  classNames({ 'foo-bar': true }); // => 'foo-bar'
  classNames({ 'foo-bar': false }); // => ''
  classNames({ foo: true }, { bar: true }); // => 'foo bar'
  classNames({ foo: true, bar: true }); // => 'foo bar'

refer this linkclassnames

this will return you className generated you can put this in render method and as your variable changes this will get updated as you want.


问:
Writing a request for the number of hired/fired each year
I'm trying to write an SQL request to count the number of Employees hired/fired each year.

I can have each Employee's dates with this select:

```<code>SELECT HiredDate, FiredDate FROM Employees;
</code>```

I can list each year with this select:

```<code>SELECT to_char(e1.HiredDate, 'YYYY') Year FROM Employees e1
UNION
SELECT to_char(e2.FiredDate, 'YYYY') Year FROM Employees e2;
</code>```

But I don't manage to count the number of hired/fired each year.

EDIT

Employees sample data:

```<code>Name   | HiredDate  | FiredDate
--------------------------------
John   | 01/02/2003 | 03/04/2013
Jack   | 05/06/2006 | 07/08/2013
Jean   | 03/04/2006 | null
James  | 01/02/2013 | null
</code>```

Expected results:

```<code>Year | HiredNumber | FiredNumber
---------------------------------
2003 |           1 |           0
2006 |           2 |           0
2013 |           1 |           2
</code>```

答:
```<code>SELECT 'Hired' What, to_char(e1.HiredDate, 'YYYY') Year, COUNT(*) TheCount
FROM Employees e1
GROUP BY to_char(e1.HiredDate, 'YYYY')
UNION ALL
SELECT 'Fired' What, to_char(e2.FiredDate, 'YYYY') Year, COUNT(*) TheCount
FROM Employees e2
GROUP BY to_char(e2.FiredDate, 'YYYY');
</code>```

Body:
I'm trying to write an SQL request to count the number of Employees hired/fired each year.

I can have each Employee's dates with this select:

SELECT HiredDate, FiredDate FROM Employees;

I can list each year with this select:

SELECT to_char(e1.HiredDate, 'YYYY') Year FROM Employees e1
UNION
SELECT to_char(e2.FiredDate, 'YYYY') Year FROM Employees e2;

But I don't manage to count the number of hired/fired each year.

EDIT

Employees sample data:

Name   | HiredDate  | FiredDate
--------------------------------
John   | 01/02/2003 | 03/04/2013
Jack   | 05/06/2006 | 07/08/2013
Jean   | 03/04/2006 | null
James  | 01/02/2013 | null

Expected results:

Year | HiredNumber | FiredNumber
---------------------------------
2003 |           1 |           0
2006 |           2 |           0
2013 |           1 |           2


问:
security warning window in IE pops up on https page
My problem is with IE.
When I search product (means when I enter product name in search box) from viewcart page before products are displayed the security warning window is getting popup:

Do you want to view only the webpage contect that was delivered securly?
  This web page contain secure HTTPS connection.

My viewcart page has url https:localhost:52470/173_201_149_151/ViewCart.aspx
and Search page has also https.

I know that security warning is displayed due to https but I dont want this security window.
Is there any way to avoid this security warning window?

答:
This usually occurs when your page URL protocol is HTTPS, but you have resources embedded in the page i.e. CSS, JavaScript, images etc, that have hardcoded protocols of HTTP.

This is quite easy to embed the correct protocol server-side in ASP.NET via Request.Url.Scheme.

When embedding third party JavaScript includes, you can use javascript to embed the correct protocol, for example:

```<code><script type="text/javascript">
    var protocol = (("https:" == document.location.protocol) ? "https" : "http");
    document.write(unescape("%3Cscript src='" + protocol + "third-party.com/script.js' type='text/javascript'%3E%3C/script%3E"));
</script>
</code>```

If you are having trouble tracking down the insecure resources, I would recommend using Fiddler2, a debugging proxy, which will highlight the issues.

Body:
This usually occurs when your page URL protocol is HTTPS, but you have resources embedded in the page i.e. CSS, JavaScript, images etc, that have hardcoded protocols of HTTP.

This is quite easy to embed the correct protocol server-side in ASP.NET via Request.Url.Scheme.

When embedding third party JavaScript includes, you can use javascript to embed the correct protocol, for example:

<script type="text/javascript">
    var protocol = (("https:" == document.location.protocol) ? "https" : "http");
    document.write(unescape("%3Cscript src='" + protocol + "third-party.com/script.js' type='text/javascript'%3E%3C/script%3E"));
</script>

If you are having trouble tracking down the insecure resources, I would recommend using Fiddler2, a debugging proxy, which will highlight the issues.


问:
should I use fragment or viewpager for my app
Demo1
Demo2

when users click the button to answer the questions for the TextView on the top, the TextView will change the questions depends on the user's answer.
(I think this part won't be hard for me)

But what should I do after user click the button, the buttons will change as well, please see the demo picture.

are there any skills I should study first? like framelayout?

Thank you for your answers.

答:
you can create a N fragement with your nuber Button and you set your buttons in this fragement (Demo 1)
but in click a one button you can replace a Specific Fragment (Demo 2) in your framelayout be placed in your Activity  </p>


问:
How to hide a div from code (c#)
I have a div element on my page that I wish to show/hide based on a session value in my code-behind. How can I do this?</p>

答:
Give the div "runat="server" and an id and you can reference it in your code behind.

```<code><div runat="server" id="theDiv">
</code>```

In code behind:

```<code>{
    theDiv.Visible = false;
}
</code>```

In Designer.cs page:

```<code> protected global::System.Web.UI.HtmlControls.HtmlGenericControl theDiv;
</code>```

Title: How to hide a div from code (c#)

Body:
Give the div "runat="server" and an id and you can reference it in your code behind.

<div runat="server" id="theDiv">

In code behind:

{
    theDiv.Visible = false;
}

In Designer.cs page:

 protected global::System.Web.UI.HtmlControls.HtmlGenericControl theDiv;


问:
Does Static Methods give bad results if two threads having own objects accessing same?
Does Static non synchronized Methods give bad results if two threads accessing same?

```<code>public class MySubjectUtils {
   public static MyResponseClass createMyResponseClass(MyParameter record) {
   if (record == null) {
     return null;
   }
   MyResponseClass mRes = new MyResponseClass()
   mRes.setName(record.getName());
   mRes.setAddress(record.getAddress());
   return mRes;
}
</code>```

If two or more threads trying to access MySubjectUtils.createMyResponseClass(record); Will both gives results of their own or will they mix it up?

答: It will not have any performance issues, and since the method is not accessing some shared resources, the threads will get their own unique result.</p>

Body:
Does Static non synchronized Methods give bad results if two threads accessing same?

public class MySubjectUtils {
   public static MyResponseClass createMyResponseClass(MyParameter record) {
   if (record == null) {
     return null;
   }
   MyResponseClass mRes = new MyResponseClass()
   mRes.setName(record.getName());
   mRes.setAddress(record.getAddress());
   return mRes;
}

If two or more threads trying to access MySubjectUtils.createMyResponseClass(record); Will both gives results of their own or will they mix it up?


问:
Restart consumption from last checkpoint in EventHostProcessor
Given an implementation of the EventHostProcessor, how can I force replay of events from the last checkpoint within the same processor?

To be clear, assume my partition is 100 deep and I have consumed 10 messages. When I invoke this replay method, I would then want onEvent to return the first message from my previously consumed 10.

In C# this seems possible through the use of the Stopwatch but I do not see the Java equivalent.

答:
The simple way is that using Java StopWatch class of Apache Commons Lang library and following the C# code in the tutorial Receive events from Azure Event Hubs using the .NET Framework to write the same feature code in Java with azure-event-hubs-java library (on GitHub here, maven dependency for EventProcessorHost here).

Hope it helps.


问:
Not able to understand FAKE Code : - FAKE F#MAKE
I have a  sample script , and I am not able to understand a piece of code from that file , here is the code:

```<code>Target "Package1" (fun _ ->
  NuGet (fun p ->
    { p with
      OutputPath = DeployDir
      ReleaseNotes = ReleaseNote
      WorkingDir = BuildDir
      Publish = false
      Version = PackageVersion
      Files = [
        (@"*.dll", Some "lib", None)
        (@"*.pdb", Some "lib",  None)
      ]
    })
    "src/Client/Project.Client.nuspec"
)
</code>```

and this target's order is last . So what is the purpose of using this target. and what is last line doing src/Project.Client/Project.Client.nuspec .If anyone can explain this in details , that would be really helpful.

答:
If you look at the documentation for NuGetHelper the signature for NuGet function is setParams:(NuGetParams -> NuGetParams) -> nuspecOrProjectFile:string -> unit.

This means that the function takes a setParams function that creates a new set of NuGetParams from the default set of NuGetParams. And a path where to write the resulting nuspecfile.

In your example the setParams function is defined as (my comments):

```<code>fun p ->
    { p with                      // p is the default NuGetParams
      OutputPath = DeployDir      // set OutputPath from FAKE properties
      ReleaseNotes = ReleaseNote  // Set ReleaseNotes to ReleaseNote (from FAKE)
      WorkingDir = BuildDir       // Set WorkingDir from FAKE properties
      Publish = false             // Do not publish to NuGet.org
      Version = PackageVersion    // Set Version number
      Files = [                   // Put these files from WorkingDir into the package
        (@"*.dll", Some "lib", None)
        (@"*.pdb", Some "lib",  None)
      ]
    })
</code>```

The reason that Target "Package1" is the last target is to ensure that all values for the setParams value are valid.

Body:
I have a  sample script , and I am not able to understand a piece of code from that file , here is the code:

Target "Package1" (fun _ ->
  NuGet (fun p ->
    { p with
      OutputPath = DeployDir
      ReleaseNotes = ReleaseNote
      WorkingDir = BuildDir
      Publish = false
      Version = PackageVersion
      Files = [
        (@"*.dll", Some "lib", None)
        (@"*.pdb", Some "lib",  None)
      ]
    })
    "src/Client/Project.Client.nuspec"
)

and this target's order is last . So what is the purpose of using this target. and what is last line doing src/Project.Client/Project.Client.nuspec .If anyone can explain this in details , that would be really helpful.

Body:
If you look at the documentation for NuGetHelper the signature for NuGet function is setParams:(NuGetParams -> NuGetParams) -> nuspecOrProjectFile:string -> unit.

This means that the function takes a setParams function that creates a new set of NuGetParams from the default set of NuGetParams. And a path where to write the resulting nuspecfile.

In your example the setParams function is defined as (my comments):

fun p ->
    { p with                      // p is the default NuGetParams
      OutputPath = DeployDir      // set OutputPath from FAKE properties
      ReleaseNotes = ReleaseNote  // Set ReleaseNotes to ReleaseNote (from FAKE)
      WorkingDir = BuildDir       // Set WorkingDir from FAKE properties
      Publish = false             // Do not publish to NuGet.org
      Version = PackageVersion    // Set Version number
      Files = [                   // Put these files from WorkingDir into the package
        (@"*.dll", Some "lib", None)
        (@"*.pdb", Some "lib",  None)
      ]
    })

The reason that Target "Package1" is the last target is to ensure that all values for the setParams value are valid.