问:
Yahoo Finance API finally dead? Using ichart GET call?
It looks like the party is over with regard to historical data from the Yahoo Finance API. I've followed previous answers and nothing is working. The previous code was of the format:

```<code>http://ichart.yahoo.com/table.csv?s=AAPL
</code>```

and even https.

```<code>https://ichart.yahoo.com/table.csv?s=AAPL
</code>```

None of these resolve in browser or can be requested. For historical data is there any API in existence for Yahoo Finance? It's possible to get current data points with the following calls:

```<code>http://finance.yahoo.com/d/quotes.csv?s=AAPL&f=e
</code>```

However no history. Any suggestions or functioning work around?

答:
Try the spreadsheets here:
Bulk Yahoo historical stock quote downloader
Historical stock prices from Yahoo

Yahoo finance now uses a cookie-crumb pair. The VBA in the spreadsheets

gets the cookie-crumb pair from Yahoo for a junk call

uses the cookie-crumb pair to download historical data

uses the cookie-crumb pair to download historical data.

The first spreadsheet lets you download bulk data. The second spreadsheet contains a wrapper function that converts old Yahoo Finance API calls to a format that still works

The VBA is more involved (not a clean API call anymore), and Yahoo may shut off this route without notice. But, for now, you can still get historical data.

Body:
It looks like the party is over with regard to historical data from the Yahoo Finance API. I've followed previous answers and nothing is working. The previous code was of the format:

http://ichart.yahoo.com/table.csv?s=AAPL

and even https.

https://ichart.yahoo.com/table.csv?s=AAPL

None of these resolve in browser or can be requested. For historical data is there any API in existence for Yahoo Finance? It's possible to get current data points with the following calls:

http://finance.yahoo.com/d/quotes.csv?s=AAPL&f=e

However no history. Any suggestions or functioning work around?


来源: stackexchange

问:
Merge: when not matched by source - update rows
I'm trying to figure out the merge function where I have to update rows that  exist in target table but those rows doesn't match with rows in source table.

Those that didn't match in source table I would like to update in line where it say's WHEN NOT MATCHED BY SOURCE with something like
Update PEOPLE set UPD = null,target.CHANGE  = CURRENT_TIMESTAMP where target.ID = source.ID and target.UPD is not null and target.CHANGE is null

This is what at the moment MERGE looks like, I think I need some output that will give me ID's that didn't match so I can update them but not sure how.

For example this are the rows in PEOPLE:

ID is not unique it is ID of a group

ID,NAME,SURNAME,UPD,CHECKED

4345,JOHN,DOE,1 - this one doesn't exist(his ID doesn't exist) in
  '#PEOPLE because it is insert from an earlier merge from an earlier #PEOPLE that now has changed

879,MARY,HON,1 - this one exist in #PEOPLE

9875,CHRISTIAN,TROY,1 - this one doesn't match the row's but his ID exist
  in PEOPLE and #PEOPLE

So from this list I want that JOHN DOE stay's as it is because his ID doesn't exit in #PEOPLE and CHRISTIAN TROY gets update where UPD will be NULL and CHANGE = CURRENT_TIMESTAMP but only if the UPD is not null and CHANGE is null because his ID exist in PEOPLE and #PEOPLE but entire row doesn't match.

```<code>MERGE INTO PEOPLE WITH (HOLDLOCK) AS target
USING #PEOPLE AS source

 on isnull(target.ID,'') = isnull(source.ID,'')
 and isnull(target.NAME,'') = isnull(source.NAME,'')
 and isnull(target.SURNAME,'') = isnull(source.SURNAME,'')

WHEN MATCHED THEN
    UPDATE SET target.UPD = 1
WHEN NOT MATCHED BY TARGET THEN
    INSERT (ID,NAME,SURNAME,UPD)
    VALUES (source.ID ,source.NAME ,source.SURNAME,1)

WHEN NOT MATCHED BY SOURCE and target.UPD is not null and target.CHANGE is null THEN
  update set UPD = NULL,target.CHANGE  = CURRENT_TIMESTAMP
</code>```

Any ideas?

答:
It was a bit hard to read all of this but as much as I can see you don't have any FK in your table and that is why you have to make update after merge.

You could use OUTPUT but maybe the easiest way would be to make updates like this. if matched UPD=2 and if it is and insert UPD = 3.. So now you have on UPD = 1 those that are not matched so you see what are ID's in #People and you update them:

```<code>MERGE INTO PEOPLE WITH (HOLDLOCK) AS target
USING #PEOPLE AS source

 on isnull(target.ID,'') = isnull(source.ID,'')
 and isnull(target.NAME,'') = isnull(source.NAME,'')
 and isnull(target.SURNAME,'') = isnull(source.SURNAME,'')

WHEN MATCHED THEN
    UPDATE SET target.UPD = 2
WHEN NOT MATCHED BY TARGET THEN
    INSERT (ID,NAME,SURNAME,UPD)
    VALUES (source.ID ,source.NAME ,source.SURNAME,3)

;

UPDATE PEOPLE set UPD = null,CHANGE = CURRENT_TIMESTAMP where UPD = 1 and CHANGE is null and ID in (Select distinct ID from #PEOPLE);
UPDATE PEOPLE set UPD = 1 where (UPD =2 or UPD=3) and MB in (Select distinct MB from #PEOPLE);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to figure out the merge function where I have to update rows that  exist in target table but those rows doesn't match with rows in source table.

Those that didn't match in source table I would like to update in line where it say's WHEN NOT MATCHED BY SOURCE with something like
Update PEOPLE set UPD = null,target.CHANGE  = CURRENT_TIMESTAMP where target.ID = source.ID and target.UPD is not null and target.CHANGE is null

This is what at the moment MERGE looks like, I think I need some output that will give me ID's that didn't match so I can update them but not sure how.

For example this are the rows in PEOPLE:

ID is not unique it is ID of a group

ID,NAME,SURNAME,UPD,CHECKED

4345,JOHN,DOE,1 - this one doesn't exist(his ID doesn't exist) in
  '#PEOPLE because it is insert from an earlier merge from an earlier #PEOPLE that now has changed

879,MARY,HON,1 - this one exist in #PEOPLE

9875,CHRISTIAN,TROY,1 - this one doesn't match the row's but his ID exist
  in PEOPLE and #PEOPLE

So from this list I want that JOHN DOE stay's as it is because his ID doesn't exit in #PEOPLE and CHRISTIAN TROY gets update where UPD will be NULL and CHANGE = CURRENT_TIMESTAMP but only if the UPD is not null and CHANGE is null because his ID exist in PEOPLE and #PEOPLE but entire row doesn't match.

MERGE INTO PEOPLE WITH (HOLDLOCK) AS target
USING #PEOPLE AS source

 on isnull(target.ID,'') = isnull(source.ID,'')
 and isnull(target.NAME,'') = isnull(source.NAME,'')
 and isnull(target.SURNAME,'') = isnull(source.SURNAME,'')

WHEN MATCHED THEN
    UPDATE SET target.UPD = 1
WHEN NOT MATCHED BY TARGET THEN
    INSERT (ID,NAME,SURNAME,UPD)
    VALUES (source.ID ,source.NAME ,source.SURNAME,1)

WHEN NOT MATCHED BY SOURCE and target.UPD is not null and target.CHANGE is null THEN
  update set UPD = NULL,target.CHANGE  = CURRENT_TIMESTAMP

Any ideas?

Body:
It was a bit hard to read all of this but as much as I can see you don't have any FK in your table and that is why you have to make update after merge.

You could use OUTPUT but maybe the easiest way would be to make updates like this. if matched UPD=2 and if it is and insert UPD = 3.. So now you have on UPD = 1 those that are not matched so you see what are ID's in #People and you update them:

MERGE INTO PEOPLE WITH (HOLDLOCK) AS target
USING #PEOPLE AS source

 on isnull(target.ID,'') = isnull(source.ID,'')
 and isnull(target.NAME,'') = isnull(source.NAME,'')
 and isnull(target.SURNAME,'') = isnull(source.SURNAME,'')

WHEN MATCHED THEN
    UPDATE SET target.UPD = 2
WHEN NOT MATCHED BY TARGET THEN
    INSERT (ID,NAME,SURNAME,UPD)
    VALUES (source.ID ,source.NAME ,source.SURNAME,3)

;

UPDATE PEOPLE set UPD = null,CHANGE = CURRENT_TIMESTAMP where UPD = 1 and CHANGE is null and ID in (Select distinct ID from #PEOPLE);
UPDATE PEOPLE set UPD = 1 where (UPD =2 or UPD=3) and MB in (Select distinct MB from #PEOPLE);


问:
Problems while trying to remove a set of tuples from a list?
Just a quick question guys, I have a long list of tuples like this:

```<code>a_lis = [('[', '1O--'), ("'", '1B--'),('hi', 'SDFD29384'), ('there','2398SDFDSF'),("'", '1B--'), (']', '1C--')]
</code>```

How can I remove all this tuples (*): ('[', '1O--'), ("'", '1B--'),("'", '1B--'), (']', '1C--') from a_lis?

I tried to:

```<code>flat_list = filter(flat_list, lambda x: x[0] == '[' && x[1] == "'")
</code>```

However, I got a non iterable error, which is a better way of removing such tuples (*) from my list, in order to get?:

```<code>a_lis = [('hi', 'SDFD29384'), ('there','2398SDFDSF')]
</code>```

答:
That's because the order of arguments you have give to filter is incorrect.

Just use

```<code>flat_list = filter(lambda x: x[0] != '[' and x[0] != "'", a_lis)
</code>```

Note: Looking at your data, a better way looks like this:

```<code>flat_list = filter(lambda x: '--' not in x[1], a_lis)
</code>```

Edit: As mentioned in the comment below, the above code makes flat_list a generator. To get concrete lists, just use list comprehensions:

```<code>def should_remove(s):
    return '[' in s or ']' in s or "'" in s

