问:
Is it possible to use channels and buffers (java.nio) to read/write types of objects I created from/to a file?
I would like to know if it is possible to use channels and buffers (from java.nio) to read/write types of objects I created from/to a file ?

For example, here is a code sample (not using "finally" or even better try-with-ressources neither closing files because it's not part of a code, just an example to illustrate why I am asking this question).

```<code>import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;

public class Main {
public static void main(String[] args) {

FileInputStream fis;
BufferedInputStream bis;
FileChannel fc;

try {
  fis = new FileInputStream(new File("test.txt"));
  bis = new BufferedInputStream(fis);
  //initializing timer
  long time = System.currentTimeMillis();
  //reading
  while(bis.read() != -1);
  //execution time
  System.out.println("Execution time with a conventionnal buffer (BufferedInputStream) : " + (System.currentTimeMillis() - time));

  //again
  fis = new FileInputStream(new File("test.txt"));
  //but we catch the channel
  fc = fis.getChannel();
  //from that we deduce the size
  int size = (int)fc.size();
  //We create a buffer corresponding to the size of the file
  ByteBuffer bBuff = ByteBuffer.allocate(size);

  //initializing the timer
  time = System.currentTimeMillis();
  //starting reading
  fc.read(bBuff);
  //preparing reading calling flip
  bBuff.flip();
  //printing execution time
  System.out.println("Execution time with a new buffer (java.nio Buffer) : " + (System.currentTimeMillis() - time));

} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}
}
}
</code>```

When I execute this code (test.txt is a 4 Mo file), I can see that the execution time is about 10 times faster with the second method than with the first one.
In this exemple, it is done with a byte buffer, but you can do it with any kind of primitive types (IntBuffer, CharBuffer, ...);

Is it also possible to use this second method (using java.nio Buffer) with a type of Objects I created ? Or should I use the first method (using BufferedInoutStream) with it like :

```<code> ObjectInputStream ois = new ObjectInputStream(
                             new BufferedInputStream(
                                 new FileInputStream(
                                     new File("test.txt"))));
</code>```

答:
Your benchmark is invalid, as it only tests a primed cache in the second case. Try it with two different files, or in the other order. You won't get the same results.

In any case your tests are not even remotely comparable. What you should be timing in the first case is bis.read(byte[]) into the same size buffer as in the second case.

When you run valid tests, you will find there is little if any difference, and therefore no motivation for your question. Use a BufferedInputStream as per your first example.

Body:
I would like to know if it is possible to use channels and buffers (from java.nio) to read/write types of objects I created from/to a file ?

For example, here is a code sample (not using "finally" or even better try-with-ressources neither closing files because it's not part of a code, just an example to illustrate why I am asking this question).

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;

public class Main {
public static void main(String[] args) {

FileInputStream fis;
BufferedInputStream bis;
FileChannel fc;

try {
  fis = new FileInputStream(new File("test.txt"));
  bis = new BufferedInputStream(fis);
  //initializing timer
  long time = System.currentTimeMillis();
  //reading
  while(bis.read() != -1);
  //execution time
  System.out.println("Execution time with a conventionnal buffer (BufferedInputStream) : " + (System.currentTimeMillis() - time));

  //again
  fis = new FileInputStream(new File("test.txt"));
  //but we catch the channel
  fc = fis.getChannel();
  //from that we deduce the size
  int size = (int)fc.size();
  //We create a buffer corresponding to the size of the file
  ByteBuffer bBuff = ByteBuffer.allocate(size);

  //initializing the timer
  time = System.currentTimeMillis();
  //starting reading
  fc.read(bBuff);
  //preparing reading calling flip
  bBuff.flip();
  //printing execution time
  System.out.println("Execution time with a new buffer (java.nio Buffer) : " + (System.currentTimeMillis() - time));

} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}
}
}

When I execute this code (test.txt is a 4 Mo file), I can see that the execution time is about 10 times faster with the second method than with the first one.
In this exemple, it is done with a byte buffer, but you can do it with any kind of primitive types (IntBuffer, CharBuffer, ...);

Is it also possible to use this second method (using java.nio Buffer) with a type of Objects I created ? Or should I use the first method (using BufferedInoutStream) with it like :

 ObjectInputStream ois = new ObjectInputStream(
                             new BufferedInputStream(
                                 new FileInputStream(
                                     new File("test.txt"))));


来源: stackexchange

问:
Java JTextField as InputStream. 'ENTER' not functioning as enter
My program connects to UNIX/PUTTY in order to execute commands through a custom GUI. I have a JTextArea as my OutputStream and a JTextField as my InputStream.

The Output is functioning as expected, however Input stream is not. In order for the command to be executed within UNIX it requires the ENTER key to be pressed, however the enter key is not functioning as expected.

Here is my code:

```<code>public class JTextFieldInputStream extends InputStream {
byte[] contents;
int pointer = 0;
String toBytes = "";
public JTextFieldInputStream(final JTextField text) {

    text.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if(e.getKeyChar()=='\n'){
                toBytes = text.getText()+'\n';
                contents = toBytes.getBytes();
                pointer = 0;
                text.setText("");
                toBytes = "";
            }
            super.keyReleased(e);
        }
    });
}

@Override
public int read() throws IOException {
    if(pointer >= contents.length) return -1;
    return this.contents[pointer++];
}
</code>```

I am trying to pass the '\n' char as the ENTER, but doesn't seem to be working. It gets into the if statement fine and will reset the text field to "". But '\n' toBytes () doesn't seem to be interpreted by the input stream as an enter press.
Any help would be greatly appreciated. Thankyou :)

答: The problem is with JTextField as it is a Single lines only you need to use JTextArea in your case.</p>

ContentLicense: CC BY-SA 3.0

Body:
My program connects to UNIX/PUTTY in order to execute commands through a custom GUI. I have a JTextArea as my OutputStream and a JTextField as my InputStream.

The Output is functioning as expected, however Input stream is not. In order for the command to be executed within UNIX it requires the ENTER key to be pressed, however the enter key is not functioning as expected.

Here is my code:

public class JTextFieldInputStream extends InputStream {
byte[] contents;
int pointer = 0;
String toBytes = "";
public JTextFieldInputStream(final JTextField text) {

    text.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if(e.getKeyChar()=='\n'){
                toBytes = text.getText()+'\n';
                contents = toBytes.getBytes();
                pointer = 0;
                text.setText("");
                toBytes = "";
            }
            super.keyReleased(e);
        }
    });
}

@Override
public int read() throws IOException {
    if(pointer >= contents.length) return -1;
    return this.contents[pointer++];
}

I am trying to pass the '\n' char as the ENTER, but doesn't seem to be working. It gets into the if statement fine and will reset the text field to "". But '\n' toBytes () doesn't seem to be interpreted by the input stream as an enter press.
Any help would be greatly appreciated. Thankyou :)


问:
How to get the ip address of a particular adapter in windows xp through command
I have more than one adapter in my system and I want to know the IP of particular adapter. Is it possible through a command in Windows, in Linux it's easy? Or any other way?</p>

答: ipconfig /all should do the trick.</p>

Body: ipconfig /all should do the trick.

ContentLicense: CC BY-SA 2.5


问:
SQL Server query to return 1 row for todays date against multiple column counts
I'm trying to write an SQL Server query with 1 row as a date stamp for multiple counts of Region for the Customer.  It is returning a row for each case statement.

```<code>Customer    Region
1           A
2           A
3           B
4           B
5           B

SELECT
CONVERT(VARCHAR(10), GETDATE(), 111),
case when Region = 'A' then COUNT(Customer) end as 'Region A',
case when Region = 'B' then COUNT(Customer) end as 'Region B',
FROM tbl_Customers
</code>```

Results:

```<code>Date        Region A    Region B
2017/06/07  2           NULL
2017/06/07  NULL        3
</code>```

答:
You just need to add the CASE expression inside the aggregation function:

```<code>SELECT  CONVERT(VARCHAR(10), GETDATE(),111) [Date],
        COUNT(CASE WHEN Region = 'A' THEN Customer END) [Region A],
        COUNT(CASE WHEN Region = 'B' THEN Customer END) [Region B]
FROM tbl_Customers;
</code>```

Body:
I'm trying to write an SQL Server query with 1 row as a date stamp for multiple counts of Region for the Customer.  It is returning a row for each case statement.

Customer    Region
1           A
2           A
3           B
4           B
5           B

SELECT
CONVERT(VARCHAR(10), GETDATE(), 111),
case when Region = 'A' then COUNT(Customer) end as 'Region A',
case when Region = 'B' then COUNT(Customer) end as 'Region B',
FROM tbl_Customers

Results:

Date        Region A    Region B
2017/06/07  2           NULL
2017/06/07  NULL        3

Body:
You just need to add the CASE expression inside the aggregation function:

SELECT  CONVERT(VARCHAR(10), GETDATE(),111) [Date],
        COUNT(CASE WHEN Region = 'A' THEN Customer END) [Region A],
        COUNT(CASE WHEN Region = 'B' THEN Customer END) [Region B]
FROM tbl_Customers;


问:
ThreadLocal variable is always null
I have a Spring application which creates my business logic method as a bean.

My code looks like:

```<code>public class MyClass {
    private ThreadLocal<String> object1 = new ThreadLocal<String>();

    public String myMethodFoo(MyTestObject testobject) {

        object1.set("Blah");
        ...
        ...
        ...

        return object1.get();
    }

}
</code>```

Now when I run my unit test which calls this method, I always get a null pointer exception on the line where I set the variable value i.e object1.set("Blah").

But somehow it magically disappears when I declare the ThreadLocal object as final. Do ThreadLocal objects always have to be declared final?

答:
No, a ThreadLocal does not have to be defined as final (same rules as with other variables apply here) and it is possible that some other thread is changing your object1 variable to null.

However, ThreadLocal variables should be declared static because:

This class provides thread-local variables. These variables differ
  from their normal counterparts in that each thread that accesses one
  (via its get or set method) has its own, independently initialized
  copy of the variable. ThreadLocal instances are typically private
  static fields in classes that wish to associate state with a thread
  (e.g., a user ID or Transaction ID).

Title: ThreadLocal variable is always null

Body:
I have a Spring application which creates my business logic method as a bean.

My code looks like:

public class MyClass {
    private ThreadLocal<String> object1 = new ThreadLocal<String>();