flat_list = [x in a_lis if not should_remove(x[1])]
</code>```

OR

```<code>flat_list = [x in a_lis if '--' not in x[1]]
</code>```

Body:
Just a quick question guys, I have a long list of tuples like this:

a_lis = [('[', '1O--'), ("'", '1B--'),('hi', 'SDFD29384'), ('there','2398SDFDSF'),("'", '1B--'), (']', '1C--')]

How can I remove all this tuples (*): ('[', '1O--'), ("'", '1B--'),("'", '1B--'), (']', '1C--') from a_lis?

I tried to:

flat_list = filter(flat_list, lambda x: x[0] == '[' && x[1] == "'")

However, I got a non iterable error, which is a better way of removing such tuples (*) from my list, in order to get?:

a_lis = [('hi', 'SDFD29384'), ('there','2398SDFDSF')]

Body:
That's because the order of arguments you have give to filter is incorrect.

Just use

flat_list = filter(lambda x: x[0] != '[' and x[0] != "'", a_lis)

Note: Looking at your data, a better way looks like this:

flat_list = filter(lambda x: '--' not in x[1], a_lis)

Edit: As mentioned in the comment below, the above code makes flat_list a generator. To get concrete lists, just use list comprehensions:

def should_remove(s):
    return '[' in s or ']' in s or "'" in s

flat_list = [x in a_lis if not should_remove(x[1])]

OR

flat_list = [x in a_lis if '--' not in x[1]]


问:
Using UITableViewController logics in UITableViewDataSource class
I'm doing a refactor because my UITableViewController is bloating very badly. The first thing I'm trying to do is refactoring the data source out of the table view controller like this:

```<code>// In my UITableViewController
let ds = MyDataSource()

func viewDidLoad() {
  tableView.dataSource = ds
}
</code>```

In my data source class, I want to use some logic that I feel should belong in the table view controller.

```<code>class MyDataSource: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    // I want to use the variable showMore here
    return showMore ? 2 : 1
  }

  // More data source doe
}
</code>```

The variable showMore is a boolean variable defined in my table view controller and is updated by a button in the footer view of a section.

Question is then, if showMore belongs in the table view controller, how can I access it from my data source class? If it doesn't belong in the
table view controller, where does it belong and why?

Thanks!

答:
First thought that comes to mind - and I'm just typing, not writing in Xcode...

```<code>// footerButtonTap
if let ds = tableView.dataSource as? MyDataSource {
    ds.showMore = !ds.showMore
    tableView.reloadData()
}
</code>```

Or something along those lines might fit your needs.

Body:
I'm doing a refactor because my UITableViewController is bloating very badly. The first thing I'm trying to do is refactoring the data source out of the table view controller like this:

// In my UITableViewController
let ds = MyDataSource()

func viewDidLoad() {
  tableView.dataSource = ds
}

In my data source class, I want to use some logic that I feel should belong in the table view controller.

class MyDataSource: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    // I want to use the variable showMore here
    return showMore ? 2 : 1
  }

  // More data source doe
}

The variable showMore is a boolean variable defined in my table view controller and is updated by a button in the footer view of a section.

Question is then, if showMore belongs in the table view controller, how can I access it from my data source class? If it doesn't belong in the
table view controller, where does it belong and why?

Thanks!

Body:
First thought that comes to mind - and I'm just typing, not writing in Xcode...

// footerButtonTap
if let ds = tableView.dataSource as? MyDataSource {
    ds.showMore = !ds.showMore
    tableView.reloadData()
}

Or something along those lines might fit your needs.


问:
Controlling shader framerate
I've got a project that I'm writing a frag shader for and I want to be able to control the framerate. I'm kind of having trouble getting info on this - almost everything I've found on it is about optimizing framerate for 60-90fps, but what I need is actually to drop it to about 20fps.</p>

答:
Doing anything with framerate is a bad design. What you should do is to change your update loop. Imagine it this way:

Your shader can render in 1000FPS, but you actually need 20FPS. If you will render static image, you wont notice if it is 20 or 1000FPS. However, if you need some sort of movement, you will notice. So, instead of updating shader variable (responsible for the movement) every frame, update it in only every n-th frame and it should give you the desired effect,

See something about game loops, eg: https://gamedev.stackexchange.com/questions/25767/is-it-safe-to-set-fps-rate-to-a-constant

Title: Controlling shader framerate


问:
Finding just one or more comma in a string with ColdFusion
How can I detect if a string value only consists of one or more commas and nothing else. The correct value should be something like: ABC,BVC,BNM but sometimes I get value like: , or ,,, or ,, and this is not allowed. How can I detect that a string only have one or more commas and then I can create a warning to the user and stop the process.

Thank you

答:
You can use listToArray() and arrayToList() to remove the empty items from the list and can then compare the sanitized version with the original like this:

```<code><cfset originalInput = trim( ",,," )>
<cfset sanitizedInput = arrayToList( listToArray( originalInput, ",", false ), "," )>

<!--- Compare both --->
<cfif originalInput NEQ sanitizedInput>

  <!--- Throw error --->

</cfif>
</code>```

Body:
You can use listToArray() and arrayToList() to remove the empty items from the list and can then compare the sanitized version with the original like this:

<cfset originalInput = trim( ",,," )>
<cfset sanitizedInput = arrayToList( listToArray( originalInput, ",", false ), "," )>

<!--- Compare both --->
<cfif originalInput NEQ sanitizedInput>

  <!--- Throw error --->

</cfif>


问:
Java scsi access
I'd like to port a Linux C program to Java. This program controls a camera which is connected to the PC with a USB cable. The C code uses Linux SCSI Generic (sg).

Sample code from the C program:

```<code>#include <linux/../scsi/sg.h>

...

static int scsi_write(int sg_fd, uint8_t *cmd, uint32_t cmdLen,
               uint8_t *buf, uint32_t bufLen) {

    sg_io_hdr_t io;
    int r;

    memset(&io, 0, sizeof(io));

    io.interface_id = 'S';
    io.cmd_len = cmdLen;

    ...
    r = ioctl(sg_fd, SG_IO, &io);
    ...
}
</code>```

Is there a way to port this program to Java? I was searching for a cross-platform SCSI library written for Java, but found none. I was also searching for a JNI over SCSI/sg, also no luck.

答: While Java supports a lot of the POSIX API, the ioctl system call is not part of what it does. What you'll need to do is to use JNI to allow Java to call a function such as the scsi_write you wrote in the question. The extra cost of using more shims is minimal given that you're talking about interfacing to external hardware anyway. The cmd and buf arguments map naturally to Java byte arrays (and since Java's arrays know their length, you won't model the cmdLen and bufLen arguments at the Java level at all).

ContentLicense: CC BY-SA 2.5

Title: Java scsi access

Body:
I'd like to port a Linux C program to Java. This program controls a camera which is connected to the PC with a USB cable. The C code uses Linux SCSI Generic (sg).

Sample code from the C program:

#include <linux/../scsi/sg.h>

...

static int scsi_write(int sg_fd, uint8_t *cmd, uint32_t cmdLen,
               uint8_t *buf, uint32_t bufLen) {

    sg_io_hdr_t io;
    int r;

    memset(&io, 0, sizeof(io));

    io.interface_id = 'S';
    io.cmd_len = cmdLen;

    ...
    r = ioctl(sg_fd, SG_IO, &io);
    ...
}

Is there a way to port this program to Java? I was searching for a cross-platform SCSI library written for Java, but found none. I was also searching for a JNI over SCSI/sg, also no luck.


问:
Fetch child entities when finding by a normal field in Spring Data JPA
I am using Spring Data JpaRepository to find List of entities matching a particular field. Consider the following code snippet:

Entity:

```<code>@Entity
@Table(name = "master")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Master implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id", nullable = false)
    private Long Id;

@NotNull
    @Column(name = "user_id", nullable = false)
    private String userId;

@OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="id", referencedColumnName="id", insertable=false, updatable=false)
    private Details Details;
</code>```

Spring Data Custom JpaRepository:

```<code>public interface MasterRepository extends JpaRepository<Master,Long> {

    List<Master> findMasterByUserId(String userId);

}
</code>```

When i am using findBookingMasterByUserId repository method to find all records with specific user id, I am getting the List of Master entity but I am not getting the Details entity that has id as foreign key in it.

However, I get all the dependent entities when I use out of the box findAll method of JpaRepository but with custom findMasterByUserId repository method, child entities are not being fetched eagerly.

Any type of help would be highly appreciated. Thanks!

答:
Your entity name is "Master" not "booking_master".

Change your method to:

```<code>List<Master> findByUserId(String userId);
</code>```

Refer to below spring docs for more information on query creation mechanism for JPA.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

Alternatively,

```<code>@Query("SELECT m FROM Master m WHERE m.userId = :userId")
List<Master> findByUserId(@Param("userId") String userId);
</code>```

The query generation from the method name is a query generation strategy where the invoked query is derived from the name of the query method.

We can create query methods that use this strategy by following these rules:

The name of our query method must start with one of the following
prefixes: find…By, read…By, query…By, count…By, and get…By.

If we want to limit the number of returned query results, we can add
the First or the Top keyword before the first By word. If we want to
get more than one result, we have to append the optional numeric
value to the First and the Top keywords. For example, findTopBy,
findTop1By, findFirstBy, and findFirst1By all return the first entity
that matches with the specified search criteria.

If we want to select unique results, we have to add the Distinct
keyword before the first By word. For example, findTitleDistinctBy or
findDistinctTitleBy means that we want to select all unique titles
that are found from the database.

We must add the search criteria of our query method after the first
By word. We can specify the search criteria by combining property
expressions with the supported keywords.

If our query method specifies x search conditions, we must add x
method parameters to it. In other words, the number of method
parameters must be equal than the number of search conditions. Also,
the method parameters must be given in the same order than the search
conditions.

Body:
I am using Spring Data JpaRepository to find List of entities matching a particular field. Consider the following code snippet:

Entity:

@Entity
@Table(name = "master")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Master implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id", nullable = false)
    private Long Id;

@NotNull
    @Column(name = "user_id", nullable = false)
    private String userId;

@OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="id", referencedColumnName="id", insertable=false, updatable=false)
    private Details Details;

Spring Data Custom JpaRepository:

public interface MasterRepository extends JpaRepository<Master,Long> {

    List<Master> findMasterByUserId(String userId);

}

When i am using findBookingMasterByUserId repository method to find all records with specific user id, I am getting the List of Master entity but I am not getting the Details entity that has id as foreign key in it.

However, I get all the dependent entities when I use out of the box findAll method of JpaRepository but with custom findMasterByUserId repository method, child entities are not being fetched eagerly.

Any type of help would be highly appreciated. Thanks!

Body:
Your entity name is "Master" not "booking_master".

Change your method to:

List<Master> findByUserId(String userId);

Refer to below spring docs for more information on query creation mechanism for JPA.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

Alternatively,

@Query("SELECT m FROM Master m WHERE m.userId = :userId")
List<Master> findByUserId(@Param("userId") String userId);

The query generation from the method name is a query generation strategy where the invoked query is derived from the name of the query method.

We can create query methods that use this strategy by following these rules:

The name of our query method must start with one of the following
prefixes: find…By, read…By, query…By, count…By, and get…By.

If we want to limit the number of returned query results, we can add
the First or the Top keyword before the first By word. If we want to
get more than one result, we have to append the optional numeric
value to the First and the Top keywords. For example, findTopBy,
findTop1By, findFirstBy, and findFirst1By all return the first entity
that matches with the specified search criteria.

If we want to select unique results, we have to add the Distinct
keyword before the first By word. For example, findTitleDistinctBy or
findDistinctTitleBy means that we want to select all unique titles
that are found from the database.

We must add the search criteria of our query method after the first
By word. We can specify the search criteria by combining property
expressions with the supported keywords.

If our query method specifies x search conditions, we must add x
method parameters to it. In other words, the number of method
parameters must be equal than the number of search conditions. Also,
the method parameters must be given in the same order than the search
conditions.


问:
spring-data: Not an managed type: class java.lang.Object
I started using spring-data project yesterday and was trying to add a test to repository I have created.

The project structure looks like

```<code>persistence/pom.xml
           src/main/java/
                        ApplicationConfig
                        BaseRepository
                        Network
           src/main/test/BaseRepositoryTest
</code>```

The ApplicationConfig looks like

```<code>@Configuration
@ComponentScan
@EnableJpaRepositories
public class ApplicationConfig {
    @Bean
    public DataSource dataSource() {
        final EmbeddedDatabaseBuilder embeddedDatabaseBuilder = new EmbeddedDatabaseBuilder();
        embeddedDatabaseBuilder.setType(EmbeddedDatabaseType.H2);
        return embeddedDatabaseBuilder.build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setDatabase(Database.H2);
        jpaVendorAdapter.setGenerateDdl(true);

        final LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        localContainerEntityManagerFactoryBean.setPackagesToScan(getClass().getPackage().getName());
        localContainerEntityManagerFactoryBean.setDataSource(dataSource());

        return localContainerEntityManagerFactoryBean;
    }
}
</code>```

The BaseRepository looks like

```<code>import org.springframework.data.repository.Repository;

public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
    List<T> findAll();
}
</code>```

The Network is an Entity class looks like

```<code>@Entity
public class Network extends com.org.comma.persistence.Entity {
    private final long networkId;

    private final String name;

    private final boolean active;

    private final DateTime createdAt;

    private String createdBy;

    private DateTime updatedAt;

    private String updatedBy;
...
}
</code>```

and BaseRepositoryTest looks like

```<code>import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationConfig.class, BaseRepository.class})
public class BaseRepositoryTest {

    @Autowired
    BaseRepository<Network, Long> baseRepository;

    @Test
    public void testAllNetworks() {
        final List<Network> networks = baseRepository.findAll();
        assertTrue(networks.isEmpty());
    }
}
</code>```

My pom.xml looks like

```<code><dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.6.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
    </dependency>
    <dependency>
        <groupId>com.google.code.findbugs</groupId>
        <artifactId>jsr305</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
</dependencies>
</code>```

When I run mvn clean install, I see error as

```<code>java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:319)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class java.lang.Object
</code>```

Please help me identify what am I doing wrong here, I am new to this project

答: This also happens if you have one repository interface that extends another and you forgot the @NoRepositoryBean on the super-interface.</p>

Body:
I started using spring-data project yesterday and was trying to add a test to repository I have created.

The project structure looks like

persistence/pom.xml
           src/main/java/
                        ApplicationConfig
                        BaseRepository
                        Network
           src/main/test/BaseRepositoryTest

The ApplicationConfig looks like

@Configuration
@ComponentScan
@EnableJpaRepositories
public class ApplicationConfig {
    @Bean
    public DataSource dataSource() {
        final EmbeddedDatabaseBuilder embeddedDatabaseBuilder = new EmbeddedDatabaseBuilder();
        embeddedDatabaseBuilder.setType(EmbeddedDatabaseType.H2);
        return embeddedDatabaseBuilder.build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setDatabase(Database.H2);
        jpaVendorAdapter.setGenerateDdl(true);

        final LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        localContainerEntityManagerFactoryBean.setPackagesToScan(getClass().getPackage().getName());
        localContainerEntityManagerFactoryBean.setDataSource(dataSource());

        return localContainerEntityManagerFactoryBean;
    }
}

The BaseRepository looks like

import org.springframework.data.repository.Repository;

public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
    List<T> findAll();
}

The Network is an Entity class looks like

@Entity
public class Network extends com.org.comma.persistence.Entity {
    private final long networkId;

    private final String name;

    private final boolean active;

    private final DateTime createdAt;

    private String createdBy;

    private DateTime updatedAt;

    private String updatedBy;
...
}

and BaseRepositoryTest looks like

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationConfig.class, BaseRepository.class})
public class BaseRepositoryTest {

    @Autowired
    BaseRepository<Network, Long> baseRepository;

    @Test
    public void testAllNetworks() {
        final List<Network> networks = baseRepository.findAll();
        assertTrue(networks.isEmpty());
    }
}

My pom.xml looks like

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.6.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
    </dependency>
    <dependency>
        <groupId>com.google.code.findbugs</groupId>
        <artifactId>jsr305</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
</dependencies>

When I run mvn clean install, I see error as

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:319)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class java.lang.Object

Please help me identify what am I doing wrong here, I am new to this project


问:
connect points during multiple Matlab plot calls
I would like to connect two or multiple data points during multiple Matlab plot calls. Below is some dummy code that shows what I am trying to accomplish,

```<code>function main()
close all

t = 0;

while t<10
    x = rand(1,1);
    y = rand(1,1);
    t = t+1;
    calculateErrorAndPlot(1,x,y,t)
end
return

function calculateErrorAndPlot(figureNumber,x,y,time)

    figure(figureNumber);
    if ~ishold
        hold on
    end

    error = x-y;
    plot(time,error,'.b');
return
</code>```

Right now, I have to use '.b' to at least see the data points being plotted. Note that plot is being called with scalars.

答:
I would rewrite this, and remove the function:</p>

```<code>time = [1:10];

for ii = 1:length(time)
    x = rand(1,1);
    y = rand(1,1);
    error(ii) = x-y;
 end
 plot(time,error,'.-b')
</code>```

Body:
I would like to connect two or multiple data points during multiple Matlab plot calls. Below is some dummy code that shows what I am trying to accomplish,

function main()
close all

t = 0;

while t<10
    x = rand(1,1);
    y = rand(1,1);
    t = t+1;
    calculateErrorAndPlot(1,x,y,t)
end
return

function calculateErrorAndPlot(figureNumber,x,y,time)

    figure(figureNumber);
    if ~ishold
        hold on
    end

    error = x-y;
    plot(time,error,'.b');
return

Right now, I have to use '.b' to at least see the data points being plotted. Note that plot is being called with scalars.

Body:
I would rewrite this, and remove the function:

time = [1:10];

for ii = 1:length(time)
    x = rand(1,1);
    y = rand(1,1);
    error(ii) = x-y;
 end
 plot(time,error,'.-b')


问:
Using string variables within a command in VBA
I was trying to get a string to work with a code where I automate multiple tabs to be filtered by the same criteria, for a sheet that gets the subtotal out of other sheets.

So, I did some If and Elses to check for some criteria and try to make the filtering after this analysis, instead of having to do multiple AutoFilters withing multiple Ifs.

So, the part bellow works just fine, it is making the string (subStr) accordingly

```<code>If subBacia = "TODOS" Then
    subStr = """<>"""