    public String myMethodFoo(MyTestObject testobject) {

        object1.set("Blah");
        ...
        ...
        ...

        return object1.get();
    }

}

Now when I run my unit test which calls this method, I always get a null pointer exception on the line where I set the variable value i.e object1.set("Blah").

But somehow it magically disappears when I declare the ThreadLocal object as final. Do ThreadLocal objects always have to be declared final?


问:
Global Transaction in GemFire
I am using GemFire for in-memory and Cassandra to act as the source of truth and finding it difficult to implement the global transaction manager for below scenario.

Using CacheWriter to insert/update the data in Cassandra and GemFire Repository for inserting/updating records in GemFire. In case of any failure in either GemFire or Cassandra, I need to rollback the data.

答:
This seems like a question I have answered before (recently too).  Anyway, I could not find it.

I have built a Global Transaction example using Pivotal GemFire combined with an HSQLDB DataSource using SD JPA.

NOTE: This example is part of my Contacts Application Reference implementation (RI) for both Spring Data Geode (for Apache Geode) and Spring Data GemFire (for Pivotal GemFire) showcasing the many capabilities features of Pivotal GemFire/Apache Geode, Spring Data GemFire/Geode and Spring in general.  This repository-example focuses on using Spring Data Commons's Repository Infrastructure and extensions to apply the Repository Data Access patterns from SD Commons to Pivotal GemFire/Apache Geode in a Spring context.  Of the many things this example shows (e.g. CRUD, Querying, custom Repository methods, etc) both Local (Cache) and Global (JTA) based transaction are part of the repository-example.  Unfortunately, the documentation is still largely a WIP.  But I do plan to keep this RI and examples up-to-date as I also use the code as a basis for my conference talks.  Anyway...

While this example combines Pivotal GemFire with a RDBMS (i.e. HSQLDB), it would be possible to swap out HSQLDB for say, Apache Cassandra.  All that is required is that the data source/store be JTA compliant.

The configuration of this example/test is here, and relies rather extensively on Spring Boot "auto-configuration" support.  That is, when Atomikos (open source JTA Transaction Manager) is on the CLASSPATH (or any JTA Transaction Manager supported by Spring Boot), Spring Boot will auto-configure JTA-based transactions.  You can, of course, use other JTA Transaction Manager providers not supported, but then you are left to configure them manually, yourself.  You can even manually configure Atomikos if you like, but Spring Boot's auto-configuration support is highly convenient and recommended.

The only other thing required is to make each data source aware of the JTA Transaction.

For Pivotal GemFire, this entailed setting up a Naming context (i.e javax.naming.InitialContext) that GemFire itself uses in order to "lookup" (by name) and find the existing JTA Transaction.  Essentially, this bean definition associates the JTA "TransactionManager" used with the proper "name" as expected by GemFire in its lookup process.

NOTE: the artificial Naming context would not be required if you were in a managed environment, such as an application server, or even Tomcat, since it provides a Naming context service for your applications.  Of course, then you would need to register the JTA Transaction with that environment instead.  However, since this is a standalone (Spring Boot) app not in a app container, I used Spring's mock/test Naming context support in my NamingContextBuilderFactoryBean class.

All that is left is for you to review Apache Cassandra/DataStax's Documentation on getting Apache Cassandra to participate in the JTA Transaction.  Then you do not need any Pivotal GemFire specific classes (e.g. CacheWriter) to update Cassandra from GemFire.  With JTA, either all JTA-compliant data store persist correctly, or don't.

More information on Pivotal GemFire's Global JTA Transaction support can be found here, and specifically, related material here.

More on Cassandra Transactions can be found starting here.  Hope this helps.

Cheers,
John

Title: Global Transaction in GemFire


问:
SonarQube Web-API - api/resources not returning all projects
I use the following url to extract a number of metrics for each of the projects we have in SonarQube:

```<code>/api/resources?metrics=lines,ncloc,reliability_rating, ...
</code>```

But, it is missing data for (at least) one of the projects. But if I use the following:

```<code>/api/resources?resource=69644
</code>```

It will pull the data for the project. What would cause the project to not show up in the first use case?

We are currently on SonarQube 5.6.

答:
I'm going to answer my own question...

Turns out this particular endpoint has a hard coded limit of 500 components. Which is a known issue and will not be fixed and the endpoint has been deprecated.

To get the same functionality I've switched to using api/projects/index to get the list of projects and then use api/measures/component for each project I'm interested in getting metrics for.

Body:
I use the following url to extract a number of metrics for each of the projects we have in SonarQube:

/api/resources?metrics=lines,ncloc,reliability_rating, ...

But, it is missing data for (at least) one of the projects. But if I use the following:

/api/resources?resource=69644

It will pull the data for the project. What would cause the project to not show up in the first use case?

We are currently on SonarQube 5.6.


问:
How to test components with menu
I'm trying to test, with Jest's snapshots, a component containing a menu. The problem is that the menu's content is not rendered so I can't test the whole component.

Is there a way to force a menu to render all its MenuOption? I tried to use <Menu opened={true}>...</Menu> but the result was the same.

For example, this code will produce a snapshot not containing foo.

```<code>  expect(renderer.create(
    <MenuContext>
      <Menu>
        <MenuOptions>
          <MenuOption>
            foo
          </MenuOption>
        </MenuOptions>
      </Menu>
    </MenuContext>
  )).toMatchSnapshot();
</code>```

答:
Menu component does not render MenuOptions directly to overcome problems with react-native z-index handling. Additionally it needs first to get dimensions of it etc. It would require more steps until you got them rendered in your test.

But the library itself has a lot of tests and in my opinion your test should not depend on internal handling of the library. Instead you should mock it - e.g.

```<code>import 'react-native';
import React from 'react';

jest.mock('react-native-popup-menu', () => ({
  Menu: 'Menu',
  MenuContext: 'MenuContext',
  MenuOptions: 'MenuOptions',
  MenuOption: 'MenuOption',
  MenuTrigger: 'MenuTrigger',
}));

import BasicExample from '../BasicExample';

import renderer from 'react-test-renderer';

test('renders correctly', () => {
  const tree = renderer.create(
    <BasicExample />
  ).toJSON();
  expect(tree).toMatchSnapshot();
});
</code>```

Note - your mocks and your imports should match! (Menu can be imported in two ways).

And then you get nice snapshot - see example snapshot

Title: How to test components with menu

Body:
I'm trying to test, with Jest's snapshots, a component containing a menu. The problem is that the menu's content is not rendered so I can't test the whole component.

Is there a way to force a menu to render all its MenuOption? I tried to use <Menu opened={true}>...</Menu> but the result was the same.

For example, this code will produce a snapshot not containing foo.

  expect(renderer.create(
    <MenuContext>
      <Menu>
        <MenuOptions>
          <MenuOption>
            foo
          </MenuOption>
        </MenuOptions>
      </Menu>
    </MenuContext>
  )).toMatchSnapshot();

Body:
Menu component does not render MenuOptions directly to overcome problems with react-native z-index handling. Additionally it needs first to get dimensions of it etc. It would require more steps until you got them rendered in your test.

But the library itself has a lot of tests and in my opinion your test should not depend on internal handling of the library. Instead you should mock it - e.g.

import 'react-native';
import React from 'react';

jest.mock('react-native-popup-menu', () => ({
  Menu: 'Menu',
  MenuContext: 'MenuContext',
  MenuOptions: 'MenuOptions',
  MenuOption: 'MenuOption',
  MenuTrigger: 'MenuTrigger',
}));

import BasicExample from '../BasicExample';

import renderer from 'react-test-renderer';