Else
    subStr = """=" & subBacia & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
End If
</code>```

But this part, that I am avoiding to do multiple ifs for, is not working:

```<code>ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr
</code>```

My idea was that it would end up as the construction bellow, for example, with multiple criteria:

```<code>ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:="=AN6b" _
    , Operator:=xlOr, Criteria2:="=TOTAIS"`
</code>```

So, what am I doing wrong, or what should I do that I am not aware of?
Edit: Here goes the full code

```<code>Sub Filter()
    Dim subBacia, encarregado As String
    Dim bm As String
    Dim subStr, encStr, bmStr As String

    'Application.Calculation = xlCalculationManual
    'Application.ScreenUpdating = False

    Sheets("Resumo").Select
    encarregado = Range("T3")
    subBacia = Range("T5")
    bm = Range("T4")
    Const QUOTE = """"
    On Error Resume Next

    If encarregado = "TODOS" And bm = "TODOS" And subBacia = "TODOS" Then
        Sheets("Dem. Rede").Select
        ActiveSheet.ShowAllData
        Sheets("Dem. Interceptor").Select
        ActiveSheet.ShowAllData
        Sheets("Dem.Ramal").Select
        ActiveSheet.ShowAllData
    Else
        If encarregado = "TODOS" Then
            encStr = """<>"""
        Else
            encStr = """=" & encarregado & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        If bm = "TODOS" Then
            bmStr = """<>"""
        Else
            bmStr = """=" & bm & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        If subBacia = "TODOS" Then
            subStr = """<>"""
        Else
            subStr = """=" & subBacia & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        Debug.Print encStr
        Debug.Print bmStr
        Debug.Print subStr
        Sheets("Dem. Rede").Select
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=2, Criteria1:=bmStr
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=3, Criteria1:=encStr
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr
        Sheets("Dem. Interceptor").Select
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=2, Criteria1:=bmStr
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=4, Criteria1:=encStr
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=3, Criteria1:=subStr
        Sheets("Dem.Ramal").Select
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=3, Criteria1:=bmStr
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=2, Criteria1:=encStr
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=1, Criteria1:=subStr
        Sheets("Cadastro Ramal").Select
            ActiveSheet.Range("$A$9:$K$841").AutoFilter Field:=2, Criteria1:=bmStr
    End If

    'Application.Calculation = xlCalculationAutomatic
    'Application.ScreenUpdating = True

End Sub
</code>```

Edit: BTW the Debug.Print is returning for example: "=9" , Operator:=xlOr, Criteria2:="=TOTAIS"

or simply "<>"

And it is exactly the way it should, but, it seems I can't concatenate the string in the code the way I hoped for.

答:
You cannot construct pieces of VBA code on the fly and use them to complement incomplete statements you have hardcoded. I don't think that ever worked anywhere. You can dynamically create a complete sub and execute it though, but I do not recommend that.

However you don't need dynamic code generation in your case anyway. You want to predetermine values for the parameters, so do that explicitly. The trick is that you will need to use the Missing special value explicitly to pass to parameters you don't want:

```<code>Private Type CriteriaTuple
  Criteria1 As Variant
  Operator As Variant
  Criteria2 As Variant
End Type

Private Function MissingValue(Optional ByVal DoNotPassAnything As Variant) As Variant
  If Not IsMissing(DoNotPassAnything) Then Err.Raise 5, , "I said do not pass anything"
  MissingValue = DoNotPassAnything
End Function

Sub Filter()
  ....

  dim subStr as CriteriaTuple

  if ... then
    subStr.Criteria1 = """<>"""
    subStr.Operator = MissingValue
    subStr.Criteria2 = MissingValue
  else
    subStr.Criteria1 = """<>"""
    subStr.Operator = xlOr
    subStr.Criteria2 = """=TOTAIS"""
  end if

  ...

  ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr.Criteria1, Operator:=subStr.Operator, Criteria2:=subStr.Criteria2
End Sub
</code>```

Body:
I was trying to get a string to work with a code where I automate multiple tabs to be filtered by the same criteria, for a sheet that gets the subtotal out of other sheets.

So, I did some If and Elses to check for some criteria and try to make the filtering after this analysis, instead of having to do multiple AutoFilters withing multiple Ifs.

So, the part bellow works just fine, it is making the string (subStr) accordingly

If subBacia = "TODOS" Then
    subStr = """<>"""
Else
    subStr = """=" & subBacia & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
End If

But this part, that I am avoiding to do multiple ifs for, is not working:

ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr

My idea was that it would end up as the construction bellow, for example, with multiple criteria:

ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:="=AN6b" _
    , Operator:=xlOr, Criteria2:="=TOTAIS"`

So, what am I doing wrong, or what should I do that I am not aware of?
Edit: Here goes the full code

Sub Filter()
    Dim subBacia, encarregado As String
    Dim bm As String
    Dim subStr, encStr, bmStr As String

    'Application.Calculation = xlCalculationManual
    'Application.ScreenUpdating = False

    Sheets("Resumo").Select
    encarregado = Range("T3")
    subBacia = Range("T5")
    bm = Range("T4")
    Const QUOTE = """"
    On Error Resume Next

    If encarregado = "TODOS" And bm = "TODOS" And subBacia = "TODOS" Then
        Sheets("Dem. Rede").Select
        ActiveSheet.ShowAllData
        Sheets("Dem. Interceptor").Select
        ActiveSheet.ShowAllData
        Sheets("Dem.Ramal").Select
        ActiveSheet.ShowAllData
    Else
        If encarregado = "TODOS" Then
            encStr = """<>"""
        Else
            encStr = """=" & encarregado & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        If bm = "TODOS" Then
            bmStr = """<>"""
        Else
            bmStr = """=" & bm & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        If subBacia = "TODOS" Then
            subStr = """<>"""
        Else
            subStr = """=" & subBacia & QUOTE & " , Operator:=xlOr, Criteria2:=" & QUOTE & "=TOTAIS" & QUOTE & ""
        End If
        Debug.Print encStr
        Debug.Print bmStr
        Debug.Print subStr
        Sheets("Dem. Rede").Select
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=2, Criteria1:=bmStr
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=3, Criteria1:=encStr
            ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr
        Sheets("Dem. Interceptor").Select
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=2, Criteria1:=bmStr
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=4, Criteria1:=encStr
            ActiveSheet.Range("$A$12:$EM$137").AutoFilter Field:=3, Criteria1:=subStr
        Sheets("Dem.Ramal").Select
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=3, Criteria1:=bmStr
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=2, Criteria1:=encStr
            ActiveSheet.Range("$B$11:$Z$1214").AutoFilter Field:=1, Criteria1:=subStr
        Sheets("Cadastro Ramal").Select
            ActiveSheet.Range("$A$9:$K$841").AutoFilter Field:=2, Criteria1:=bmStr
    End If

    'Application.Calculation = xlCalculationAutomatic
    'Application.ScreenUpdating = True

End Sub

Edit: BTW the Debug.Print is returning for example: "=9" , Operator:=xlOr, Criteria2:="=TOTAIS"

or simply "<>"

And it is exactly the way it should, but, it seems I can't concatenate the string in the code the way I hoped for.

Body:
You cannot construct pieces of VBA code on the fly and use them to complement incomplete statements you have hardcoded. I don't think that ever worked anywhere. You can dynamically create a complete sub and execute it though, but I do not recommend that.

However you don't need dynamic code generation in your case anyway. You want to predetermine values for the parameters, so do that explicitly. The trick is that you will need to use the Missing special value explicitly to pass to parameters you don't want:

Private Type CriteriaTuple
  Criteria1 As Variant
  Operator As Variant
  Criteria2 As Variant
End Type

Private Function MissingValue(Optional ByVal DoNotPassAnything As Variant) As Variant
  If Not IsMissing(DoNotPassAnything) Then Err.Raise 5, , "I said do not pass anything"
  MissingValue = DoNotPassAnything
End Function

Sub Filter()
  ....

  dim subStr as CriteriaTuple

  if ... then
    subStr.Criteria1 = """<>"""
    subStr.Operator = MissingValue
    subStr.Criteria2 = MissingValue
  else
    subStr.Criteria1 = """<>"""
    subStr.Operator = xlOr
    subStr.Criteria2 = """=TOTAIS"""
  end if

  ...

  ActiveSheet.Range("$A$12:$EX$2025").AutoFilter Field:=4, Criteria1:=subStr.Criteria1, Operator:=subStr.Operator, Criteria2:=subStr.Criteria2
End Sub


问:
Can not curl docker swarm from remote host
I'm trying to test how to interact with docker swarm using docker API. I have an ec2 instance in AWS running docker. I need to connect to it from my local machine using curl then initialize the swarm and get the join tokens after to use it to connect 2 other ec2 instances to the swarm. I need to do all of that using curl only.

I created the swarm manually by ssh'ing to the instance and running:

```<code>docker swarm init --advertise-addr 10.0.0.2
</code>```

and then I tried running this curl command:

```<code>curl 10.0.0.2:2377/swarm
curl 10.0.0.2:2377/info
</code>```

and I get an empty line. If I try changing the port to 2376 I get connection refused error.

What am I missing?

running netstat -tuplen, found the following result:

答: To pull the answer out of the comments: By default accessing the remote API has to be done with https authentication. You can turn that off but this isn't recommended for production apps. There may be a way to write an authorization plugin that will allow other forms of authentication access.</p>

Body:
I'm trying to test how to interact with docker swarm using docker API. I have an ec2 instance in AWS running docker. I need to connect to it from my local machine using curl then initialize the swarm and get the join tokens after to use it to connect 2 other ec2 instances to the swarm. I need to do all of that using curl only.

I created the swarm manually by ssh'ing to the instance and running:

docker swarm init --advertise-addr 10.0.0.2

and then I tried running this curl command:

curl 10.0.0.2:2377/swarm
curl 10.0.0.2:2377/info

and I get an empty line. If I try changing the port to 2376 I get connection refused error.

What am I missing?

running netstat -tuplen, found the following result:


问:
LED matrix (HUB-75 type)
I'm trying to make the 64x64 LED matrix work without libraries. Started driving it with STM32F103C8T6 chip figured out the problem and tried ATmega328 instead, but nothing changed.

The problem is when I'm trying to lit a LED on specified address it actually lights up with almost 0 brightness, but the LED directly under it (on the next address) lights up with full brightness.

I cut the code to a minimum.

#define CLK 0
#define LAT 1
#define R1 2

uint16_t data [64][4];

void shiftOutLed (void);

int main () {
 data [0][0] = 0x0001;
 data [0][2] = 0x1800;
 DDRC |= 0x0F; //pin 0 - A, pin 1 - B, pin 2 - C, pin3 - D
 DDRB |= 0x03; // pin 0 - CLK, pin 1 - LAT
 DDRD |= 0x04; // pin 2 - R1

 while (1){
  shiftOutLed ();
 }
}

 void shiftOutLed (void){
  for (uint8_t _addr = 0; _addr < 16; _addr++){
   PORTC &= 0xF0;
   PORTC |= _addr;
   for (uint8_t _byte = 0; _byte < 4; _byte++){
    for (uint8_t _bit = 0; _bit < 16; _bit++){
     if (data[_addr][_byte] & (1 << _bit)) PORTD |= (1 << R1);
     else PORTD &= ~(1 << R1);
     PORTB |= (1 << CLK);
     PORTB &= ~(1 << CLK);
    }
   }
   PORTB |= (1 << LAT);
   PORTB &= ~(1 << LAT);
   PORTD &= ~(1 << R1);
  }
}
```