test('renders correctly', () => {
  const tree = renderer.create(
    <BasicExample />
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

Note - your mocks and your imports should match! (Menu can be imported in two ways).

And then you get nice snapshot - see example snapshot


问:
Python: Callbacks, Delegates, ... ? What is common?
Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>

答: I have seen listeners and callbacks used. But AFAIK there is no Python way. They should be equally feasible if the application in question is suitable.</p>

OwnerDisplayName: okoman

OwnerDisplayName: muhuk


问:
Bezier path stroking performance issues
My code goes as following -

```<code>[[NSColor whiteColor] set];
// `path' is a bezier path with more than 1000 points in it
[path setLineWidth:2];
[path setLineJoinStyle:NSRoundLineJoinStyle];
[path stroke];
// some other stuff...
</code>```

Running the time profiling tool in Instruments it tells me my app is spending 93.5% of the time doing the last line [path stroke], and Quartz Debugger tells me my app is only running at less than 10 fps (another view changing position on top of it is always causing the update).

I'm looking for ways to improve the performance of stroking the bezier path, sometimes paths with more than 1000 points draws very quickly with >60fps, however in some extreme cases even with the same number of points, perhaps if the points are too far from each other (or too dense?) the performance becomes really sluggish.

I'm not sure what I can do about this. I think caching the view as a bitmap rep is helpful, but it can't really help with live resize.

Edit: commenting out the line [path setLineWidth:2]; certainly helps, but the path looked really too 'thin'.

答:
What do you mean when you say

another view changing position on top
  of it is always causing the update

??

Do you mean that you are not redrawing the view at 60fps? Then that will be why you are not seeing 60fps then.

When

Instruments it tells me my app is
  spending 93.5% of the time

doing something, it doesn't mean 'all available' time it means 93.5% of the cpu cycles your app consumed. ie, it could be no time at all. It isn't enough to determine that you need to optimise. I'm not saying you don't need to, or that stroking massive beziers isn't dog slow. Just that alone doesn't mean much.

Title: Bezier path stroking performance issues

Body:
My code goes as following -

[[NSColor whiteColor] set];
// `path' is a bezier path with more than 1000 points in it
[path setLineWidth:2];
[path setLineJoinStyle:NSRoundLineJoinStyle];
[path stroke];
// some other stuff...

Running the time profiling tool in Instruments it tells me my app is spending 93.5% of the time doing the last line [path stroke], and Quartz Debugger tells me my app is only running at less than 10 fps (another view changing position on top of it is always causing the update).

I'm looking for ways to improve the performance of stroking the bezier path, sometimes paths with more than 1000 points draws very quickly with >60fps, however in some extreme cases even with the same number of points, perhaps if the points are too far from each other (or too dense?) the performance becomes really sluggish.

I'm not sure what I can do about this. I think caching the view as a bitmap rep is helpful, but it can't really help with live resize.

Edit: commenting out the line [path setLineWidth:2]; certainly helps, but the path looked really too 'thin'.


问:
React Component interface to methods
Q: Is there any way to provide an interface to access public methods from a given reusable component?

Scenario: Imagine that I am buiding a Tabs component. It's located inside a parent component, called App:

```<code><App>
    <Tabs />
    <button id="previous">Previous</button>
    <button id="next">Next</button>
</App>
</code>```

As you can see there is two buttons that should interact with Tabs component, moving it to previous or next tab pane.

My implementation consists in keeping next() and previous() methods inside Tabs component:

```<code>export default class Tabs extends React.Component {
    next() {}
    previous() {}
}
</code>```

Q: How can I bind next() and previous() methods to those buttons inside App component? Can I write some kind of interface exposed by Tabs component? What is the best and clean way to do that?

Edit 1: ...

Edit 2: Tabs is a "reusable" component. Many applications can render it inside.

答:
As others said, it doesn't make sense for your buttons to be outside your Tabs Component.

The way I see your code sample, your App component should be your Tabs component, and I assume your Tabs component is representative of some sort of TabsView.

app.js

```<code>import Tabs from './components/tabs';

<App>
  <Tabs/>
</App>
</code>```

tabs.js

```<code>class TabsView extends Component {
  constructor(props){
    super(props);
  }
  render(){
    return(
      <span>{this.props.currentTab}</span>
    );
  }
}

class Tabs extends Component {
  constructor(props){
    super(props);
    this.state = {
      currentTab: 0
    }
  }
  handleOnClickPrev(){
    this.setState({currentTab: currentTab--});
  }
  handleOnClickNext(){
    this.setState({currentTab: currentTab++});
  }

  render(){
    return(
      <div>
        <TabsView currentTab={this.state.currentTab}/>
        <button id="prev" onClick={handleOnClickPrev.bind(this)}>-</button>
        <button id="next" onClick={handleOnClickNext.bind(this)}>+</button>
      </div>
    );
  }
}

export default Tabs;
</code>```

This way all the functionality of your component lives within it. The Tabs component now has all the information it needs. Each Tabs component you use will have its own state and tabs. If you want your currentTab state to come from the App so that you can render this same currentTab in other places you can pass it through from your App component as props.

app.js

```<code><App>
  <Tabs currentTab={this.state.currentTab} handlePrev={} handleNext={}/>
</App>
</code>```

tabs.js

```<code>class Tabs extends Component {
  constructor(props){
    super(props);
  }

  render(){
    return(
      <div>
        <TabsView currentTab={this.props.currentTab}/>
        <button id="prev" onClick={this.props.handlePrev}>-</button>
        <button id="next" onClick={this.props.handleNext}>+</button>
      </div>
    );
  }
}

export default Tabs;
</code>```

If you're looking to display Tabs in certain places and not the buttons in other places, you can use the TabsView component using that same prop that you passes down to the Tabs component.

app.js

```<code><App>
  <Tabs currentTab={this.state.currentTab} handlePrev={} handleNext={}/>
  <TabsView currentTab={this.state.currentTab} />
</App>
</code>```

If you're really hellbent on having your controls for the component live in different place than the component itself, I would suggest passing the same props down to both TabsView and buttons.

app.js

```<code>handlePrev() {
  this.setState({ currentTab: this.state.currentTab - 1 })
}
handleNext(){
  ...
}
render(){
  return (
    <App>
      <TabsView currentTab={this.state.currentTab} />
      <button id="prev" onClick={this.handlePrev.bind(this)}>-</button>
      <button id="next" onClick={this.handleNext.bind(this)}>+</button>
    </App>
  )
}
</code>```

I don't think it makes sense for you to introduce Redux or any other state library at this point. Managing global state just for your tabs component is overkill.

Title: React Component interface to methods

Body:
Q: Is there any way to provide an interface to access public methods from a given reusable component?

Scenario: Imagine that I am buiding a Tabs component. It's located inside a parent component, called App:

<App>
    <Tabs />
    <button id="previous">Previous</button>
    <button id="next">Next</button>
</App>

As you can see there is two buttons that should interact with Tabs component, moving it to previous or next tab pane.

My implementation consists in keeping next() and previous() methods inside Tabs component:

export default class Tabs extends React.Component {
    next() {}
    previous() {}
}

Q: How can I bind next() and previous() methods to those buttons inside App component? Can I write some kind of interface exposed by Tabs component? What is the best and clean way to do that?

Edit 1: ...

Edit 2: Tabs is a "reusable" component. Many applications can render it inside.

Body:
As others said, it doesn't make sense for your buttons to be outside your Tabs Component.

The way I see your code sample, your App component should be your Tabs component, and I assume your Tabs component is representative of some sort of TabsView.

app.js

import Tabs from './components/tabs';

<App>
  <Tabs/>
</App>

tabs.js

class TabsView extends Component {
  constructor(props){
    super(props);
  }
  render(){
    return(
      <span>{this.props.currentTab}</span>
    );
  }
}

class Tabs extends Component {
  constructor(props){
    super(props);
    this.state = {
      currentTab: 0
    }
  }
  handleOnClickPrev(){
    this.setState({currentTab: currentTab--});
  }
  handleOnClickNext(){
    this.setState({currentTab: currentTab++});
  }

  render(){
    return(
      <div>
        <TabsView currentTab={this.state.currentTab}/>
        <button id="prev" onClick={handleOnClickPrev.bind(this)}>-</button>
        <button id="next" onClick={handleOnClickNext.bind(this)}>+</button>
      </div>
    );
  }
}

export default Tabs;

This way all the functionality of your component lives within it. The Tabs component now has all the information it needs. Each Tabs component you use will have its own state and tabs. If you want your currentTab state to come from the App so that you can render this same currentTab in other places you can pass it through from your App component as props.

app.js

<App>
  <Tabs currentTab={this.state.currentTab} handlePrev={} handleNext={}/>
</App>

tabs.js

class Tabs extends Component {
  constructor(props){
    super(props);
  }

  render(){
    return(
      <div>
        <TabsView currentTab={this.props.currentTab}/>
        <button id="prev" onClick={this.props.handlePrev}>-</button>
        <button id="next" onClick={this.props.handleNext}>+</button>
      </div>
    );
  }
}

export default Tabs;

If you're looking to display Tabs in certain places and not the buttons in other places, you can use the TabsView component using that same prop that you passes down to the Tabs component.

app.js

<App>
  <Tabs currentTab={this.state.currentTab} handlePrev={} handleNext={}/>
  <TabsView currentTab={this.state.currentTab} />
</App>

If you're really hellbent on having your controls for the component live in different place than the component itself, I would suggest passing the same props down to both TabsView and buttons.

app.js

handlePrev() {
  this.setState({ currentTab: this.state.currentTab - 1 })
}
handleNext(){
  ...
}
render(){
  return (
    <App>
      <TabsView currentTab={this.state.currentTab} />
      <button id="prev" onClick={this.handlePrev.bind(this)}>-</button>
      <button id="next" onClick={this.handleNext.bind(this)}>+</button>
    </App>
  )
}

I don't think it makes sense for you to introduce Redux or any other state library at this point. Managing global state just for your tabs component is overkill.


问:
How does Git create commits so fast?
From what I understand, each commit in Git is a "snapshot" of the entire repository, which means that, at the very least, every file has to be read. My repository is 9.2 GB and a commit takes a fraction of a second. Makes no sense how it happens so fast.</p>

答:
As far as I understand it so far... Imagine you have a many commits in the master branch and another branch with also many many commits. So if a VCS does not support the concept of git with hashes and so on and just stores the difference of the files and then you want to branch. Then the other VCS has either to revert all changes unitl the shared commit and apply all changes of the other branch or it has to compare all files one by one. In my opinion the hashing algorithm of git seems to be the better approach even if git has to do much iterating/searching I guess.
Idk if I'm right I just started today to read something about git. Feel free to downvote/upvote and comment :D I think it's a topic where only a few people have really in dept knowledge</p>

Title: How does Git create commits so fast?


问:
Push Submodule to GitHub
I have a problem pushing all code to GitHub after installing a component using composer. Here's the current setup:

GitHub repository created.

Repository cloned on local and project files added.

There is one remote called "origin".

Component added using "composer require". Component installed successfully to project sub-folder.

Composer created a git submodule (in this sub-folder) with two remotes. (a) "origin" which points to the component author github url. (b) "composer" which points to the same url and does not have a push url.

Project pushed to GitHub successfully but does NOT push git submodule containing component files.

If I try to push component to project "origin" I get error "Updates were rejected because the remote contains work that you do not have locally".

How do I get this git submodule component code into my GitHub repo? The folder in GitHub is empty.

答:
Digging deeper, I found the component had installed itself as a git submodule. I've updated the question to reflect that. A standard git push didn't deploy it to github. I probably needed to do a "git push --recurse-submodules=on-demand" (or similar).

But to keep things simple, I decided to remove the submodule. It was necessary to run the following to remove the submodule reference.

```<code>git rm --cached [path to submodule]
</code>```

Also, installed.json showed the "installation-source" = source. Other modules had value dist. So I deleted all component files and ran the following to force composer to install a component dist.

```<code>composer require [component] --prefer-dist
composer install --prefer-dist
</code>```

Title: Push Submodule to GitHub

Body:
Digging deeper, I found the component had installed itself as a git submodule. I've updated the question to reflect that. A standard git push didn't deploy it to github. I probably needed to do a "git push --recurse-submodules=on-demand" (or similar).

But to keep things simple, I decided to remove the submodule. It was necessary to run the following to remove the submodule reference.

git rm --cached [path to submodule]

Also, installed.json showed the "installation-source" = source. Other modules had value dist. So I deleted all component files and ran the following to force composer to install a component dist.

composer require [component] --prefer-dist
composer install --prefer-dist


问:
Fluent NHibernate with SQLite
I am using SQLite for unit test.

```<code>private ISession _session;
    [SetUp]
    public virtual void SetUp()
    {
        string[] mappingAssemblies = RepositoryTestsHelper.GetMappingAssemblies();
        configuration = NHibernateSession.Init(new SimpleSessionStorage(), mappingAssemblies,
                               new AutoPersistenceModelGenerator().Generate(),
                               @"C:\Sharp Architecture\SharpArchitecture_1_6_FullSourceAndTemplates (1)\src\NorthwindSample\tests\Northwind.Tests\Hibernate.cfg.xml");
        _session = NHibernateSession.GetDefaultSessionFactory().OpenSession();
        new SchemaExport(configuration).Execute(false, true, false, _session.Connection, null);
    }

    [TearDown]
    public virtual void TearDown()
    {
        NHibernateSession.CloseAllSessions();
        NHibernateSession.Reset();
    }

    [Test]
    public void CanConfirmDatabaseMatchesMappings()
    {
        var allClassMetadata = NHibernateSession.GetDefaultSessionFactory().GetAllClassMetadata();
        foreach (var entry in allClassMetadata)
        {

            NHibernateSession.Current.CreateCriteria(entry.Value.GetMappedClass(EntityMode.Poco))
                 .SetMaxResults(0).List();
        }
    }
</code>```

I am getting the following exception.

```<code>NHibernate.ADOException : could not execute query
[ SELECT this_.CategoryID as CategoryID0_0_, this_.CategoryName as Category2_0_0_ FROM Categories this_ limit 0 ]
[SQL: SELECT this_.CategoryID as CategoryID0_0_, this_.CategoryName as Category2_0_0_ FROM Categories this_ limit 0]
  ----> System.Data.SQLite.SQLiteException : SQLite error
no such table: Categories
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
at NHibernate.Loader.Criteria.CriteriaLoader.List(ISessionImplementor session)
at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results)
at NHibernate.Impl.CriteriaImpl.List(IList results)
at NHibernate.Impl.CriteriaImpl.List()
at Tests.Northwind.Data.NHibernateMaps.MappingIntegrationTests.CanConfirmDatabaseMatchesMappings() in MappingIntegrationTests.cs: line 50
--SQLiteException
at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, ref String strRemain)
at System.Data.SQLite.SQLiteCommand.BuildNextCommand()
at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
</code>```

I am using Sharp Architecture.
Thanks,
Nabin

答:
Take a look at the class:

```<code>FluentNHibernate.Testing.SingleConnectionSessionSourceForSQLiteInMemoryTesting
</code>```

It has a BuildSchema() method.

Title: Fluent NHibernate with SQLite

Body:
I am using SQLite for unit test.

private ISession _session;
    [SetUp]
    public virtual void SetUp()
    {
        string[] mappingAssemblies = RepositoryTestsHelper.GetMappingAssemblies();
        configuration = NHibernateSession.Init(new SimpleSessionStorage(), mappingAssemblies,
                               new AutoPersistenceModelGenerator().Generate(),
                               @"C:\Sharp Architecture\SharpArchitecture_1_6_FullSourceAndTemplates (1)\src\NorthwindSample\tests\Northwind.Tests\Hibernate.cfg.xml");
        _session = NHibernateSession.GetDefaultSessionFactory().OpenSession();
        new SchemaExport(configuration).Execute(false, true, false, _session.Connection, null);
    }

    [TearDown]
    public virtual void TearDown()
    {
        NHibernateSession.CloseAllSessions();
        NHibernateSession.Reset();
    }

    [Test]
    public void CanConfirmDatabaseMatchesMappings()
    {
        var allClassMetadata = NHibernateSession.GetDefaultSessionFactory().GetAllClassMetadata();
        foreach (var entry in allClassMetadata)
        {

            NHibernateSession.Current.CreateCriteria(entry.Value.GetMappedClass(EntityMode.Poco))
                 .SetMaxResults(0).List();
        }
    }

I am getting the following exception.

NHibernate.ADOException : could not execute query
[ SELECT this_.CategoryID as CategoryID0_0_, this_.CategoryName as Category2_0_0_ FROM Categories this_ limit 0 ]
[SQL: SELECT this_.CategoryID as CategoryID0_0_, this_.CategoryName as Category2_0_0_ FROM Categories this_ limit 0]
  ----> System.Data.SQLite.SQLiteException : SQLite error
no such table: Categories
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
at NHibernate.Loader.Criteria.CriteriaLoader.List(ISessionImplementor session)
at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results)
at NHibernate.Impl.CriteriaImpl.List(IList results)
at NHibernate.Impl.CriteriaImpl.List()
at Tests.Northwind.Data.NHibernateMaps.MappingIntegrationTests.CanConfirmDatabaseMatchesMappings() in MappingIntegrationTests.cs: line 50
--SQLiteException
at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, ref String strRemain)
at System.Data.SQLite.SQLiteCommand.BuildNextCommand()
at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)