When I modify the code introducing delays while clocking and latching every bit LEDs light up in right row.

答:
Seems like the matrix needs the address set after clocking the entire row

```<code>#define CLK 0
#define LAT 1
#define R1 2

uint16_t data [64][4];

void shiftOutLed (void);

int main () {
 data [0][0] = 0x0001;
 data [0][2] = 0x1800;
 DDRC |= 0x0F; //pin 0 - A, pin 1 - B, pin 2 - C, pin3 - D
 DDRB |= 0x03; // pin 0 - CLK, pin 1 - LAT
 DDRD |= 0x04; // pin 2 - R1

 while (1){
  shiftOutLed ();
 }
}

 void shiftOutLed (void){
  for (uint8_t _addr = 0; _addr < 16; _addr++){
   PORTC &= 0xF0;
   for (uint8_t _byte = 0; _byte < 4; _byte++){
    for (uint8_t _bit = 0; _bit < 16; _bit++){
     if (data[_addr][_byte] & (1 << _bit)) PORTD |= (1 << R1);
     else PORTD &= ~(1 << R1);
     PORTB |= (1 << CLK);
     PORTB &= ~(1 << CLK);
    }
   }
   PORTC |= _addr;
   PORTB |= (1 << LAT);
   PORTB &= ~(1 << LAT);
   PORTD &= ~(1 << R1);
  }
}
</code>```

Now it works

Title: LED matrix (HUB-75 type)

Body:
I'm trying to make the 64x64 LED matrix work without libraries. Started driving it with STM32F103C8T6 chip figured out the problem and tried ATmega328 instead, but nothing changed.

The problem is when I'm trying to lit a LED on specified address it actually lights up with almost 0 brightness, but the LED directly under it (on the next address) lights up with full brightness.

I cut the code to a minimum.

#define CLK 0
#define LAT 1
#define R1 2

uint16_t data [64][4];

void shiftOutLed (void);

int main () {
 data [0][0] = 0x0001;
 data [0][2] = 0x1800;
 DDRC |= 0x0F; //pin 0 - A, pin 1 - B, pin 2 - C, pin3 - D
 DDRB |= 0x03; // pin 0 - CLK, pin 1 - LAT
 DDRD |= 0x04; // pin 2 - R1

 while (1){
  shiftOutLed ();
 }
}

 void shiftOutLed (void){
  for (uint8_t _addr = 0; _addr < 16; _addr++){
   PORTC &= 0xF0;
   PORTC |= _addr;
   for (uint8_t _byte = 0; _byte < 4; _byte++){
    for (uint8_t _bit = 0; _bit < 16; _bit++){
     if (data[_addr][_byte] & (1 << _bit)) PORTD |= (1 << R1);
     else PORTD &= ~(1 << R1);
     PORTB |= (1 << CLK);
     PORTB &= ~(1 << CLK);
    }
   }
   PORTB |= (1 << LAT);
   PORTB &= ~(1 << LAT);
   PORTD &= ~(1 << R1);
  }
}

When I modify the code introducing delays while clocking and latching every bit LEDs light up in right row.

Body:
Seems like the matrix needs the address set after clocking the entire row

#define CLK 0
#define LAT 1
#define R1 2

uint16_t data [64][4];

void shiftOutLed (void);

int main () {
 data [0][0] = 0x0001;
 data [0][2] = 0x1800;
 DDRC |= 0x0F; //pin 0 - A, pin 1 - B, pin 2 - C, pin3 - D
 DDRB |= 0x03; // pin 0 - CLK, pin 1 - LAT
 DDRD |= 0x04; // pin 2 - R1

 while (1){
  shiftOutLed ();
 }
}

 void shiftOutLed (void){
  for (uint8_t _addr = 0; _addr < 16; _addr++){
   PORTC &= 0xF0;
   for (uint8_t _byte = 0; _byte < 4; _byte++){
    for (uint8_t _bit = 0; _bit < 16; _bit++){
     if (data[_addr][_byte] & (1 << _bit)) PORTD |= (1 << R1);
     else PORTD &= ~(1 << R1);
     PORTB |= (1 << CLK);
     PORTB &= ~(1 << CLK);
    }
   }
   PORTC |= _addr;
   PORTB |= (1 << LAT);
   PORTB &= ~(1 << LAT);
   PORTD &= ~(1 << R1);
  }
}

Now it works


问:
Myth of Soma MMO game Bot - Memory Address for Items on floor contains garbage and constantly changing info
I've been coding a bot for a relatively small MMO, mainly as a hobby to challenge my own skills and learn something new.

I've overcome many challenges and have successfully built a bot which hunts monsters in the game and manages itself. However i've been unable to find the memory addresses for items on the floor. Using cheat engine, I find that the name of the item is stored more than 15 times around pockets of memory, when I pickup the item and place another down, some of these addresses will change to the new item's name, but the others will all change to garbage information which includes other text on the screen too such as whats going on in the chat.

Sometimes these pockets of memory addresses seem to actually change to the values of the item, then they quickly change again to garbage.

Is this some sort of scrambling anti-cheat? I can't imagine so since it is a very old and small game. It is called myth of soma.

I once found an address whcih always showed the first item on the floor, but I couldn't find any others and since then i've never found this address again.

This is an isometric game where each item on the floor is assigned coords. Would anyone have some advice for me in this area? I'd like to be able to reverse engineer the memory addresses for these items.

答: For future reference for anybody. I finally solved this problem by creating a second cache array. By copying the data from the first into the second, if it exists but then also adding a cache timer to each row. If the data disappears from the main array, the timer cache timer will keep the data alive until it runs out. </p>


问:
How can i check my android device support wifi direct?
I am working with android wifi direct demo application. After installation in my device I noticed that it is not working as expected.

I am confused, does my device support wifi direct or special hardware feature required for wifi direct? My device is local walton brand and API level 16. After reading android documentation i know that Wi-Fi Direct added in API level 14 doesn't need a wireless access point.

My other question is if in a place where no wifi zone is created using wifi direct two or more device  communicate with each other. in summing my problem, i need to know if my device not support wifi direct what i do to run wifi demo. Thanks in advance.

答:
In addition to StoneLam's answer, which is probably the most robust, a quicker-and-dirtier method would be to go ahead and call WifiP2pManager.discoverPeers() as you would if WiFi Direct were supported. The latter takes an ActionListener with an onFailure() callback. The failure reason passed to onFailure(int reason) can be P2P_UNSUPPORTED, which would answer your question: the device doesn't support WiFi Direct.

A call to onSuccess() would mean the device does support WiFi Direct. A call to onFailure() with other failure reasons would probably be inconclusive as to the device's capabilities.


问:
how to migrate from ionic3 to ionic2 and also from ionic2 back to ionic3
I want to know how to exchange between ionic 3 and 2 or 2 to 3 with keep same project

im use WINDOWS. in the  first time, I install

```<code>npm install -g ionic Cordova
</code>```

and for starting a new project i insert like following docs in ionicframework.com :

```<code>ionic start [myproject] blank
</code>```

and

```<code> cd [myproject]
 ionic serve
</code>```

i don't know what the version ionic was installed? is the latest version by default or what?
because of this article here :
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/

tell should install v2 in the first time and then we want to move to 3 !!

and I want to know how can moving between the version 2>>3 or 3>>2 without any crash.
and I'm afraid if I'm using v3 by default and give something wrong while coding

plizzz someone explain carefully my issue

答:
You can type in your console 'ionic info' and then you will see all info from your project.
Sample output, from my environment:

```<code>global packages:

    @ionic/cli-utils : 1.4.0
    Cordova CLI      : 6.3.1
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.7
    @ionic/cli-plugin-cordova       : 1.4.0
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Cordova Platforms               : android 6.1.2 browser 4.1.0
    Ionic Framework                 : ionic-angular 3.5.0

System:

    Node       : v7.4.0
    OS         : Linux 4.4
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed
    npm        : 5.0.3
</code>```

You have to pay attention that there are differences between what is installed globally and what is local.
Globally you should have ionic-cli, which is the command line tool used to manage Ionics' project (either 1, 2, or 3).

The version of the framework you are using is the Ionic Framework, installed locally, and managed by npm (via package.json, the package is called 'ionic-framework').
So, do change dependencies, you should only change the package.json from your project.
You must pay attention, too, that each ionic-framework version has its own dependencies versions, specially from @angular (example: ionic-framework v2 uses angular2, ionic-framework v3 uses angular4).

Body:
I want to know how to exchange between ionic 3 and 2 or 2 to 3 with keep same project

im use WINDOWS. in the  first time, I install

npm install -g ionic Cordova

and for starting a new project i insert like following docs in ionicframework.com :

ionic start [myproject] blank

and

 cd [myproject]
 ionic serve

i don't know what the version ionic was installed? is the latest version by default or what?
because of this article here :
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/

tell should install v2 in the first time and then we want to move to 3 !!

and I want to know how can moving between the version 2>>3 or 3>>2 without any crash.
and I'm afraid if I'm using v3 by default and give something wrong while coding