I am using Sharp Architecture.
Thanks,
Nabin

Body:
Take a look at the class:

FluentNHibernate.Testing.SingleConnectionSessionSourceForSQLiteInMemoryTesting

It has a BuildSchema() method.


问:
bash sed/awk/something for printing lines from match till eof except first line
Well task should be easy i guess but i failed to find the answer.

I need to find some regex in file and print all lines from first match till the end of file but the first found one.

To find and print sed/awk do the trick:

```<code>awk '/regex/,0'
sed '/regex/,$p'
</code>```

But i feel pretty silly that i can't exclude first matching line from output.

Any tips? Pretty sure that shouldn't be hard. I'm just lacking of knowledge.

PS I need exactly to:

find line matching regex

print all lines from this regex to the end of file

exclude first line

in one action.

Excluding line after only find-n-print action leads to more complicated solution

Example

```<code>$ cat file
11 1st Cookie
12 2nd Cookie
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

Find and print:

```<code>$ awk '/Dinner/,0' file
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

What i want to get:

```<code>14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

答:
Here is a POSIX sed version:

```<code>$ sed -ne '/Dinner/{s///; :a' -e 'n;p;ba' -e '}' file
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake
</code>```

Explanation:

/pattern/ The desired pattern

s/// assuming you do not want the pattern included in the output - empty the pattern space.

:a; n; p; ba;

a loop that:

fetches a new line from input (n);

prints it (p);

branches back to label a :a; ...; ba;

With GNU sed:

```<code>$ sed -ne '/Dinner/{s///; :a;n;p;ba}' file
</code>```

Body:
Well task should be easy i guess but i failed to find the answer.

I need to find some regex in file and print all lines from first match till the end of file but the first found one.

To find and print sed/awk do the trick:

awk '/regex/,0'
sed '/regex/,$p'

But i feel pretty silly that i can't exclude first matching line from output.

Any tips? Pretty sure that shouldn't be hard. I'm just lacking of knowledge.

PS I need exactly to:

find line matching regex

print all lines from this regex to the end of file

exclude first line

in one action.

Excluding line after only find-n-print action leads to more complicated solution

Example

$ cat file
11 1st Cookie
12 2nd Cookie
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

Find and print:

$ awk '/Dinner/,0' file
13 1st Dinner
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

What i want to get:

14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

Body:
Here is a POSIX sed version:

$ sed -ne '/Dinner/{s///; :a' -e 'n;p;ba' -e '}' file
14 1st Candy
15 2nd Candy
16 3rd Cookie
17 1st Cake
18 2nd Dinner
19 2nd Cake

Explanation:

/pattern/ The desired pattern

s/// assuming you do not want the pattern included in the output - empty the pattern space.

:a; n; p; ba;

a loop that:

fetches a new line from input (n);

prints it (p);

branches back to label a :a; ...; ba;

With GNU sed:

$ sed -ne '/Dinner/{s///; :a;n;p;ba}' file


问:
Get the center of an element using jquery using .position().left()
Hello I am using a jQuery snippet that uses .position().left()

This finds the position of the left of the element.

Is there any way to find the center of the element?

I did some research and theres no such thing as .position().center()

so I would like to do something like this

jQuery(this).position().center() but this obviously doesnt work

Anyone have an idea on the correct syntax?

Thanks!

答:
$(this).position().left()+$(this)[0].width/2

you can just add the left position from the jquery function to half of the element's width. Just use the width property


问:
Alternatives to CFContent?
I currently store files uploaded to the CMS in a database.  My question does not ask for an alternative to that.  The problem I have is when serving the file from the public facing web server.

Ideally I can cache the files on the web server in the file system, but there is a problem with that.  The system allows different files to be uploaded with the same filename, and I don't want to cache the files using a UUID or MD5 hash because I want the end user to be able to have the filename in the save dialog.

The issues I have with cfcontent are

Each and every request to a file loads the file into memory, I don't mind doing this once to build the cache.

cfcontent does not allow for http download chunking, such that an end user stops downloading a file and later tries to resume it.

Too many requests to large files will tie up the concurrent requests and force normal page requests into the queue.

P.S.  The files are stored in the database because the database is the only form of communication between the CMS and the public site.

答:
Offhand, I'd suggest using the primary key from the db as the directory name, so you can keep the files with the original name, and still store them in a unique location on the server.

So, let's say someone uploads document.docx, and it's assigned the ID 3.  Your url would point to /content/3/document.docx or similar.

Title: Alternatives to CFContent?


问:
Center and dynamically size the horizontal drop down menu bar using CSS
What I am trying to do is limit the horizontal size of the menu to whatever number and size of the options there are.  And also center the whole thing.  Right now everything is at the top and left justified.  In addition it also takes up the entire width of the page.

I would like it to appear after a header image and be centered with a dynamic size appropriate for the number of selections.

```<code>    <!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="Width=device-Width, initial-scale=1">
        <style>
            /* CSSTerm.com Horizontal Easy DropDown CSS menu */

            .drop_menu {
                position:relative;
                background:#005555;
                padding:0;
                margin:auto;
                list-style-type:none;
                height:40px;
                width:360;
            }
            .drop_menu li {
            float:left;
            display:inline-block;
            }
            .drop_menu li a {
                padding:12px 20px;
                display:block;
                color:#fff;
                text-decoration:none;
                font:12px arial, verdana, sans-serif;
                border-right:1px solid #75809a;
            }

            /* Submenu */
            .drop_menu ul {
                text-align: center;
                position:absolute;
                left:-9999px;
                top:-9999px;
                list-style-type:none;
                display:inline;
            }
            .drop_menu li:hover { position:relative; background:#75809a;  }
            .drop_menu li:hover ul {
                left:0px;
                top:38px;
                background:#75809a;
                padding:0px;
            }

            .drop_menu li:hover ul li a {
                padding:10px;
                display:block;
                width:168px;
                text-indent:15px;
                background-color:#75809a;
            }
            .drop_menu li:hover ul li a:hover { background:#005555;  }

        </style>
        <title>Home menu for YavapaiNA.org site</title>
        <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
        <script type="text/javascript" src="js/Version_1_0_1.js"></script>
        <SCRIPT TYPE="text/javascript">
            //      var ScreenWidth = document.documentElement.clientWidth;
            //      var ScreenHeight = document.documentElement.clientHeight;

            var LeftsideMeetingsPopup = ((document.documentElement.clientWidth / 2) - 550);
            var TopOfMeetingsPopup = ((document.documentElement.clientHeight / 2) - 300);

            var LeftsideEventsPopup = ((document.documentElement.clientWidth / 2) - 300);
            var TopOfEventsPopup = ((document.documentElement.clientHeight / 2) - 230);

            var MeetingsParams = 'Width=1100,Height=600,Left=' + LeftsideMeetingsPopup + ',Top=' + TopOfMeetingsPopup + ',scrollbars=no';
            var EventsParams = 'Width=600,Height=460,Left=' + LeftsideEventsPopup + ',Top=' + TopOfEventsPopup + ',scrollbars=no';

            function Meetings_Popup(mylink, windowname) {
             if (!window.focus) return true;
             var href;
             if (typeof(mylink) == 'string') href = mylink;
             else href = mylink.href;
             window.open(href, windowname, MeetingsParams);
             return false;
            }

            function Events_Popup(mylink, windowname) {
             if (!window.focus) return true;
             var href;
             if (typeof(mylink) == 'string') href = mylink;
             else href = mylink.href;
             window.open(href, windowname, EventsParams);
             return false;
            }
            //          alert(MeetingsParams);
            //          alert(EventsParams);

        </SCRIPT>
    </head>
    <body>
        <div align="center" style="width:360">
            <ul class="drop_menu">
                <li><a href="#">Home</a></li>
                <li><A HREF="/Meetings_Popup.html" onClick="return Meetings_Popup(this, 'notes')">Meeting List</a></li>
                <li><A HREF="/Events_Popup.html" onClick="return Events_Popup(this, 'notes')">Events</a></li>
                <li>
                    <a href='#'>Misc Links</a>
                    <ul>
                        <li><a href="#">Arizona</a></li>
                        <li><a href="#">Camp Verde</a></li>
                        <li><a href="#">Some Services</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </body>
</html>
</code>```

答:
Let me know if this helps

* {
  box-sizing: border-box;
}
.drop_menu {
  background: #005555;
  list-style-type: none;
  height: 40px;
  width: 460px;
  display: flex;
  padding: 0;
  margin:0 auto;
}
img {
  float: left;
}
.drop_menu li a {
  padding: 12px 20px;
  display: inline-block;
  color: #fff;
  text-decoration: none;
  font: 12px arial, verdana, sans-serif;
}
.drop_menu > li {
  border-right: 1px solid #75809a;
  width: 100%;
  text-align: center;
}
.drop_menu > li:last-child {
  border-right: none;
}

/* Submenu */

.drop_menu ul {
  text-align: left;
  position: absolute;
  left: -9999px;
  top: -9999px;
  list-style-type: none;
  display: inline;
}

.drop_menu li:hover {
  position: relative;
  background: #75809a;
}

.drop_menu li:hover ul {
  left: 0px;
  top: 38px;
  background: #75809a;
  padding: 0px;
}

.drop_menu li:hover ul li a {
  padding: 10px;
  display: block;
  width: 168px;
  text-indent: 15px;
  background-color: #75809a;
}

.drop_menu li:hover ul li a:hover {
  background: #005555;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width:100%; background-color: red; height: 100px;">
  <img src="http://placehold.it/100x40" />
  <ul class="drop_menu">
    <li>Home</li>
    <li>Meeting List</li>
    <li>Events</li>
    <li>
      Misc Links
      <ul>
        <li>Arizona</li>
        <li>Camp Verde</li>
        <li>Some Services</li>
      </ul>
    </li>
  </ul>
</div></code>```

Body:
What I am trying to do is limit the horizontal size of the menu to whatever number and size of the options there are.  And also center the whole thing.  Right now everything is at the top and left justified.  In addition it also takes up the entire width of the page.

I would like it to appear after a header image and be centered with a dynamic size appropriate for the number of selections.

    <!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="Width=device-Width, initial-scale=1">

        <title>Home menu for YavapaiNA.org site</title>

Home

Meeting List

Events

                    Misc Links

Arizona

Camp Verde

Some Services

Body:
Let me know if this helps

* {
  box-sizing: border-box;
}
.drop_menu {
  background: #005555;
  list-style-type: none;
  height: 40px;
  width: 460px;
  display: flex;
  padding: 0;
  margin:0 auto;
}
img {
  float: left;
}
.drop_menu li a {
  padding: 12px 20px;
  display: inline-block;
  color: #fff;
  text-decoration: none;
  font: 12px arial, verdana, sans-serif;
}
.drop_menu > li {
  border-right: 1px solid #75809a;
  width: 100%;
  text-align: center;
}
.drop_menu > li:last-child {
  border-right: none;
}

/* Submenu */

.drop_menu ul {
  text-align: left;
  position: absolute;
  left: -9999px;
  top: -9999px;
  list-style-type: none;
  display: inline;
}

.drop_menu li:hover {
  position: relative;
  background: #75809a;
}

.drop_menu li:hover ul {
  left: 0px;
  top: 38px;
  background: #75809a;
  padding: 0px;
}

.drop_menu li:hover ul li a {
  padding: 10px;
  display: block;
  width: 168px;
  text-indent: 15px;
  background-color: #75809a;
}

.drop_menu li:hover ul li a:hover {
  background: #005555;
}

<div style="width:100%; background-color: red; height: 100px;">
  <img src="http://placehold.it/100x40" />
  <ul class="drop_menu">
    <li><a href="#">Home</a></li>
    <li><a href="/Meetings_Popup.html" onClick="return Meetings_Popup(this, 'notes')">Meeting List</a></li>
    <li><a href="/Events_Popup.html" onClick="return Events_Popup(this, 'notes')">Events</a></li>
    <li>
      <a href='#'>Misc Links</a>
      <ul>
        <li><a href="#">Arizona</a></li>
        <li><a href="#">Camp Verde</a></li>
        <li><a href="#">Some Services</a></li>
      </ul>
    </li>
  </ul>
</div>


问:
Azure Automation RunBook Download File from Blob To VM
Is there a way to use Azure Automation to download a file from azure storage? I can currently connect to the VM using templates from the gallery to create files/folder but how would I download a file from storage?

I am currently trying to use Get-AzureStorageBlob command from Invoke-command -ScriptBlock

答:
If you are trying to use the powershell cmdlets, you need to remember to login to Azure prior to executing them.  See the documentation.  You would need to login in on the remote computer (ie: inside the Script Block).

An alternative is to have azcopy accessible, and simply pass in the key information via Automation Credentials.


问:
Xcode swift Terminating app due to uncaught exception 'NSUnknownKeyException
I have an array like this :

```<code>let listCourse = ["Pommes",
                      "Framboises",
                      "Pâtes",
                      "Tomates",
                      "Boudoirs",
                      "Coca",
                      "Lait"]
</code>```

It is displayed in a TableViewController:

```<code>        if let mycell = cell as? MyTableViewCell {
            mycell.myLabel.text = self.listCourse[indexPath.row]

        } // ou if cell is MyTableViewCell

        return cell

    }
</code>```

When I click on an item it opens a ViewController with the name of the item clicked and it should have a button that close this viewController.
This is to display the view controller when an item is clicked :

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print("Select article \(self.listCourse[indexPath.row])")

        let storyboard = UIStoryboard(name:"Main", bundle:nil)
        if let controller = storyboard.instantiateViewController(withIdentifier: "ViewController") as? ViewController{
            self.present(controller, animated: true){

            }
            controller.myDetail.text = self.listCourse[indexPath.row]

        }

    }
</code>```

This is the ViewController :

```<code> @IBAction func closeButton(_ sender: Any) {

       self.dismiss(animated: true, completion: nil)

    }

    @IBOutlet weak var myDetail: UILabel!
</code>```

But when I run the application I get a crash and this error :

TableViewController[11561:421467] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key closeButton.'

When I delete the button it works, I don't understand why, can someone have any ideas ?

答:
I found the problem, here my new ViewController : </p>

```<code>@IBAction func closeButton(_ sender: Any) {

       self.dismiss(animated: true, completion: nil)

    }

    @IBOutlet weak var myDetail: UILabel!

    @IBOutlet weak var closeButton: UIButton!
</code>```

Body:
I have an array like this :

let listCourse = ["Pommes",
                      "Framboises",
                      "Pâtes",
                      "Tomates",
                      "Boudoirs",
                      "Coca",
                      "Lait"]

It is displayed in a TableViewController:

        if let mycell = cell as? MyTableViewCell {
            mycell.myLabel.text = self.listCourse[indexPath.row]

        } // ou if cell is MyTableViewCell

        return cell

    }

When I click on an item it opens a ViewController with the name of the item clicked and it should have a button that close this viewController.
This is to display the view controller when an item is clicked :

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print("Select article \(self.listCourse[indexPath.row])")

        let storyboard = UIStoryboard(name:"Main", bundle:nil)
        if let controller = storyboard.instantiateViewController(withIdentifier: "ViewController") as? ViewController{
            self.present(controller, animated: true){

            }
            controller.myDetail.text = self.listCourse[indexPath.row]

        }

    }

This is the ViewController :

 @IBAction func closeButton(_ sender: Any) {

       self.dismiss(animated: true, completion: nil)

    }

    @IBOutlet weak var myDetail: UILabel!

But when I run the application I get a crash and this error :

TableViewController[11561:421467] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key closeButton.'

When I delete the button it works, I don't understand why, can someone have any ideas ?

Body:
I found the problem, here my new ViewController :

@IBAction func closeButton(_ sender: Any) {

       self.dismiss(animated: true, completion: nil)

    }

    @IBOutlet weak var myDetail: UILabel!

    @IBOutlet weak var closeButton: UIButton!


问:
How to understand this C++ palindrome code?
I recently came to the solution of the palindrome problem, but I do not understand how this part of code works (with rbegin and rend). Can someone explain it to me?</p>

```<code>#include <iostream>
#include <string>

using namespace std;
bool checkPalindrome(string);
int main()
{
    string inputString = "palindrom";
    cout << checkPalindrome(inputString);
return 0;
}

bool checkPalindrome(std::string inputString)
{
   return (inputString == string(inputString.rbegin(), inputString.rend()));
}
</code>```

答:
Basically, you're reversing inputString and then checking if the two strings are still equal.

rbegin() and rend() are reverse iterators. There's a string constructor that takes a beginning and ending iterator as parameters.

All string(inputString.rbegin(), inputString.rend()) does is return the reverse of inputString.

Body:
I recently came to the solution of the palindrome problem, but I do not understand how this part of code works (with rbegin and rend). Can someone explain it to me?

#include <iostream>
#include <string>

using namespace std;
bool checkPalindrome(string);
int main()
{
    string inputString = "palindrom";
    cout << checkPalindrome(inputString);
return 0;
}

bool checkPalindrome(std::string inputString)
{
   return (inputString == string(inputString.rbegin(), inputString.rend()));
}


问:
function to be run multiple times to generate the final dataset in R
I am new to R and have written a function that needs to be run multiple times to generate the final dataset.
So the multiple times is determined by the vector of unique years and again based on these years every single time the function gives an output.
Still I am not getting the right output.

Desired output: for eg it takes 10 samples from each year, after 10th run I should have 100 rows of correct output.

```<code>create_strsample <- function(n1,n2){
   yr <- c(2010,2011,2012,2013)
   for(i in 1:length(yr)){

     k1<-subset(data,format(as.Date(data$account_opening_date),"%Y")==yr[i])
     r1 <-sample(which(!is.na(k1$account_closing_date)),n1,replace=FALSE)
     r2<-sample(which(is.na(k1$account_closing_date)),n2,replace=FALSE)
     #final.data <-k1[c(r1,r2),]
     sample.data <- lapply(yr, function(x) {f.data<-create_strsample(200,800)})

     k1 <- do.call(rbind,k1)
     return(k1)
   }

   final <- do.call(rbind,sample.data)
   return(final)
}
stratified.sample.data <- create_strsample(200,800)
</code>```

答:
I tried this later after your suggestion @herbaman for the desired output minus the lapply.</p>

```<code>create_strsample <- function(n1,n2){
final.data <- NULL
yr <- c(2010,2011,2012,2013)

for(i in 1:length(yr)){

    k1<-subset(data,format(as.Date(data$account_opening_date),"%Y")==yr[i])
    r1 <- k1[sample(which(!is.na(k1$account_closing_date)),n1,replace=FALSE), ]
    r2 <- k1[sample(which(is.na(k1$account_closing_date)),n2,replace=FALSE), ]
    sample.data <- rbind(r1,r2)
    final.data <- rbind(final.data, sample.data)
}

return(final.data)
}

 stratified.sample.data <- create_strsample(200,800)
</code>```

Body:
I am new to R and have written a function that needs to be run multiple times to generate the final dataset.
So the multiple times is determined by the vector of unique years and again based on these years every single time the function gives an output.
Still I am not getting the right output.

Desired output: for eg it takes 10 samples from each year, after 10th run I should have 100 rows of correct output.

create_strsample <- function(n1,n2){
   yr <- c(2010,2011,2012,2013)
   for(i in 1:length(yr)){

     k1<-subset(data,format(as.Date(data$account_opening_date),"%Y")==yr[i])
     r1 <-sample(which(!is.na(k1$account_closing_date)),n1,replace=FALSE)
     r2<-sample(which(is.na(k1$account_closing_date)),n2,replace=FALSE)
     #final.data <-k1[c(r1,r2),]
     sample.data <- lapply(yr, function(x) {f.data<-create_strsample(200,800)})

     k1 <- do.call(rbind,k1)
     return(k1)
   }

   final <- do.call(rbind,sample.data)
   return(final)
}
stratified.sample.data <- create_strsample(200,800)

Body:
I tried this later after your suggestion @herbaman for the desired output minus the lapply.

create_strsample <- function(n1,n2){
final.data <- NULL
yr <- c(2010,2011,2012,2013)

for(i in 1:length(yr)){

    k1<-subset(data,format(as.Date(data$account_opening_date),"%Y")==yr[i])
    r1 <- k1[sample(which(!is.na(k1$account_closing_date)),n1,replace=FALSE), ]
    r2 <- k1[sample(which(is.na(k1$account_closing_date)),n2,replace=FALSE), ]
    sample.data <- rbind(r1,r2)
    final.data <- rbind(final.data, sample.data)
}

return(final.data)
}

 stratified.sample.data <- create_strsample(200,800)


问:
How to keep window visible at all times, but not force it to be on top
I'm creating a "desktop gadget" of sorts, I've disabled manual minimizing  of the window, but now there is another problem: the system can still hide the window if the user presses Windows+D, for example.

When hidden that way, no usual minimize/resize/visibility events are fired.
I want to do something almost like TopMost, but without forcing the window order.

Maybe it's possible to install a global shortcut event using win32 API, and briefly set TopMost to true, but that sounds very hackish.

I found one solution, but it does not seem to work on Windows 10: Keeping window visible through "Show Desktop"/Win+D
 The other common option, which would be writing an actual desktop gadget, is not possible on Windows 10, given their deprecation.

Are there any other methods to keep a window visible (but not on top of the screen) at all moments?

答:
This function is working for me:

```<code>BOOL FixShowDesktop(HWND hWnd)
{
    HWND hWndTmp = FindWindowEx(NULL, NULL, L"Progman", NULL);
    if (hWndTmp)
    {
        hWndTmp = FindWindowEx(hWndTmp, NULL, L"SHELLDLL_DefView", NULL);
        if (hWndTmp)
        {
            SetWindowLongPtr(hWnd, -8, (LONG_PTR)hWndTmp);
            return TRUE;
        }
    }
    return FALSE;
}
</code>```

Note, this code is a bit better then from Keeping window visible through "Show Desktop"/Win+D because the window can be overflowed by other windows (like any other window). Using SetParent places window under all other windows.

Body:
This function is working for me:

BOOL FixShowDesktop(HWND hWnd)
{
    HWND hWndTmp = FindWindowEx(NULL, NULL, L"Progman", NULL);
    if (hWndTmp)
    {
        hWndTmp = FindWindowEx(hWndTmp, NULL, L"SHELLDLL_DefView", NULL);
        if (hWndTmp)
        {
            SetWindowLongPtr(hWnd, -8, (LONG_PTR)hWndTmp);
            return TRUE;
        }
    }
    return FALSE;
}

Note, this code is a bit better then from Keeping window visible through "Show Desktop"/Win+D because the window can be overflowed by other windows (like any other window). Using SetParent places window under all other windows.


问:
Trouble Applying Function to Each Cell in Pandas DataFrame
I have a Pandas DataFrame with a single column ('publish_time') of type datetime.  I want to just get the times, so I tried something like this:

```<code>df.applymap(datetime.time)
</code>```

Unfortunately, I get a TypeError:

```<code>TypeError: ('an integer is required', u'occurred at index publish_time')
</code>```

I'm a little lost here because I'm applying a datetime function to a bunch of datetime objects, so I don't know why Python expects an integer.  Any suggestions?

Thanks!

答:
With the dt accessor, you can get the time component in a vectorized way:

```<code>df = pd.DataFrame({'publish_time': ['20170606 12:04', '20170606 17:02']})

df
Out:
     publish_time
0  20170606 12:04
1  20170606 17:02

df['publish_time'] = pd.to_datetime(df['publish_time'])

df['publish_time'].dt.time
Out:
0    12:04:00
1    17:02:00
Name: publish_time, dtype: object
</code>```

Body:
I have a Pandas DataFrame with a single column ('publish_time') of type datetime.  I want to just get the times, so I tried something like this:

df.applymap(datetime.time)

Unfortunately, I get a TypeError:

TypeError: ('an integer is required', u'occurred at index publish_time')

I'm a little lost here because I'm applying a datetime function to a bunch of datetime objects, so I don't know why Python expects an integer.  Any suggestions?

Thanks!

Body:
With the dt accessor, you can get the time component in a vectorized way:

df = pd.DataFrame({'publish_time': ['20170606 12:04', '20170606 17:02']})

df
Out:
     publish_time
0  20170606 12:04
1  20170606 17:02

df['publish_time'] = pd.to_datetime(df['publish_time'])

df['publish_time'].dt.time
Out:
0    12:04:00
1    17:02:00
Name: publish_time, dtype: object


问:
Create a JSON and post to API using php
What I am trying to do is to create a json file and  submit to API via CURL

PHP CURL EXAMPLE:

```<code>    //API Url
    $url = 'https://example.com/api';

    //Initiate cURL.
    $ch = curl_init($url);

    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );

    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);

    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);

    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

    //Execute the request
    $result = curl_exec($ch);

    ?>