plizzz someone explain carefully my issue

Body:
You can type in your console 'ionic info' and then you will see all info from your project.
Sample output, from my environment:

global packages:

    @ionic/cli-utils : 1.4.0
    Cordova CLI      : 6.3.1
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.7
    @ionic/cli-plugin-cordova       : 1.4.0
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Cordova Platforms               : android 6.1.2 browser 4.1.0
    Ionic Framework                 : ionic-angular 3.5.0

System:

    Node       : v7.4.0
    OS         : Linux 4.4
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed
    npm        : 5.0.3

You have to pay attention that there are differences between what is installed globally and what is local.
Globally you should have ionic-cli, which is the command line tool used to manage Ionics' project (either 1, 2, or 3).

The version of the framework you are using is the Ionic Framework, installed locally, and managed by npm (via package.json, the package is called 'ionic-framework').
So, do change dependencies, you should only change the package.json from your project.
You must pay attention, too, that each ionic-framework version has its own dependencies versions, specially from @angular (example: ionic-framework v2 uses angular2, ionic-framework v3 uses angular4).


问:
Delete the manually created iOS Development certificate and generate from Xcode
Can we delete the existing manually generated iOS development Certificate and re-generate using the XCode? If then, can you please share me the steps need to be taken for that? So, it does not conflict when using same mailid to generate iOS dev cert and provisioning profile from XCode.</p>

答:
Deleting existing certificate

Open Keychain Access

On the left side from Keychains select login and from Category select My Certificate

Look for your development certificates.

Right click on it and delete it.

Create development certificates from Xcode.

Go to Xcode preferences.

Go to Accounts tab and select the apple id.

Click Manage certificates

And create new certificates.


问:
Where can I find Android source code online?
Where can I browse the source code for any Android Open Source Project (AOSP) application (for example the Contacts application)? Is the only way to clone the entire source repository for all of AOSP?</p>

答:
gitweb will allow you to browse through the code (and changes) via a browser.

http://git.or.cz/gitwiki/Gitweb

(Don't know if someone has already setup a public gitweb for Android, but it's probably not too hard.)

OwnerDisplayName: J. Pablo Fernández

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: Peter Boughton


问:
SQL custom unit conversion
I am looking for a solution for a custom unit conversion in SQL, the database my company used is Microsoft SQL server, I need to write a SQL to return a conversion factor based on a "unit conversion table"

say:

```<code>Item: chicken wings (itemid 1001)
vendor: food wholesale ltd (vendorid 5000)
unitid: gram (id=10)
unitid: kilogram (id=500)
unitid: boxes (id=305)
Quantity: 1000 grams = 1kgs = 5 boxs
</code>```

Unit conversion table:

```<code>itemid | vendorid | unit1id | unit2id | quantity1 | quantity2

1001 5000 10 500 1000 1

1001 5000 500 305 1 5
</code>```

Question:
What is the closing stock for chicken wings in gram if I have 10 boxes

How to write this sql to return the "conversion factor"?

Thanks in advance

答:
I would use a conversion table and put in all combinations. So even if 5000g ->5kg -> 1 box, I would put gram -> box conversions as well. Something like this:

```<code>create table unit_unit_conv(
   from_unit varchar(10)   not null
  ,to_unit   varchar(10)   not null
  ,rate      decimal(10,6) not null
  ,primary key(from_unit, to_unit)
);

insert into unit_unit_conv values('kilogram', 'kilogram',   1);
insert into unit_unit_conv values('kilogram', 'gram',       1000);
insert into unit_unit_conv values('kilogram', 'box',        0.2);
insert into unit_unit_conv values('gram',     'gram',       1);
insert into unit_unit_conv values('gram',     'kilogram',   0.001);
insert into unit_unit_conv values('gram',     'box',        0.0002);
insert into unit_unit_conv values('box',      'box',        1);
insert into unit_unit_conv values('box',      'kilogram',   5);
insert into unit_unit_conv values('box',      'gram',       5000);
</code>```

So whatever unit of measure you have, you can convert it into any unit by multiplying the quantity you have with the rate column in this table. So if you have a table of items like this:

```<code>create table items(
   item_id        varchar(10) not null
  ,item_qty       int not null
  ,item_qty_unit  varchar(10)
);

insert into items values('chicken', 5,    'kilogram');
insert into items values('babies',  5000, 'gram');
insert into items values('beef',    1,    'box');
</code>```

...and you want to convert everything to boxes, you would query the data like this:

```<code>select i.item_id
      ,i.item_qty    as qty_original
      ,item_qty_unit as qty_unit_original
      ,i.item_qty * c.rate as box_qty
  from items          i
  join unit_unit_conv c on(i.item_qty_unit = c.from_unit)
 where c.to_unit = 'box';

+---------+--------------+-------------------+----------+
| item_id | qty_original | qty_unit_original | box_qty  |
+---------+--------------+-------------------+----------+
| chicken |            5 | kilogram          | 1.000000 |
| babies  |         5000 | gram              | 1.000000 |
| beef    |            1 | box               | 1.000000 |
+---------+--------------+-------------------+----------+
</code>```

Title: SQL custom unit conversion

Body:
I am looking for a solution for a custom unit conversion in SQL, the database my company used is Microsoft SQL server, I need to write a SQL to return a conversion factor based on a "unit conversion table"

say:

Item: chicken wings (itemid 1001)
vendor: food wholesale ltd (vendorid 5000)
unitid: gram (id=10)
unitid: kilogram (id=500)
unitid: boxes (id=305)
Quantity: 1000 grams = 1kgs = 5 boxs

Unit conversion table:

itemid | vendorid | unit1id | unit2id | quantity1 | quantity2

1001 5000 10 500 1000 1

1001 5000 500 305 1 5

Question:
What is the closing stock for chicken wings in gram if I have 10 boxes

How to write this sql to return the "conversion factor"?

Thanks in advance

Body:
I would use a conversion table and put in all combinations. So even if 5000g ->5kg -> 1 box, I would put gram -> box conversions as well. Something like this:

create table unit_unit_conv(
   from_unit varchar(10)   not null
  ,to_unit   varchar(10)   not null
  ,rate      decimal(10,6) not null
  ,primary key(from_unit, to_unit)
);

insert into unit_unit_conv values('kilogram', 'kilogram',   1);
insert into unit_unit_conv values('kilogram', 'gram',       1000);
insert into unit_unit_conv values('kilogram', 'box',        0.2);
insert into unit_unit_conv values('gram',     'gram',       1);
insert into unit_unit_conv values('gram',     'kilogram',   0.001);
insert into unit_unit_conv values('gram',     'box',        0.0002);
insert into unit_unit_conv values('box',      'box',        1);
insert into unit_unit_conv values('box',      'kilogram',   5);
insert into unit_unit_conv values('box',      'gram',       5000);

So whatever unit of measure you have, you can convert it into any unit by multiplying the quantity you have with the rate column in this table. So if you have a table of items like this:

create table items(
   item_id        varchar(10) not null
  ,item_qty       int not null
  ,item_qty_unit  varchar(10)
);

insert into items values('chicken', 5,    'kilogram');
insert into items values('babies',  5000, 'gram');
insert into items values('beef',    1,    'box');

...and you want to convert everything to boxes, you would query the data like this:

select i.item_id
      ,i.item_qty    as qty_original
      ,item_qty_unit as qty_unit_original
      ,i.item_qty * c.rate as box_qty
  from items          i
  join unit_unit_conv c on(i.item_qty_unit = c.from_unit)
 where c.to_unit = 'box';

+---------+--------------+-------------------+----------+
| item_id | qty_original | qty_unit_original | box_qty  |
+---------+--------------+-------------------+----------+
| chicken |            5 | kilogram          | 1.000000 |
| babies  |         5000 | gram              | 1.000000 |
| beef    |            1 | box               | 1.000000 |
+---------+--------------+-------------------+----------+


问:
Postfix and prefix increment that causes an error
Why does that code does not compile due to an error:

```<code>#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << ++(i++) << " " << i << endl;
    return 0;
}
</code>```

While that code does compile:

```<code>#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << (++i)++ << " " << i << endl;
    return 0;
}
</code>```

I do not understand that. From my point of view it would be pretty reasonable for the first chunk to compile. The expression ++(i++) would just mean take i, increment it and output, then increment it again.

I am not asking about an undefined behavior in int overflow. I do not know about r and l value at all at the time of writing the question and I do not care why is ++i considered an l-value, but i++ is not.

答:
Shortly speaking the difference is that in C++ you may use any even number of pluses (restricted only by the compiler limits) for the prefix increment operator like this

```<code>++++++++++++++++i;
</code>```

and only two pluses for the post increment operator

```<code>i++;
</code>```

The postfix increment operator returns a value (The C++ Standard, 5.2.6 Increment and decrement)

1 The value of a postfix ++ expression is the value of its
  operand. [ Note: the value obtained is a copy of the original value
  —end note ]

While the prefix increment operator returns its operand after increment (The C++ Standard ,5.3.2 Increment and decrement)

1  ...The result is the updated operand; it is an lvalue...

Opposite to C++ in C you also can apply only two pluses to an object using the prefix increment operator.:) Thus the C compiler will issue an error for such an expression like this

```<code>++++++++++++++++i;
</code>```

Body:
Why does that code does not compile due to an error:

#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << ++(i++) << " " << i << endl;
    return 0;
}

While that code does compile:

#include <iostream>

using namespace std;

int main()
{
    int i = 0;
    cout << (++i)++ << " " << i << endl;
    return 0;
}

I do not understand that. From my point of view it would be pretty reasonable for the first chunk to compile. The expression ++(i++) would just mean take i, increment it and output, then increment it again.

I am not asking about an undefined behavior in int overflow. I do not know about r and l value at all at the time of writing the question and I do not care why is ++i considered an l-value, but i++ is not.

Body:
Shortly speaking the difference is that in C++ you may use any even number of pluses (restricted only by the compiler limits) for the prefix increment operator like this

++++++++++++++++i;

and only two pluses for the post increment operator

i++;

The postfix increment operator returns a value (The C++ Standard, 5.2.6 Increment and decrement)

1 The value of a postfix ++ expression is the value of its
  operand. [ Note: the value obtained is a copy of the original value
  —end note ]

While the prefix increment operator returns its operand after increment (The C++ Standard ,5.3.2 Increment and decrement)

1  ...The result is the updated operand; it is an lvalue...

Opposite to C++ in C you also can apply only two pluses to an object using the prefix increment operator.:) Thus the C compiler will issue an error for such an expression like this

++++++++++++++++i;


问:
Correction script Bash
I'm trying in vain to solve my problem with this script.

```<code>#!/bin/bash
for a in `wget -O - "https://pastebin.com/raw/7BFC94Ty"`; do echo "local-zone: \""$a" redirect\"""local-data: \""$a" A 0.0.0.0\"" >> adstest.conf; done
</code>```

Here is the result

```<code>local-zone: "101com.com
 redirect"local-data: "101com.com
 A 0.0.0.0"
</code>```

But this is not the right formatting, this is the expected result:

```<code>local-zone: "101com.com" redirect
local-data: "101com.com A 0.0.0.0"
</code>```

But I can not find this damn solution. I'm also looking for a solution to be able to use a local file rather than a url because I have a file of 40 000 lines and I would like to do without a web host for that.

Thank you for your help !

答:
To address @chepner's concerns, we can use sed to process the stream:

```<code>wget -O - "https://pastebin.com/raw/7BFC94Ty" | dos2unix | sed 's/\(.*\)/local-zone: "\1" redirect\nlocal-data: "\1 A 0.0.0.0"/' > adstest.conf
</code>```

It just takes the whole pattern space of the line, saved with \(.*\), and replaces it with the text we want, putting the pattern space back in with \1 where we need it, and using \n to put in the line break.

Title: Correction script Bash

Body:
I'm trying in vain to solve my problem with this script.

#!/bin/bash
for a in `wget -O - "https://pastebin.com/raw/7BFC94Ty"`; do echo "local-zone: \""$a" redirect\"""local-data: \""$a" A 0.0.0.0\"" >> adstest.conf; done

Here is the result

local-zone: "101com.com
 redirect"local-data: "101com.com
 A 0.0.0.0"

But this is not the right formatting, this is the expected result:

local-zone: "101com.com" redirect
local-data: "101com.com A 0.0.0.0"

But I can not find this damn solution. I'm also looking for a solution to be able to use a local file rather than a url because I have a file of 40 000 lines and I would like to do without a web host for that.

Thank you for your help !

Body:
To address @chepner's concerns, we can use sed to process the stream:

wget -O - "https://pastebin.com/raw/7BFC94Ty" | dos2unix | sed 's/\(.*\)/local-zone: "\1" redirect\nlocal-data: "\1 A 0.0.0.0"/' > adstest.conf

It just takes the whole pattern space of the line, saved with \(.*\), and replaces it with the text we want, putting the pattern space back in with \1 where we need it, and using \n to put in the line break.


问:
How to copy the sheet name to a column on the same sheet?
I am using this code:

```<code>Function wrksht() as Variant
wrksht = Application.Caller.Parent.Name
End function
</code>```

I am continuously being thrown

run time error '424' object not found

I have a workbook with several sheets, each having a date on it.

I want to populate the first column on every sheet with its sheet name.

答:
The above will work, but I have an easier solution:

```<code>=MID(CELL("filename",A1),FIND("]",CELL("filename",A1))+1,255)
</code>```

Paste this value (it is a formula, not VBA code) into the cell you wish to populate with the sheet name, and it will magically appear.

Body:
I am using this code:

Function wrksht() as Variant
wrksht = Application.Caller.Parent.Name
End function

I am continuously being thrown

run time error '424' object not found

I have a workbook with several sheets, each having a date on it.

I want to populate the first column on every sheet with its sheet name.

Body:
The above will work, but I have an easier solution:

=MID(CELL("filename",A1),FIND("]",CELL("filename",A1))+1,255)

Paste this value (it is a formula, not VBA code) into the cell you wish to populate with the sheet name, and it will magically appear.


问:
how to get rid of \' from queried string which produced \' in string instead of '
I queried using Sequelize which produces result ONTARIO\'S INSTEAD OF ONTARIO'S. I want of inject it into a JSON String where I want it to be ONTARIO'S INSTEAD OF ONTARIO\'S. I used this is achieve the results.

```<code>var text = ("ONTARIO\'S").replace(/\'/g,"'");
</code>```

However this doesn't give me desired result. Can some body help me with this?

答:
There is a good probability that you are confusing the way the object notion prints when inspecting with the way it would appear if using the data within the object.

Have you tried using the JSON string data to print? They may not be visible when using them in your UI for example, but may be present when inspecting the JSON object. Try using the strings and see for example if using them in your UI, if the escaped single quotes will persist.

Body:
I queried using Sequelize which produces result ONTARIO\'S INSTEAD OF ONTARIO'S. I want of inject it into a JSON String where I want it to be ONTARIO'S INSTEAD OF ONTARIO\'S. I used this is achieve the results.