</code>```

The problem is I need a json format like this:

THE JSON FORMAT I NEED TO SEND VIA POST:

```<code>{
  "transaction-request": {
    "version": "1.0.0",
    "verification": {
      "merchantId": "*****",
      "merchantKey": "*****"
    },
    "sale": {
      "order": {
        "reference": "123456789",
        "totalAmount": "50000"
      },
      "payment": {
        "acquirer": "1",
        "method": "1",
        "amount": "10000",
        "currency": "986",
        "country": "BRA",
        "numberOfPayments": "1",
        "groupNumber": "0",
        "flag": "mastercard",
        "cardHolder": "Jose da Silva",
        "cardNumber": "*****",
        "cardSecurityCode": "123",
        "cardExpirationDate": "201805",
        "saveCreditCard": "true",
        "generateToken": "false",
        "departureTax": "0"
      },
      "billing": {
        "customerIdentity": "1",
        "name": "Fulano de Tal",
        "address": "Av. Federativa, 230",
        "address2": "10 Andar",
        "city": "Mogi das Cruzes",
        "state": "SP",
        "postalCode": "20031170",
        "country": "BR",
        "phone": "*****",
        "email": "*****"
      },
      "urlReturn": "http://loja.exemplo.com.br",
      "fraud": "false"
    }
  }
}
</code>```

How to create this json format in my php CURL example?

答:
your curl code looks good, if you just want to know how to write the data for json_encode, based on your test json, it'd look like this:

```<code>$jsonData = array (
        'transaction-request' => array (
                'version' => '1.0.0',
                'verification' => array (
                        'merchantId' => '*****',
                        'merchantKey' => '*****'
                ),
                'sale' => array (
                        'order' => array (
                                'reference' => '123456789',
                                'totalAmount' => '50000'
                        ),
                        'payment' => array (
                                'acquirer' => '1',
                                'method' => '1',
                                'amount' => '10000',
                                'currency' => '986',
                                'country' => 'BRA',
                                'numberOfPayments' => '1',
                                'groupNumber' => '0',
                                'flag' => 'mastercard',
                                'cardHolder' => 'Jose da Silva',
                                'cardNumber' => '*****',
                                'cardSecurityCode' => '123',
                                'cardExpirationDate' => '201805',
                                'saveCreditCard' => 'true',
                                'generateToken' => 'false',
                                'departureTax' => '0'
                        ),
                        'billing' => array (
                                'customerIdentity' => '1',
                                'name' => 'Fulano de Tal',
                                'address' => 'Av. Federativa, 230',
                                'address2' => '10 Andar',
                                'city' => 'Mogi das Cruzes',
                                'state' => 'SP',
                                'postalCode' => '20031170',
                                'country' => 'BR',
                                'phone' => '*****',
                                'email' => '*****'
                        ),
                        'urlReturn' => 'http://loja.exemplo.com.br',
                        'fraud' => 'false'
                )
        )
);
</code>```

and that code was created by echo var_export(json_decode($json,true),true); , and formatted by eclipse

as a sidenote, 'fraud'=>'false' looks hilarious. i'm sure the bad guys are all going to send 'fraud'=>'true'. reminds me of https://www.ietf.org/rfc/rfc3514.txt

Title: Create a JSON and post to API using php

Body:
What I am trying to do is to create a json file and  submit to API via CURL

PHP CURL EXAMPLE:

    //API Url
    $url = 'https://example.com/api';

    //Initiate cURL.
    $ch = curl_init($url);

    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );

    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);

    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);

    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

    //Execute the request
    $result = curl_exec($ch);

    ?>

The problem is I need a json format like this:

THE JSON FORMAT I NEED TO SEND VIA POST:

{
  "transaction-request": {
    "version": "1.0.0",
    "verification": {
      "merchantId": "*****",
      "merchantKey": "*****"
    },
    "sale": {
      "order": {
        "reference": "123456789",
        "totalAmount": "50000"
      },
      "payment": {
        "acquirer": "1",
        "method": "1",
        "amount": "10000",
        "currency": "986",
        "country": "BRA",
        "numberOfPayments": "1",
        "groupNumber": "0",
        "flag": "mastercard",
        "cardHolder": "Jose da Silva",
        "cardNumber": "*****",
        "cardSecurityCode": "123",
        "cardExpirationDate": "201805",
        "saveCreditCard": "true",
        "generateToken": "false",
        "departureTax": "0"
      },
      "billing": {
        "customerIdentity": "1",
        "name": "Fulano de Tal",
        "address": "Av. Federativa, 230",
        "address2": "10 Andar",
        "city": "Mogi das Cruzes",
        "state": "SP",
        "postalCode": "20031170",
        "country": "BR",
        "phone": "*****",
        "email": "*****"
      },
      "urlReturn": "http://loja.exemplo.com.br",
      "fraud": "false"
    }
  }
}

How to create this json format in my php CURL example?

Body:
your curl code looks good, if you just want to know how to write the data for json_encode, based on your test json, it'd look like this:

$jsonData = array (
        'transaction-request' => array (
                'version' => '1.0.0',
                'verification' => array (
                        'merchantId' => '*****',
                        'merchantKey' => '*****'
                ),
                'sale' => array (
                        'order' => array (
                                'reference' => '123456789',
                                'totalAmount' => '50000'
                        ),
                        'payment' => array (
                                'acquirer' => '1',
                                'method' => '1',
                                'amount' => '10000',
                                'currency' => '986',
                                'country' => 'BRA',
                                'numberOfPayments' => '1',
                                'groupNumber' => '0',
                                'flag' => 'mastercard',
                                'cardHolder' => 'Jose da Silva',
                                'cardNumber' => '*****',
                                'cardSecurityCode' => '123',
                                'cardExpirationDate' => '201805',
                                'saveCreditCard' => 'true',
                                'generateToken' => 'false',
                                'departureTax' => '0'
                        ),
                        'billing' => array (
                                'customerIdentity' => '1',
                                'name' => 'Fulano de Tal',
                                'address' => 'Av. Federativa, 230',
                                'address2' => '10 Andar',
                                'city' => 'Mogi das Cruzes',
                                'state' => 'SP',
                                'postalCode' => '20031170',
                                'country' => 'BR',
                                'phone' => '*****',
                                'email' => '*****'
                        ),
                        'urlReturn' => 'http://loja.exemplo.com.br',
                        'fraud' => 'false'
                )
        )
);

and that code was created by echo var_export(json_decode($json,true),true); , and formatted by eclipse

as a sidenote, 'fraud'=>'false' looks hilarious. i'm sure the bad guys are all going to send 'fraud'=>'true'. reminds me of https://www.ietf.org/rfc/rfc3514.txt


问:
LABVIEW - How to create a csv file with string, double and integer?
I'm working in LABView and I want to create a csv file with an header string, 8192 double type values and a integer type value at the end. I tried with the clusters but it seems not work and so I'm stucked. My situation is the following:

If I connect the output cluster with the "Create Spreadsheet" vi it gives me incompatible type error and same if I use the "Convert Cluster to Array" vi.

Can anyone help me?

答:
Convert all the double arrays to string arrays in the format you want and make your input one big string array, in that way you can also included the header. So the code would look like this, it is an older version of labview but works the same way.

And the result array that gets written to file looks likes this:


问:
Why cannot I find the cvPoint2D32f function in opencv?
I am using Python 2.7.13 |Anaconda 4.3.1 (64-bit) and OpenCv '2.4.13.2'.
I am trying to apply geometrical transformation to images for which I need to use

```<code>CvPoint2D32f center = cvPoint2D32f(x, y)
</code>```

but I am not able to find this function, is this not available in python or are deprecated.

答:
The type CvPoint2D32f is an older/deprecated type. OpenCV 2 introduced the type Point2f to replace it. Regardless, you don't need that type in Python. What you likely need is a numpy array with the dtype = np.float32. For points, the array should be constructed like:

```<code>points = np.array([ [[x1, y1]], ..., [[xn, yn]] ], dtype=np.float32)
</code>```

You won't always need to set the dtype, as some functions (like cv2.findHomography() for example) will take integers.

For an example of these points being used, with the images from this tutorial, we could do the following to find and apply an homography to an image:

```<code>import cv2
import numpy as np

src = cv2.imread('book2.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]], dtype=np.float32)
dst = cv2.imread('book1.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]], dtype=np.float32)

transf = cv2.getPerspectiveTransform(pts_src, pts_dst)
warped = cv2.warpPerspective(src, transf, (dst.shape[1],dst.shape[0]))

alpha = 0.5
beta = 1 - alpha
blended = cv2.addWeighted(warped, alpha, dst, beta, 1.0)

cv2.imshow("Blended Warped Image", blended)
cv2.waitKey(0)
</code>```

Which will result in the following image:

Body:
I am using Python 2.7.13 |Anaconda 4.3.1 (64-bit) and OpenCv '2.4.13.2'.
I am trying to apply geometrical transformation to images for which I need to use

CvPoint2D32f center = cvPoint2D32f(x, y)

but I am not able to find this function, is this not available in python or are deprecated.

Body:
The type CvPoint2D32f is an older/deprecated type. OpenCV 2 introduced the type Point2f to replace it. Regardless, you don't need that type in Python. What you likely need is a numpy array with the dtype = np.float32. For points, the array should be constructed like:

points = np.array([ [[x1, y1]], ..., [[xn, yn]] ], dtype=np.float32)

You won't always need to set the dtype, as some functions (like cv2.findHomography() for example) will take integers.

For an example of these points being used, with the images from this tutorial, we could do the following to find and apply an homography to an image:

import cv2
import numpy as np

src = cv2.imread('book2.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]], dtype=np.float32)
dst = cv2.imread('book1.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]], dtype=np.float32)

transf = cv2.getPerspectiveTransform(pts_src, pts_dst)
warped = cv2.warpPerspective(src, transf, (dst.shape[1],dst.shape[0]))

alpha = 0.5
beta = 1 - alpha
blended = cv2.addWeighted(warped, alpha, dst, beta, 1.0)

cv2.imshow("Blended Warped Image", blended)
cv2.waitKey(0)

Which will result in the following image:


问:
C# Regex replace all alphabets except :abc
I have tried few combinations in C# but with no luck

I want to replace any alphabet in the string with empty string,  except where string contains :abc as the last 4 characters?

Test123 will become 123

Testabc123 will become 123

Test:abc123 will become 123

Test123:abc will become 123:abc

Testabc123:abc will become 123:abc

In the above examples,  alphabets were replaced to empty string, except where :abc were the last 4 characters, and then numbers:abc were not replaced by empty string

Can you please suggest appropriate regex?

答:
Your task is still not quite clear. How many digit groups can there be in the string? Do some digits always preceed :abc? Does the string represent a single line or do you want it to be multiline and do replacement in each line?

If you use it just on a single string, try

Regex.Replace(s, @"[^\d]+(\d*:abc$)|[^\d]+", "$1")

The idea behind this one is simple: IF non-digits part ends with (optionally) some digits  and :abc AND is at the end of the line (such substring will be matched by the first part of the pattern before |) THEN preserve them ($1); ELSE (substring is matched by the last part of the pattern) leave nothing from this match.

P.S. Generally regular expresssions are not very good at "negative patterns" and sometimes it is easier to roll up some code. Or as Jamie Zawinski famously quoted:

Some people, when confronted with a problem, think

  “I know, I'll use regular expressions.”

  Now they have two problems.

So how hard can it be?

    static string ReplaceAlphaExceptAbc(string src)
    {
        const string preserveEndPattern = ":abc";
        var res = new StringBuilder(src.Length);

        for (int i = 0; i < src.Length; i++)
        {
            var ch = src[i];
            if (Char.IsDigit(ch))
                res.Append(ch);
        }

        if (src.EndsWith(preserveEndPattern))
            res.Append(preserveEndPattern);
        return res.ToString();
    }
```


问:
Set magic line width to the anchor not the list item
Hello I am using a magic line and I get it working, but the width of the magic line is taking the width of the
 element, but I want it to take the width of the  element. Can anyone help me edit the jquery code to do this?

Here is the html:

```<code><ul id="menu-main-menu">
    <li><a href="#">text</a></li>
    <li><a href="#">text text</a></li>
    <li><a href="#">text text text</a></li>
    <li><a href="#">text text text text</a></li>
</ul>
</code>```

css:

```<code>#menu-main-menu {
  display: flex;
}

#menu-main-menu li {
  flex: 1 1 100%;
  text-align: center;
  list-style-type: none;
  position: relative;
}

#menu-main-menu li a {
  padding: 0 10px;
}

#magic-line {
    position: absolute !important;
    top: 0px;
    left: 0;
    width: 100px;
    height: 2px;
    background: #000;
    padding-top: 0 !important;
    margin-right: 0 !important;
}
</code>```

jquery (sorry about the length)

```<code>jQuery(function() {

    var $el, leftPos, newWidth,
        $mainNav = jQuery("#menu-main-menu");

    $mainNav.append("<li id='magic-line'></li>");
    var $magicLine = jQuery("#magic-line");

    if( jQuery('#menu-main-menu .current-menu-ancestor').length ) {
        var currentPageWidth = jQuery('#menu-main-menu .current-menu-ancestor > a').parent().width();
        var currentPageLeft = jQuery('#menu-main-menu .current-menu-ancestor > a').parent().position().left;
    }

    if( jQuery('#menu-main-menu .current-menu-item').length ) {
        var currentPageWidth = jQuery('#menu-main-menu .current-menu-item > a').parent().width();
        var currentPageLeft = jQuery('#menu-main-menu .current-menu-item > a').parent().position().left;
    }

    $magicLine
        .width(currentPageWidth)
        .css("left", currentPageLeft)
        .data("origLeft", $magicLine.position().left)
        .data("origWidth", $magicLine.width());

    jQuery("#menu-main-menu li").hover(function() {
        $el = jQuery(this);
        leftPos = $el.position().left;
        newWidth = $el.width();
        $magicLine.stop().animate({
            left: leftPos,
            width: newWidth
        });
    }, function() {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });

    jQuery("#menu-main-menu li .sub-menu li").hover(function() {
        $magicLine.stop()
    }, function() {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });
}, 1500);
</code>```

and the jsfiddle

here

Thanks!

答:
You should change this

```<code>jQuery("#menu-main-menu li").hover(function() {
            $el = jQuery(this);
            leftPos = $el.position().left;
            newWidth = $el.width();
            $magicLine.stop().animate({
                left: leftPos,
                width: newWidth
            });
        }, function() {
            $magicLine.stop().animate({
                left: $magicLine.data("origLeft"),
                width: $magicLine.data("origWidth")
            });
        });
</code>```

into

```<code>jQuery("#menu-main-menu li").hover(function() {
            $el = jQuery(this);
            leftPos = $el.position().left + $el.children().position().left ;
            newWidth = $el.children().width();
            $magicLine.stop().animate({
                left: leftPos,
                width: newWidth
            });
        }, function() {
            $magicLine.stop().animate({
                left: $magicLine.data("origLeft"),
                width: $magicLine.data("origWidth")
            });
        });
</code>```

Body:
Hello I am using a magic line and I get it working, but the width of the magic line is taking the width of the
 element, but I want it to take the width of the  element. Can anyone help me edit the jquery code to do this?

Here is the html:

text

text text

text text text

text text text text

css:

#menu-main-menu {
  display: flex;
}

#menu-main-menu li {
  flex: 1 1 100%;
  text-align: center;
  list-style-type: none;
  position: relative;
}