var text = ("ONTARIO\'S").replace(/\'/g,"'");

However this doesn't give me desired result. Can some body help me with this?


问:
C# code generator
Can someone recommend a simple c# code generator. I just looking something with methods like:

```<code>GenClass = CreateNewClass(AccessModifier,Name......)

GenClass.Add(new Method(AccessModifier,RetType,Name....){code=@"....."}

GenClass.Add(new Property(AccessModifier,Type, Name....)
</code>```

...........
etc

and after creating all classes\methods and other members we call Code Generation function(where we can specific some parametrs)

Is there such opensource code generator?

答: take a look at my open source generator http://code.google.com/p/magicapps/ </p>

Title: C# code generator

Body:
Can someone recommend a simple c# code generator. I just looking something with methods like:

GenClass = CreateNewClass(AccessModifier,Name......)

GenClass.Add(new Method(AccessModifier,RetType,Name....){code=@"....."}

GenClass.Add(new Property(AccessModifier,Type, Name....)

...........
etc

and after creating all classes\methods and other members we call Code Generation function(where we can specific some parametrs)

Is there such opensource code generator?


问:
Input value equal/match to a any value in declared array with strings
I have this JS code, I need to compare the input value with the array, if the input value match with some value in the array then show the related message, but I can't get the array values and compare them with my input value.</p>

```<code>var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

    if ($("input.reservationkey").val() === invalidkeyreservation) {
        BootstrapDialog.show(return $content;}

    } else{
        window.location.href = "/branches/Cancelaciones/Seleccion.html";
    }
</code>```

答:
You should be able to see if one of the elements in the array includes any of the string value, like so:

ES6

```<code>const invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if(invalidkeyreservation.some(key => key === $("input.reservationkey").val()) {
    BootstrapDialog.show(return $content);
} else{
    window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
</code>```

ES5

```<code>var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if(invalidkeyreservation.indexOf($("input.reservationkey").val()) > -1) {
    BootstrapDialog.show(return $content);
} else{
    window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
</code>```

Body:
I have this JS code, I need to compare the input value with the array, if the input value match with some value in the array then show the related message, but I can't get the array values and compare them with my input value.

var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

    if ($("input.reservationkey").val() === invalidkeyreservation) {
        BootstrapDialog.show(return $content;}

    } else{
        window.location.href = "/branches/Cancelaciones/Seleccion.html";
    }

Body:
You should be able to see if one of the elements in the array includes any of the string value, like so:

ES6

const invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if(invalidkeyreservation.some(key => key === $("input.reservationkey").val()) {
    BootstrapDialog.show(return $content);
} else{
    window.location.href = "/branches/Cancelaciones/Seleccion.html";
}

ES5

var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if(invalidkeyreservation.indexOf($("input.reservationkey").val()) > -1) {
    BootstrapDialog.show(return $content);
} else{
    window.location.href = "/branches/Cancelaciones/Seleccion.html";
}


问:
Keras: Feeding in part of previous layer to next layer, in CNN

I am trying to feed in the individual kernel outputs of the previous layer to a new conv filter, to get the next layer. To do that, I tried passing each of the kernel outputs through a Conv2D, by calling them by their index. The function I used is:

def modification(weights_path=None, classes=2):

    ###########
    ## Input ##
    ###########

    ### 224x224x3 sized RGB Input
    inputs = Input(shape=(224,224,3))

    #################################
    ## Conv2D Layer with 5 kernels ##
    #################################

    k = 5
    x = Conv2D(k, (3,3), data_format='channels_last', padding='same', name='block1_conv1')(inputs)
    y = np.empty(k, dtype=object)
    for i in range(0,k):
        y[i] = Conv2D(1, (3,3), data_format='channels_last', padding='same')(np.asarray([x[i]]))
    y = keras.layers.concatenate([y[i] for i in range (0,k)], axis=3, name='block1_conv1_loc')
    out = Activation('relu')(y)
    print ('Output shape is, ' +str(out.get_shape()))

    ### Maxpooling(2,2) with a stride of (2,2)
    out = MaxPooling2D((2,2), strides=(2,2), data_format='channels_last')(out)

    ############################################
    ## Top layer, with fully connected layers ##
    ############################################

    out = Flatten(name='flatten')(out)
    out = Dense(4096, activation='relu', name='fc1')(out)
    out = Dropout(0.5)(out)
    out = Dense(4096, activation='relu', name='fc2')(out)
    out = Dropout(0.5)(out)
    out = Dense(classes, activation='softmax', name='predictions')(out)

    if weights_path:
        model.load_weights(weights_path)

    model = Model(inputs, out, name='modification')

    return model
```

<p>But this is not working, and is throwing the following error:</p>

<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "sim-conn-edit.py", line 137, in <module>
    model = modification()
  File "sim-conn-edit.py", line 38, in modification
    y[i] = Conv2D(1, (3,3), data_format='channels_last', padding='same')(np.asarray([x[i]]))
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 511, in __call__
    self.assert_input_compatibility(inputs)
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 408, in assert_input_compatibil
ity
    if K.ndim(x) != spec.ndim:
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 437, in ndim
    dims = x.get_shape()._dims
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'
</code>```

I fed in layer x[i] as [ x[i] ] to meet the dimention requirements of a Conv2D layer. Any help with solving this problem will be deeply appreciated!

答:
Prabaha. I know you've solved your problem, but now I see your answer, you can do that without using the lambda layer too, just split the first Conv2D in many. One layer with k filters is equivalent to k layers with one filter:

```<code>for i in range(0,k):
    y[i] = Conv2D(1, (3,3), ... , name='block1_conv'+str(i))(inputs)
    y[i] = Conv2D(1,(3,3), ...)(y[i])
y = Concatenate()([y[i] for i in range (0,k)])
out = Activation('relu')(y)
</code>```

You can count the total parameters in your answer and in this answer to compare.

Body:
I am trying to feed in the individual kernel outputs of the previous layer to a new conv filter, to get the next layer. To do that, I tried passing each of the kernel outputs through a Conv2D, by calling them by their index. The function I used is:

def modification(weights_path=None, classes=2):

    ###########
    ## Input ##
    ###########

    ### 224x224x3 sized RGB Input
    inputs = Input(shape=(224,224,3))

    #################################
    ## Conv2D Layer with 5 kernels ##
    #################################

    k = 5
    x = Conv2D(k, (3,3), data_format='channels_last', padding='same', name='block1_conv1')(inputs)
    y = np.empty(k, dtype=object)
    for i in range(0,k):
        y[i] = Conv2D(1, (3,3), data_format='channels_last', padding='same')(np.asarray([x[i]]))
    y = keras.layers.concatenate([y[i] for i in range (0,k)], axis=3, name='block1_conv1_loc')
    out = Activation('relu')(y)
    print ('Output shape is, ' +str(out.get_shape()))

    ### Maxpooling(2,2) with a stride of (2,2)
    out = MaxPooling2D((2,2), strides=(2,2), data_format='channels_last')(out)

    ############################################
    ## Top layer, with fully connected layers ##
    ############################################

    out = Flatten(name='flatten')(out)
    out = Dense(4096, activation='relu', name='fc1')(out)
    out = Dropout(0.5)(out)
    out = Dense(4096, activation='relu', name='fc2')(out)
    out = Dropout(0.5)(out)
    out = Dense(classes, activation='softmax', name='predictions')(out)

    if weights_path:
        model.load_weights(weights_path)

    model = Model(inputs, out, name='modification')

    return model

But this is not working, and is throwing the following error:

Traceback (most recent call last):
  File "sim-conn-edit.py", line 137, in <module>
    model = modification()
  File "sim-conn-edit.py", line 38, in modification
    y[i] = Conv2D(1, (3,3), data_format='channels_last', padding='same')(np.asarray([x[i]]))
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 511, in __call__
    self.assert_input_compatibility(inputs)
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 408, in assert_input_compatibil
ity
    if K.ndim(x) != spec.ndim:
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 437, in ndim
    dims = x.get_shape()._dims
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'

I fed in layer x[i] as [ x[i] ] to meet the dimention requirements of a Conv2D layer. Any help with solving this problem will be deeply appreciated!

Body:
Prabaha. I know you've solved your problem, but now I see your answer, you can do that without using the lambda layer too, just split the first Conv2D in many. One layer with k filters is equivalent to k layers with one filter:

for i in range(0,k):
    y[i] = Conv2D(1, (3,3), ... , name='block1_conv'+str(i))(inputs)
    y[i] = Conv2D(1,(3,3), ...)(y[i])
y = Concatenate()([y[i] for i in range (0,k)])
out = Activation('relu')(y)

You can count the total parameters in your answer and in this answer to compare.


问:
Loop through entire file python
I've put together this piece of code:

```<code>flux =[31.,29,27.,25.]
F=[]
with open("results.rdx", "r") as file1:
for line in enumerate(file1):
    f_list = [float(i) for line in file1 for i in line.split(',') if
    i.strip()]
    F = f_list[7:11]
    with open("results.txt", "a+") as file2:
            file2.write(str(chisqfunc(flux,F)))
            file2.write("\n")
</code>```

And my input file looks like this:

```<code>5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650
5.0, 1000.0, 500000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
4.873E-09, 8.890E-09, 8.243E-10, 9.974E-12, 4.157, 3.704, 3.582, 3.649
5.0, 1000.0, 1000000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
8.883E-09, 1.705E-08, 1.668E-09, 2.039E-11, 4.212, 3.731, 3.577, 3.648
</code>```

Actually there are way more lines, but it's pointless to post it all. The function does some array multiplication etc. What I was hoping the code would do is: Read the first line, append the values of the columns 7-10 to the array F[], call chisqfunc and print its result into the file results.txt. Afterwards proceed to the second line, append the new values to F etc.
But all it does is start from line 2 and do the above described procedure for line 2 and only print the value for line 2.
I suspect the problem is in the way I declared for.
Any help is greatly appreciated.

答:
enumerate returns value pairs: a count, followed by the elements of the given iterable.  Your for statement ignores the lines of the file: line is merely a counter from 0 to the file length in lines.

Perhaps try ...

```<code>for line in file1:
</code>```

Also, if your input file has 3 lines rather than the 6 you show, please edit the posting appropriately.  Otherwise, your input line doesn't even have positions 7:11.

Title: Loop through entire file python

Body:
I've put together this piece of code:

flux =[31.,29,27.,25.]
F=[]
with open("results.rdx", "r") as file1:
for line in enumerate(file1):
    f_list = [float(i) for line in file1 for i in line.split(',') if
    i.strip()]
    F = f_list[7:11]
    with open("results.txt", "a+") as file2:
            file2.write(str(chisqfunc(flux,F)))
            file2.write("\n")

And my input file looks like this:

5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650
5.0, 1000.0, 500000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
4.873E-09, 8.890E-09, 8.243E-10, 9.974E-12, 4.157, 3.704, 3.582, 3.649
5.0, 1000.0, 1000000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
8.883E-09, 1.705E-08, 1.668E-09, 2.039E-11, 4.212, 3.731, 3.577, 3.648

Actually there are way more lines, but it's pointless to post it all. The function does some array multiplication etc. What I was hoping the code would do is: Read the first line, append the values of the columns 7-10 to the array F[], call chisqfunc and print its result into the file results.txt. Afterwards proceed to the second line, append the new values to F etc.
But all it does is start from line 2 and do the above described procedure for line 2 and only print the value for line 2.
I suspect the problem is in the way I declared for.
Any help is greatly appreciated.

Body:
enumerate returns value pairs: a count, followed by the elements of the given iterable.  Your for statement ignores the lines of the file: line is merely a counter from 0 to the file length in lines.

Perhaps try ...

for line in file1:

Also, if your input file has 3 lines rather than the 6 you show, please edit the posting appropriately.  Otherwise, your input line doesn't even have positions 7:11.


问:
Whats wrong with my python program

tip and tax calculator

```<code>bill = price + tax + tip

price = raw_input("What is the price of the meal")

tax = price * .06

tip = price * 0.20
</code>```

what is wrong with my code
I have tried everything
please answer and get back to me

答:
a few things.</p>

```<code>bill = price + tax + tip  #You can't add up these values BEFORE calculating them

price = raw_input("What is the price of the meal") #raw_input returns a string, not a float which you will need for processing

tax = price * .06 #So here you need to do float(price) * .06

tip = price * 0.20 #And float(price) here as well.

#Then your " bill = price + tax + tip " step goes here
</code>```

Title: Whats wrong with my python program

Body:
tip and tax calculator

bill = price + tax + tip

price = raw_input("What is the price of the meal")

tax = price * .06

tip = price * 0.20

what is wrong with my code
I have tried everything
please answer and get back to me

Body:
a few things.

bill = price + tax + tip  #You can't add up these values BEFORE calculating them

price = raw_input("What is the price of the meal") #raw_input returns a string, not a float which you will need for processing

tax = price * .06 #So here you need to do float(price) * .06

tip = price * 0.20 #And float(price) here as well.

#Then your " bill = price + tax + tip " step goes here


问:
ProgressDialog circle not showing in device
I have this ProgressDialog in my activity. I'm using a few devices to test but only in one the loading circle is not showing.
The device that it's not showing it's a Moto G4 Plus running android 7.0. Below there is a picture.

I also run the app in a Asus Zenfone 3 running also android 7.0. They both are running android 7.0 but only one don't show the circle.

Here is my code:

```<code>import android.app.ProgressDialog;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Carregando...");
   }

    private void myMethod(){
            progressDialog.show();
   }
</code>```

Did anyone had the same problem? Is there a way to solve it and still use the ProgressDialog?

答: Check whether your device is in Power Saving mode (some devices disable animation) or the animation is off in Developer Options.</p>

Body:
I have this ProgressDialog in my activity. I'm using a few devices to test but only in one the loading circle is not showing.
The device that it's not showing it's a Moto G4 Plus running android 7.0. Below there is a picture.

I also run the app in a Asus Zenfone 3 running also android 7.0. They both are running android 7.0 but only one don't show the circle.

Here is my code:

import android.app.ProgressDialog;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Carregando...");
   }

    private void myMethod(){
            progressDialog.show();
   }

Did anyone had the same problem? Is there a way to solve it and still use the ProgressDialog?