#menu-main-menu li a {
  padding: 0 10px;
}

#magic-line {
    position: absolute !important;
    top: 0px;
    left: 0;
    width: 100px;
    height: 2px;
    background: #000;
    padding-top: 0 !important;
    margin-right: 0 !important;
}

jquery (sorry about the length)

jQuery(function() {

    var $el, leftPos, newWidth,
        $mainNav = jQuery("#menu-main-menu");

    $mainNav.append("

");
    var $magicLine = jQuery("#magic-line");

    if( jQuery('#menu-main-menu .current-menu-ancestor').length ) {
        var currentPageWidth = jQuery('#menu-main-menu .current-menu-ancestor > a').parent().width();
        var currentPageLeft = jQuery('#menu-main-menu .current-menu-ancestor > a').parent().position().left;
    }

    if( jQuery('#menu-main-menu .current-menu-item').length ) {
        var currentPageWidth = jQuery('#menu-main-menu .current-menu-item > a').parent().width();
        var currentPageLeft = jQuery('#menu-main-menu .current-menu-item > a').parent().position().left;
    }

    $magicLine
        .width(currentPageWidth)
        .css("left", currentPageLeft)
        .data("origLeft", $magicLine.position().left)
        .data("origWidth", $magicLine.width());

    jQuery("#menu-main-menu li").hover(function() {
        $el = jQuery(this);
        leftPos = $el.position().left;
        newWidth = $el.width();
        $magicLine.stop().animate({
            left: leftPos,
            width: newWidth
        });
    }, function() {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });

    jQuery("#menu-main-menu li .sub-menu li").hover(function() {
        $magicLine.stop()
    }, function() {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });
}, 1500);

and the jsfiddle

here

Thanks!

Body:
You should change this

jQuery("#menu-main-menu li").hover(function() {
            $el = jQuery(this);
            leftPos = $el.position().left;
            newWidth = $el.width();
            $magicLine.stop().animate({
                left: leftPos,
                width: newWidth
            });
        }, function() {
            $magicLine.stop().animate({
                left: $magicLine.data("origLeft"),
                width: $magicLine.data("origWidth")
            });
        });

into

jQuery("#menu-main-menu li").hover(function() {
            $el = jQuery(this);
            leftPos = $el.position().left + $el.children().position().left ;
            newWidth = $el.children().width();
            $magicLine.stop().animate({
                left: leftPos,
                width: newWidth
            });
        }, function() {
            $magicLine.stop().animate({
                left: $magicLine.data("origLeft"),
                width: $magicLine.data("origWidth")
            });
        });


问:
GET request to IIS returns Microsoft-HttpApi/2.0
I've got 6 identical machines running IIS and Apache. Today one of them decided to just stop serving requests. I can access all of the webapps when I try from localhost/resource but when I try from url/resource I get a 404. I did a Get request against the machine that isn't working and I get this back:

Server: Microsoft-HTTPAPI/2.0

Connection: close

Compared to a working server:

Server: Microsoft-IIS/8.5

X-Powered-By: ASP.NET

Content-Type: text/html

Tried searching for this problem but came up with nothing, anyone got any idea's?

答:
Windows has an HTTP service that manages calls to IIS and other HTTP enabled services on a windows machine. Either you need to configure it to handle your calls, or, in the case of WAMP or similar non-IIS-web-server-on-windows scenarios you may just need to turn it off.

When you see "Microsoft-HttpApi/2.0" returning error, such as 400 "bad URL" or "bad header", etc. the problem is most likely because the HTTP.sys service is intercepting your http request and terminating it because it does not meet with the minimum validation rules that are configured.

This configuration is found in the registry at HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters. In my case, it was choking because I had a RESTful call that had a 400 character segment in the url which was 160 characters more than the default value of 260, so I

added the registry parameter UrlSegmentMaxLength with a DWORD value of 512,

stopped the service using net stop http

started the service using net start http

I've run into these issues before and it is easy to troubleshoot but there is very little on the web that addresses it.

Try these links

"the underlying problem is that the client has sent a request to IIS that breaks one or more rules that HTTP.sys is enforcing"

enabling logging on HTTP.sys is described here

a list of the HTTP.sys parameters that you can control in the registry is found here.


问:
Error with create tables in sqlite3 in editor
I am creating table in my database. I am also inserting values into that table. So I am running the .py file in terminal it is not printing the inserted values. Its working in shell but with editor it doesn't ? I am writing this code to create table:

```<code>import sqlite3

conn = sqlite3.connect('raman.db')

c = conn.cursor()

c.execute("CREATE table raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")

c.execute("INSERT INTO raman VALUES(1,'H',1,'1')");

conn.commit()
</code>```

Now if i want to print those inserted values it doesn't work in editor. but with shell its working. i am writing this to print :

```<code>import sqlite3

conn = sqlite3.connect('raman.db')

c = conn.cursor()

for row in c.execute('SELECT * FROM raman'):

       conn.commit()
</code>```

答:
I see here  a few problems:

At line 1 there is no closing parenthesis.

At line 4 you are using single quotes inside the double quotes literal.

Body:
I am creating table in my database. I am also inserting values into that table. So I am running the .py file in terminal it is not printing the inserted values. Its working in shell but with editor it doesn't ? I am writing this code to create table:

import sqlite3

conn = sqlite3.connect('raman.db')

c = conn.cursor()

c.execute("CREATE table raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")

c.execute("INSERT INTO raman VALUES(1,'H',1,'1')");

conn.commit()

Now if i want to print those inserted values it doesn't work in editor. but with shell its working. i am writing this to print :

import sqlite3

conn = sqlite3.connect('raman.db')

c = conn.cursor()

for row in c.execute('SELECT * FROM raman'):

       conn.commit()


问:
Stackoverflow due to large return type of a function
this my code:

```<code>#include <iostream>
#include <array>

using namespace std;

array< array<int, 1000>, 1000 > largeThing;

array< array<int, 1000>, 1000 > functionFoo() {
    return largeThing;
}

void main(){
    functionFoo();
    return;
}
</code>```

If i run this i get a Stackoverflow error. I've got so far that the reason for this is the large return type of functionFoo(), because the return value is actually on the Heap.

Question:

How to use a function with a large return type so that all the memory that the function will put on the stack will be put on the heap instead?

Edit:

I just increased the stacksize, it worked fine.

答: By far the easiest solution is to use vector instead of array. This will use std::allocator aka "the heap".

Body:
this my code:

#include <iostream>
#include <array>

using namespace std;

array< array<int, 1000>, 1000 > largeThing;

array< array<int, 1000>, 1000 > functionFoo() {
    return largeThing;
}

void main(){
    functionFoo();
    return;
}

If i run this i get a Stackoverflow error. I've got so far that the reason for this is the large return type of functionFoo(), because the return value is actually on the Heap.

Question:

How to use a function with a large return type so that all the memory that the function will put on the stack will be put on the heap instead?

Edit:

I just increased the stacksize, it worked fine.