问:
How should you initialize constant data that needs parameters from another part of the code?
I don't think I explained my question very well in the title, so I'll do my best to do it here.

I have an abstract class called Song, a class that extends it MidiSongand then I have a SongCreator interface and a MidiSongCreatorclass that implements it. I would like to have a way to store lots of SongCreators so I can call their Create method but the problem is, since the SongCreators will each be a MidiSongCreator I am wondering how I should initialize each MidiSongCreator since it takes a MIDIPlayer and other things to help initialize it which doesn't have a static reference to it. Should I create a static class that holds lots of SongCreators? Should I not make the SongList class static?

What is looks like:

```<code>public abstract class Song{
    public IList<Playable> notes { get; private set; }

    public SongPlayData Start(){
         // calls onStartEvent
       return CreateSongData();
    }
    protected abstract SongPlayData CreateSongData();
    public bool Update(SongPlayData songData, float songTime,List<SongPlayer> players) { // note that the players list is a list of people who are playing this game (this is a rhythm game) (doesn't have anything to do with MIDIPlayer

    }
    public void End(){
       //calls end event
    }
}
public class MidiSong : Song { // this is the class that needs the MIDIPlayer parameter

    public MIDIPlayer midiPlayer;

    protected MidiSong(MIDIPlayer player){
        this.midiPlayer = player;
    }

    protected override SongPlayData CreateSongData() {
        return new MidiSongData(midiPlayer);
    }
}
public interface SongCreator<out T> where T : Song {

    T Create();

}
   public class MidiSongCreator : SongCreator<MidiSong>, IListenerObject { // this is the class that I need to store lots of instances of. the midiPlayer will probably be the same every time

    private MIDIPlayer player;

    public MidiSongCreator(MIDIPlayer player) {
        this.player = player;
        Init();
    }

    private void Init() {
        player.midiListener.listener = this;
        //
    }
    private void Clear() { // resets all the data so we can create another Song if we need to (even without entering stuff in)
        if(player.midiListener.listener == this) {
            player.midiListener.listener = null;
        }
    }

    public MidiSong Create() {

        MidiSong r = new MidiSong(player);
        // I'm still going to implement calls to other methods from midiPlayer
        Clear();
        return r;
    }

    public void OnLoad(MidiFile file) {
        // does stuff to load midi file (deals with individual events)
    }

}
public class MasterSong : MonoBehaviour { // this should initialize last btw (It's in the Script Execution Order)

    public MIDIPlayer midiPlayer;
    public Song song;
    public SongPlayData playData;

    // Use this for initialization
    void Start() {
        // this is where I'd like to reference a SongCreator and call it's create method and Start the song
        //for instance:
        song = SongList.SONG_NAME.Create();
        playData = song.Start();
    }

    void Update() {

    }
}
</code>```

It's a RhythmGame made with unity, but I didn't add the unity tag because I feel that this is more of a C#/design thing.

Also note, that I have my classes much more organized that just one file with all these.

I'm looking for ways to improve on the design that I have.

答:
This is a design problem, domain design!

I suggest don't write code yet. Create a class diagram, with pen and paper, don't need to use tools in the beginning.

Try to determine entities - classes, interfaces etc - and the relationship among them. Just use boxes and arrow, don't need to put details yet. With boxes and arrows, you will be able to have a picture of your domain much more clearly. Keep refining and changing it, still at this high level, without details, until you are satisfied.

Then, step by step, refine it by adding details/properties such attributes and methods. This may cause to change the diagram from the first step.

I intentionally did not refer to specifics of you questions like the classes and interfaces you mentioned. Since, there is not enough information to comment on that. Secondly, and more importantly, you should start at high level of design and once that is done, then do coding based on your design.

Body:
I don't think I explained my question very well in the title, so I'll do my best to do it here.

I have an abstract class called Song, a class that extends it MidiSongand then I have a SongCreator interface and a MidiSongCreatorclass that implements it. I would like to have a way to store lots of SongCreators so I can call their Create method but the problem is, since the SongCreators will each be a MidiSongCreator I am wondering how I should initialize each MidiSongCreator since it takes a MIDIPlayer and other things to help initialize it which doesn't have a static reference to it. Should I create a static class that holds lots of SongCreators? Should I not make the SongList class static?

What is looks like:

public abstract class Song{
    public IList<Playable> notes { get; private set; }

    public SongPlayData Start(){
         // calls onStartEvent
       return CreateSongData();
    }
    protected abstract SongPlayData CreateSongData();
    public bool Update(SongPlayData songData, float songTime,List<SongPlayer> players) { // note that the players list is a list of people who are playing this game (this is a rhythm game) (doesn't have anything to do with MIDIPlayer

    }
    public void End(){
       //calls end event
    }
}
public class MidiSong : Song { // this is the class that needs the MIDIPlayer parameter

    public MIDIPlayer midiPlayer;

    protected MidiSong(MIDIPlayer player){
        this.midiPlayer = player;
    }

    protected override SongPlayData CreateSongData() {
        return new MidiSongData(midiPlayer);
    }
}
public interface SongCreator<out T> where T : Song {

    T Create();

}
   public class MidiSongCreator : SongCreator<MidiSong>, IListenerObject { // this is the class that I need to store lots of instances of. the midiPlayer will probably be the same every time

    private MIDIPlayer player;

    public MidiSongCreator(MIDIPlayer player) {
        this.player = player;
        Init();
    }

    private void Init() {
        player.midiListener.listener = this;
        //
    }
    private void Clear() { // resets all the data so we can create another Song if we need to (even without entering stuff in)
        if(player.midiListener.listener == this) {
            player.midiListener.listener = null;
        }
    }

    public MidiSong Create() {

        MidiSong r = new MidiSong(player);
        // I'm still going to implement calls to other methods from midiPlayer
        Clear();
        return r;
    }

    public void OnLoad(MidiFile file) {
        // does stuff to load midi file (deals with individual events)
    }

}
public class MasterSong : MonoBehaviour { // this should initialize last btw (It's in the Script Execution Order)

    public MIDIPlayer midiPlayer;
    public Song song;
    public SongPlayData playData;

    // Use this for initialization
    void Start() {
        // this is where I'd like to reference a SongCreator and call it's create method and Start the song
        //for instance:
        song = SongList.SONG_NAME.Create();
        playData = song.Start();
    }

    void Update() {

    }
}

It's a RhythmGame made with unity, but I didn't add the unity tag because I feel that this is more of a C#/design thing.

Also note, that I have my classes much more organized that just one file with all these.

I'm looking for ways to improve on the design that I have.


来源: stackexchange

问:
How to make sure realm io user can only access certain data in a model
I'm still learning how to implement realm.io in my next project. I'm really amazed in the Realm Mobile Platform (offline-sync).

I'm reading https://realm.io/docs/realm-object-server/#access-control but what I need is preventing user accessing certain data in a model. (let's say they only can access data only their own data).

Thank You

答:
In addition to the Realm documentation. There are a couple overviews on Multi-Realm setups you could check out. They go over permissions and database design.

https://realm.io/docs/tech-notes/multi-realm-cheatsheet/

https://realm.io/docs/tech-notes/teamwork/

ContentLicense: CC BY-SA 3.0


问:
Drawing 30fps chart in Windows Forms
I'd like to draw a high-framerate (30fps+) graph/chart in a Windows Forms app.

How?

Windows Forms gets TERRIBLE frame rates drawing a clear-background drawing over a window.

(I come from the land of GNU, so I apologize if this is obvious.)

答: Running full tilt I get about 180FPS using a System::Windows::Forms::DataVisualization::Charting::Chart plotting 128bins of an FFT using a 'FastLine' style for the series of data. That's running on an Intel Core 2 Duo (2.53Ghz) IBM Thinkpad.</p>

ContentLicense: CC BY-SA 2.5

Title: Drawing 30fps chart in Windows Forms


问:
R: Extract columns from list of data.frames in a tibble
I am wondering how to manipulate a list containing data.frames stored in a tibble.

Specifically, I would like to extract two columns from a data.frame that are stored in a tibble list column.

I would like to go from this tibble c

```<code>random_data<-list(a=letters[1:10],b=LETTERS[1:10])
x<-as.data.frame(random_data, stringsAsFactors=FALSE)
y<-list()
y[[1]]<-x[1,,drop=FALSE]
y[[3]]<-x[2,,drop=FALSE]
c<-tibble(z=c(1,2,3),my_data=y)
</code>```

to this tibble d

```<code>d<-tibble(z=c(1,2,3),a=c('a',NA,'b'),b=c('A',NA,'B'))
</code>```

thanks

Iain

答:
c2 is the final output.

```<code>library(tidyverse)

c2 <- c %>%
  filter(!map_lgl(my_data, is.null)) %>%
  unnest() %>%
  right_join(c, by = "z") %>%
  select(-my_data)
</code>```

Body:
I am wondering how to manipulate a list containing data.frames stored in a tibble.

Specifically, I would like to extract two columns from a data.frame that are stored in a tibble list column.

I would like to go from this tibble c

random_data<-list(a=letters[1:10],b=LETTERS[1:10])
x<-as.data.frame(random_data, stringsAsFactors=FALSE)
y<-list()
y[[1]]<-x[1,,drop=FALSE]
y[[3]]<-x[2,,drop=FALSE]
c<-tibble(z=c(1,2,3),my_data=y)

to this tibble d

d<-tibble(z=c(1,2,3),a=c('a',NA,'b'),b=c('A',NA,'B'))

thanks

Iain

Body:
c2 is the final output.

library(tidyverse)

c2 <- c %>%
  filter(!map_lgl(my_data, is.null)) %>%
  unnest() %>%
  right_join(c, by = "z") %>%
  select(-my_data)


问:
select query to display result and the parameter that got the result when using OR clause in where (Oracle)
I have a query

```<code>select columnX from tableA
  where (columnY like '%string1%' or columnY like '%string2%');
</code>```

but I also want to know what parameter (string1 or string2) got matched because of which I got my result, so I modify my query to

```<code>  select columnX value,'string1' pattern from tableA
  where columnY like '%string1%'
  union
  select columnX,'string2' from tableA
  where columnY like '%string2%'
</code>```

This gives me my result but makes the query huge (as I have hundreds of patterns to match against so basically I write the entire query for each parameter), I highly doubt this would be the best way to do this, is there some other way to do this where I do not have to write a new query for all the patterns that I want to match ?
Can this be done by simply modifying the query or will I have to use any advanced construct of Oracle SQL to perform what I need ?

答:
Don't forget the requirement that there are hundreds of patterns to match.  The solutions using case statements are then impractical I'm afraid as you would have to edit hundreds of those.  Put the compare strings in a table.  Here I simulate that by using a CTE (the compare_strings table).  If you ever need to add a value to compare to, you just add it to the compare_strings table and the query does not have to change.  To simulate, edit the 'efs' to be 'blah' and you will then pick up row 1.

There is a caveat though, as per your example the compare string will match anywhere it appears in columnY, even if the string is embedded within another word that may not be what you want to match on.  To get more precise, you may need to switch to using regexp_like where you can tailor the regex to meet your needs.

```<code>SQL> WITH tableA(columnX, columnY) AS (
     SELECT 1, 'blah blah blah'  FROM DUAL UNION
     SELECT 2, 'string2'         FROM DUAL UNION
     SELECT 3, 'string'          FROM DUAL UNION
     SELECT 4, 'string1'         FROM DUAL UNION
     SELECT 5, 'string1 string2' FROM DUAL UNION
     SELECT 6, NULL              FROM DUAL UNION
     SELECT 7, 'string3'         FROM DUAL
   ),
   COMPARE_STRINGS(description) AS (
     SELECT 'string1'    FROM DUAL UNION
     SELECT 'efs'        FROM DUAL UNION
     SELECT 'string2'    FROM DUAL UNION
     SELECT 'Mata Hairy' FROM DUAL UNION
     SELECT 'string3'    FROM DUAL
   )
   SELECT columnX, cs.description "hit string"
   FROM TABLEA A CROSS JOIN COMPARE_STRINGS CS
   WHERE a.columnY LIKE '%' || cs.description || '%'
   ORDER BY columnX;

   COLUMNX hit string
---------- ----------
         2 string2
         4 string1
         5 string1
         5 string2
         7 string3
</code>```

Note you get 2 hits in line 5 as columnY contains 2 entries from the compare_strings table.  You'll need to decide how you want to handle that.  See the caveat above.

EDIT 7/10/17 to put multiple hit strings per row on a single line.

Alter the query to use LISTAGG():

```<code>   SELECT columnX,
   LISTAGG(cs.description, '|') WITHIN GROUP (ORDER BY columnX) hit_string
   FROM TABLEA A CROSS JOIN COMPARE_STRINGS CS
   WHERE a.columnY LIKE '%' || cs.description || '%'
   GROUP BY columnX;

SQL> /

   COLUMNX HIT_STRING
---------- --------------------
         2 string2
         4 string1
         5 string1|string2
         7 string3
</code>```

Body:
I have a query

select columnX from tableA
  where (columnY like '%string1%' or columnY like '%string2%');

but I also want to know what parameter (string1 or string2) got matched because of which I got my result, so I modify my query to

  select columnX value,'string1' pattern from tableA
  where columnY like '%string1%'
  union
  select columnX,'string2' from tableA
  where columnY like '%string2%'

This gives me my result but makes the query huge (as I have hundreds of patterns to match against so basically I write the entire query for each parameter), I highly doubt this would be the best way to do this, is there some other way to do this where I do not have to write a new query for all the patterns that I want to match ?
Can this be done by simply modifying the query or will I have to use any advanced construct of Oracle SQL to perform what I need ?

Body:
Don't forget the requirement that there are hundreds of patterns to match.  The solutions using case statements are then impractical I'm afraid as you would have to edit hundreds of those.  Put the compare strings in a table.  Here I simulate that by using a CTE (the compare_strings table).  If you ever need to add a value to compare to, you just add it to the compare_strings table and the query does not have to change.  To simulate, edit the 'efs' to be 'blah' and you will then pick up row 1.

There is a caveat though, as per your example the compare string will match anywhere it appears in columnY, even if the string is embedded within another word that may not be what you want to match on.  To get more precise, you may need to switch to using regexp_like where you can tailor the regex to meet your needs.

SQL> WITH tableA(columnX, columnY) AS (
     SELECT 1, 'blah blah blah'  FROM DUAL UNION
     SELECT 2, 'string2'         FROM DUAL UNION
     SELECT 3, 'string'          FROM DUAL UNION
     SELECT 4, 'string1'         FROM DUAL UNION
     SELECT 5, 'string1 string2' FROM DUAL UNION
     SELECT 6, NULL              FROM DUAL UNION
     SELECT 7, 'string3'         FROM DUAL
   ),
   COMPARE_STRINGS(description) AS (
     SELECT 'string1'    FROM DUAL UNION
     SELECT 'efs'        FROM DUAL UNION
     SELECT 'string2'    FROM DUAL UNION
     SELECT 'Mata Hairy' FROM DUAL UNION
     SELECT 'string3'    FROM DUAL
   )
   SELECT columnX, cs.description "hit string"
   FROM TABLEA A CROSS JOIN COMPARE_STRINGS CS
   WHERE a.columnY LIKE '%' || cs.description || '%'
   ORDER BY columnX;

   COLUMNX hit string
---------- ----------
         2 string2
         4 string1
         5 string1
         5 string2
         7 string3

Note you get 2 hits in line 5 as columnY contains 2 entries from the compare_strings table.  You'll need to decide how you want to handle that.  See the caveat above.

EDIT 7/10/17 to put multiple hit strings per row on a single line.

Alter the query to use LISTAGG():

   SELECT columnX,
   LISTAGG(cs.description, '|') WITHIN GROUP (ORDER BY columnX) hit_string
   FROM TABLEA A CROSS JOIN COMPARE_STRINGS CS
   WHERE a.columnY LIKE '%' || cs.description || '%'
   GROUP BY columnX;

SQL> /

   COLUMNX HIT_STRING
---------- --------------------
         2 string2
         4 string1
         5 string1|string2
         7 string3


问:
Full address is not showing in the response
I want full selected address when the user selects any address from the address book.

Following is the response what I got when "getOrderReferenceDetails" is executed.

```<code>{
"GetOrderReferenceDetailsResult": {
    "OrderReferenceDetails": {
        "OrderReferenceStatus": {
            "State": "Draft"
        },
        "Destination": {
            "DestinationType": "Physical",
            "PhysicalDestination": {
                "StateOrRegion": "IA",
                "City": "CLEAR LAKE",
                "CountryCode": "US",
                "PostalCode": "50428"
            }
        },
        "ExpirationTimestamp": "2018-01-01T12:51:02.920Z",
        "IdList": {

        },
        "SellerOrderAttributes": {
            "StoreName": "TEST1234"
        },
        "OrderTotal": {
            "CurrencyCode": "USD",
            "Amount": "253.98"
        },
        "ReleaseEnvironment": "Sandbox",
        "SellerNote": "LEED Green Associate Exam Prep Online Anytime",
        "AmazonOrderReferenceId": "S01-2494539-9324741",
        "CreationTimestamp": "2017-07-05T12:51:02.920Z",
        "RequestPaymentAuthorization": "false"
    }
},
"ResponseMetadata": {
    "RequestId": "ffa51eb9-a31a-48d2-a2a5-b37126eba592"
},
"ResponseStatus": "200"
</code>```

}

答:
In order to retrieve the entire shipping address prior to confirming an order, you need to take the following steps:

Ensure the "payments:shipping_address" scope is requested in your Amazon Pay button code

Capture the Access Token during the login process (this can be found appended to the return URL, or retrieved using Login with Amazon JS SDK)

Pass the Access Token in to the GetOrderReferenceDetails API call via the AddressConsentToken field

If the above three actions are taken, you'll receive the full shipping address while the order is still in draft state. Below is an example response. Note it now contains the AddressLine1, Name and Phone fields.

```<code><?xml version="1.0" ?>
<GetOrderReferenceDetailsResponse xmlns="http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01">
  <GetOrderReferenceDetailsResult>
    <OrderReferenceDetails>
      <AmazonOrderReferenceId>P01-7416549-1234567</AmazonOrderReferenceId>
      <ExpirationTimestamp>2015-07-09T00:54:54.828Z</ExpirationTimestamp>
      <Constraints>
        <Constraint>
          <ConstraintID>AmountNotSet</ConstraintID>
          <Description>The seller has not set the amount for the Order Reference.</Description>
        </Constraint>
      </Constraints>
      <IdList/>
      <OrderReferenceStatus>
        <State>Draft</State>
      </OrderReferenceStatus>
      <Destination>
        <DestinationType>Physical</DestinationType>
        <PhysicalDestination>
          <Phone>2061112222</Phone>
          <PostalCode>98100-2000</PostalCode>
          <Name>John Doe</Name>
          <CountryCode>US</CountryCode>
          <StateOrRegion>WA</StateOrRegion>
          <AddressLine1>100 SEATTLE ST</AddressLine1>
          <City>SEATTLE</City>
        </PhysicalDestination>
      </Destination>
      <ReleaseEnvironment>Live</ReleaseEnvironment>
      <Buyer>
        <Email>john.doe@abc.com</Email>
        <Name>John Doe</Name>
      </Buyer>
      <SellerOrderAttributes/>
      <CreationTimestamp>2015-01-10T00:54:54.828Z</CreationTimestamp>
    </OrderReferenceDetails>
  </GetOrderReferenceDetailsResult>
  <ResponseMetadata>
    <RequestId>e1de6c1f-64fd-48ec-9a69-a34646464</RequestId>
  </ResponseMetadata>
</GetOrderReferenceDetailsResponse>
</code>```

Body:
I want full selected address when the user selects any address from the address book.

Following is the response what I got when "getOrderReferenceDetails" is executed.

{
"GetOrderReferenceDetailsResult": {
    "OrderReferenceDetails": {
        "OrderReferenceStatus": {
            "State": "Draft"
        },
        "Destination": {
            "DestinationType": "Physical",
            "PhysicalDestination": {
                "StateOrRegion": "IA",
                "City": "CLEAR LAKE",
                "CountryCode": "US",
                "PostalCode": "50428"
            }
        },
        "ExpirationTimestamp": "2018-01-01T12:51:02.920Z",
        "IdList": {

        },
        "SellerOrderAttributes": {
            "StoreName": "TEST1234"
        },
        "OrderTotal": {
            "CurrencyCode": "USD",
            "Amount": "253.98"
        },
        "ReleaseEnvironment": "Sandbox",
        "SellerNote": "LEED Green Associate Exam Prep Online Anytime",
        "AmazonOrderReferenceId": "S01-2494539-9324741",
        "CreationTimestamp": "2017-07-05T12:51:02.920Z",
        "RequestPaymentAuthorization": "false"
    }
},
"ResponseMetadata": {
    "RequestId": "ffa51eb9-a31a-48d2-a2a5-b37126eba592"
},
"ResponseStatus": "200"

}

Body:
In order to retrieve the entire shipping address prior to confirming an order, you need to take the following steps:

Ensure the "payments:shipping_address" scope is requested in your Amazon Pay button code

Capture the Access Token during the login process (this can be found appended to the return URL, or retrieved using Login with Amazon JS SDK)

Pass the Access Token in to the GetOrderReferenceDetails API call via the AddressConsentToken field

If the above three actions are taken, you'll receive the full shipping address while the order is still in draft state. Below is an example response. Note it now contains the AddressLine1, Name and Phone fields.

<?xml version="1.0" ?>
<GetOrderReferenceDetailsResponse xmlns="http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01">
  <GetOrderReferenceDetailsResult>
    <OrderReferenceDetails>
      <AmazonOrderReferenceId>P01-7416549-1234567</AmazonOrderReferenceId>
      <ExpirationTimestamp>2015-07-09T00:54:54.828Z</ExpirationTimestamp>
      <Constraints>
        <Constraint>
          <ConstraintID>AmountNotSet</ConstraintID>
          <Description>The seller has not set the amount for the Order Reference.</Description>
        </Constraint>
      </Constraints>
      <IdList/>
      <OrderReferenceStatus>
        <State>Draft</State>
      </OrderReferenceStatus>
      <Destination>
        <DestinationType>Physical</DestinationType>
        <PhysicalDestination>
          <Phone>2061112222</Phone>
          <PostalCode>98100-2000</PostalCode>
          <Name>John Doe</Name>
          <CountryCode>US</CountryCode>
          <StateOrRegion>WA</StateOrRegion>
          <AddressLine1>100 SEATTLE ST</AddressLine1>
          <City>SEATTLE</City>
        </PhysicalDestination>
      </Destination>
      <ReleaseEnvironment>Live</ReleaseEnvironment>
      <Buyer>
        <Email>john.doe@abc.com</Email>
        <Name>John Doe</Name>
      </Buyer>
      <SellerOrderAttributes/>
      <CreationTimestamp>2015-01-10T00:54:54.828Z</CreationTimestamp>
    </OrderReferenceDetails>
  </GetOrderReferenceDetailsResult>
  <ResponseMetadata>
    <RequestId>e1de6c1f-64fd-48ec-9a69-a34646464</RequestId>
  </ResponseMetadata>
</GetOrderReferenceDetailsResponse>


问:
Uncaught RangeError Maximum call stack size exceeded in React App
I'm learning React and for training, I want to create a basic Todo app. For the first step, I want to create a component called AddTodo that renders an input field and a button and every time I enter something in the input field and press the button, I want to pass the value of the input field to another component called TodoList and append it to the list.

The problem is when I launch the app, the AddTodo component renders successfully but when I enter something and press the button, the app stops responding for 2 seconds and after that, I get this: Uncaught RangeError: Maximum call stack size exceeded and nothing happens.

My app source code: Main.jsx

```<code>import React, {Component} from 'react';
import TodoList from 'TodoList';
import AddTodo from 'AddTodo';

class Main extends Component {
    constructor(props) {
        super(props);
        this.setNewTodo = this.setNewTodo.bind(this);
        this.state = {
            newTodo: ''
        };
    }
    setNewTodo(todo) {
        this.setState({
            newTodo: todo
        });
    }
    render() {
        var {newTodo} = this.state;
        return (
            <div>
                <TodoList addToList={newTodo} />
                <AddTodo setTodo={this.setNewTodo}/>
            </div>
        );
    }
}
export default Main;
</code>```

AddTodo.jsx

```<code>import React, {Component} from 'react';

class AddTodo extends Component {
    constructor(props) {
        super(props);
        this.handleNewTodo = this.handleNewTodo.bind(this);
    }
    handleNewTodo() {
        var todo = this.refs.todo.value;
        this.refs.todo.value = '';
        if (todo) {
            this.props.setTodo(todo);
        }
    }
    render() {
        return (
            <div>
                <input type="text" ref="todo" />
                <button onClick={this.handleNewTodo}>Add to Todo List</button>
            </div>
        );
    }
}
AddTodo.propTypes = {
    setTodo: React.PropTypes.func.isRequired
};
export default AddTodo;
</code>```

TodoList.jsx

```<code>import React, {Component} from 'react';

class TodoList extends Component {
    constructor(props) {
        super(props);
        this.renderItems = this.renderItems.bind(this);
        this.state = {
            todos: []
        };
    }
    componentDidUpdate() {
        var newTodo = this.props.addToList;
        var todos = this.state.todos;
        todos = todos.concat(newTodo);
        this.setState({
            todos: todos
        });
    }
    renderItems() {
        var todos = this.state.todos;
        todos.map((item) => {
            <h4>{item}</h4>
        });
    }
    render() {
        return (
            <div>
                {this.renderItems()}
            </div>
        );
    }
}
export default TodoList;
</code>```

答:
First time componentDidUpdate is called (which happens after first change in its props/state, which in your case happens after adding first todo) it adds this.props.addToList to this.state.todo and updates state. Updating state will run componentDidUpdate again and it adds the value of this.props.addToList to 'this.state.todo` again and it goes infinitely.

You can fix it with some dirty hacks but your approach is a bad approach overall. Right thing to do is to keep todos in parent component (Main), append the new todo to it in setNewTodo (you may probably rename it to addTodo) and pass the todos list from Main state to TodoList: <TodoList todos={this.state.todos}/> for example.

Body:
I'm learning React and for training, I want to create a basic Todo app. For the first step, I want to create a component called AddTodo that renders an input field and a button and every time I enter something in the input field and press the button, I want to pass the value of the input field to another component called TodoList and append it to the list.

The problem is when I launch the app, the AddTodo component renders successfully but when I enter something and press the button, the app stops responding for 2 seconds and after that, I get this: Uncaught RangeError: Maximum call stack size exceeded and nothing happens.

My app source code: Main.jsx

import React, {Component} from 'react';
import TodoList from 'TodoList';
import AddTodo from 'AddTodo';

class Main extends Component {
    constructor(props) {
        super(props);
        this.setNewTodo = this.setNewTodo.bind(this);
        this.state = {
            newTodo: ''
        };
    }
    setNewTodo(todo) {
        this.setState({
            newTodo: todo
        });
    }
    render() {
        var {newTodo} = this.state;
        return (

                <TodoList addToList={newTodo} />
                <AddTodo setTodo={this.setNewTodo}/>

        );
    }
}
export default Main;

AddTodo.jsx

import React, {Component} from 'react';

class AddTodo extends Component {
    constructor(props) {
        super(props);
        this.handleNewTodo = this.handleNewTodo.bind(this);
    }
    handleNewTodo() {
        var todo = this.refs.todo.value;
        this.refs.todo.value = '';
        if (todo) {
            this.props.setTodo(todo);
        }
    }
    render() {
        return (

                <input type="text" ref="todo" />
                <button onClick={this.handleNewTodo}>Add to Todo List</button>

        );
    }
}
AddTodo.propTypes = {
    setTodo: React.PropTypes.func.isRequired
};
export default AddTodo;

TodoList.jsx

import React, {Component} from 'react';

class TodoList extends Component {
    constructor(props) {
        super(props);
        this.renderItems = this.renderItems.bind(this);
        this.state = {
            todos: []
        };
    }
    componentDidUpdate() {
        var newTodo = this.props.addToList;
        var todos = this.state.todos;
        todos = todos.concat(newTodo);
        this.setState({
            todos: todos
        });
    }
    renderItems() {
        var todos = this.state.todos;
        todos.map((item) => {

{item}

        });
    }
    render() {
        return (

                {this.renderItems()}

        );
    }
}
export default TodoList;


问:
getting message: forbidden reply from AWS API gateway
I am trying to create a lambda service on AWS and have it accessed from outside via the API gateway with no authentication or restriction required.

To make things easy I set the gateway for now to be a Mock.

On the Get method of the API, the Authorization is set to None and the API Key is not required.

When I try this, I get {"message":"Forbidden"}
(same message if I connect it to the actual lambda service).

Any advice on how to make it accessible?

答: On the API Gateway dashboard choose Resources, click Actions and choose Deploy API. Before your first deployment the only response you'll get is the {"message":"Forbidden"}.

ContentLicense: CC BY-SA 4.0


问:
compare 2 strings, subtract the same characters and return the new values
i have two strings, it can be more then two may be 5 or 6

```<code> $a =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123
 $b =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000
</code>```

i need help i need a function or any way that when i compare $a with $b it should only returns me string like below

```<code>$remaining = '2015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000';
</code>```

i tried this function with no luck if (strcmp($var1, $var2) === 0) {

答:
An alternative approach here would be to skip the matched content.

```<code>$a =  '2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123';
$b =  '2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000';
if(strpos($b, $a) !== false) {
    echo substr($b, (strrpos($b, $a) + strlen($a)));
}
</code>```

would work. If you have multiple matches though you will need a different approach (because this is only for 1 iteration). The str_replace is probably your best approach.

Demo: https://eval.in/829490

Body:
i have two strings, it can be more then two may be 5 or 6

 $a =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123
 $b =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000

i need help i need a function or any way that when i compare $a with $b it should only returns me string like below

$remaining = '2015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000';

i tried this function with no luck if (strcmp($var1, $var2) === 0) {

Body:
An alternative approach here would be to skip the matched content.

$a =  '2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123';
$b =  '2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000';
if(strpos($b, $a) !== false) {
    echo substr($b, (strrpos($b, $a) + strlen($a)));
}

would work. If you have multiple matches though you will need a different approach (because this is only for 1 iteration). The str_replace is probably your best approach.

Demo: https://eval.in/829490


问:
XInclude not working with Saxon?
I have this XSLT stylesheet xinclude-test.xsl:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xi="http://www.w3.org/2001/XInclude">
  <xsl:output method="text"/>
  <xi:include href="xinclude-test-included.xml"/>

  <!-- <xsl:param name="test"> -->
  <!--   aaa -->
  <!-- </xsl:param> -->

  <xsl:template name="main">
    <xsl:value-of select="$test"/>
  </xsl:template>
</xsl:stylesheet>
</code>```

The included file xinclude-test-included.xml is

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:param name="test" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
aaa
</xsl:param>
</code>```

When I evaluate the stylesheet with

```<code>saxon -xi -xsl:xinclude-test.xsl -it:main -t
</code>```

It prints

```<code>Saxon-HE 9.8.0.1J from Saxonica
Java version 1.8.0_31
Static error at char 5 in xsl:value-of/@select on line 13 column 35 of xinclude-test.xsl:
  XPST0008: Variable test has not been declared (or its declaration is not in scope)
Errors were reported during stylesheet compilation
</code>```

where I expect it to print "aaa".

However if I use another stylesheet to load the first XSLT:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="2.0">
  <xsl:template name="main">
    <xsl:copy-of select="document('xinclude-test.xsl')"/>
  </xsl:template>
</xsl:stylesheet>
</code>```

it correctly does the XInclude processing.

So what did I do wrong in my first XSLT?

答:
I'm sure you'll get an answer or comments about Saxon in particular, but as a more general answer to your question,

So what did I do wrong in my first XSLT?

I'll observe that XSLT 2.0 does not contain any provision requiring processors to perform XInclude processing on the stylesheet document.  Inasmuch as the spec defines the form and semantics of stylesheet documents, I'm inclined to take that omission as an indication that processors should not perform XInclude processing on the stylesheet document.  Whether the document() function performs XInclude processing is not specified either, but I don't take that as indicative in the same way.

For better or for worse, XSLT has its own mechanism for including external stylesheet fragments.  The semantics are a bit different from XInclude: xsl:include and xsl:import are used to bring in external stylesheet modules, not arbitrary XML fragments.

Title: XInclude not working with Saxon?

Body:
I have this XSLT stylesheet xinclude-test.xsl:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xi="http://www.w3.org/2001/XInclude">
  <xsl:output method="text"/>
  <xi:include href="xinclude-test-included.xml"/>

  <xsl:template name="main">
    <xsl:value-of select="$test"/>
  </xsl:template>
</xsl:stylesheet>

The included file xinclude-test-included.xml is

<?xml version="1.0" encoding="utf-8"?>
<xsl:param name="test" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
aaa
</xsl:param>

When I evaluate the stylesheet with

saxon -xi -xsl:xinclude-test.xsl -it:main -t

It prints

Saxon-HE 9.8.0.1J from Saxonica
Java version 1.8.0_31
Static error at char 5 in xsl:value-of/@select on line 13 column 35 of xinclude-test.xsl:
  XPST0008: Variable test has not been declared (or its declaration is not in scope)
Errors were reported during stylesheet compilation

where I expect it to print "aaa".

However if I use another stylesheet to load the first XSLT:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="2.0">
  <xsl:template name="main">
    <xsl:copy-of select="document('xinclude-test.xsl')"/>
  </xsl:template>
</xsl:stylesheet>

it correctly does the XInclude processing.

So what did I do wrong in my first XSLT?


问:
Cascading Style Sheets (CSS) - Creating Posts above the image in a scroll
I want to ask how to display the text above the image and the file is located inside a scrollbar like the picture below.
I've searched on google and used position but it did not work. I hope you can help me to find a solution.

Pictures and texts contained in scroll

答:
First of all you have to create a block with picture and a text.

Give your block position: relative and your text position: absolute.

What about scrollbar - it means that you have a container where all your photos are, but it is small, so you use overflow: scroll.

see here code example: https://codepen.io/alex_ukr/pen/QgVzeL

body {
  background-color: lightblue;
}

.main-container {
  width: 450px;
  height: 300px;
  overflow-y: scroll;
  border: 5px solid red;
  background-color: white;
}
.picture-container {
  display: inline-block;
  width: 200px;
  height: 200px;
  position: relative;
}

img {

  width: 200px;
  height: 200px;
}

span {
  position: absolute;
  top: 10px;
  font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-container">
  <div class="picture-container">
    <img src="https://uploads.scratch.mit.edu/users/avatars/1385/1878.png" alt="">
    <span>your text</span>
  </div>
  <div class="picture-container">
    <img src="https://uploads.scratch.mit.edu/users/avatars/1385/1878.png" alt="">
    <span>your text</span>
  </div>
  <div class="picture-container">
    <img src="https://uploads.scratch.mit.edu/users/avatars/1385/1878.png" alt="">
    <span>your text</span>
  </div>
  <div class="picture-container">
    <img src="https://uploads.scratch.mit.edu/users/avatars/1385/1878.png" alt="">
    <span>your text</span>
  </div>
</div></code>```

Body:
First of all you have to create a block with picture and a text.

Give your block position: relative and your text position: absolute.

What about scrollbar - it means that you have a container where all your photos are, but it is small, so you use overflow: scroll.

see here code example: https://codepen.io/alex_ukr/pen/QgVzeL

body {
  background-color: lightblue;
}

.main-container {
  width: 450px;
  height: 300px;
  overflow-y: scroll;
  border: 5px solid red;
  background-color: white;
}
.picture-container {
  display: inline-block;
  width: 200px;
  height: 200px;
  position: relative;
}

img {

  width: 200px;
  height: 200px;
}

span {
  position: absolute;
  top: 10px;
  font-size: 20px;
}

<div class="main-container">
  <div class="picture-container">
    <img src="https://uploads.scratch.mit.edu/users/avatars/1385/1878.png" alt="">
    <span>your text</span>
  </div>
  <div class="picture-container">
    <img src="https://uploads.scratch.mit.edu/users/avatars/1385/1878.png" alt="">
    <span>your text</span>
  </div>
  <div class="picture-container">
    <img src="https://uploads.scratch.mit.edu/users/avatars/1385/1878.png" alt="">
    <span>your text</span>
  </div>
  <div class="picture-container">
    <img src="https://uploads.scratch.mit.edu/users/avatars/1385/1878.png" alt="">
    <span>your text</span>
  </div>
</div>


问:
wordpress cannot access admin section and website as theme does not exist
I am facing two challenges on this site as I was uploading a photo, it ended up crashing or something.

The website URL is chandariaproperties.com. The front end is showing the below. I removed the plugins, reset .htaccess. flushed my cookies.

The wp-admin is showing as below

I tried changing the site URL and also .htaccess still no nope. I really no other other idea on how to go about it now

答:
If it is a case of the activated theme not existing then you can change it in the database.

You need to change the three rows in the options table that have the following value in the option_name field.

template – the “Theme Name” as defined in style.css

current_theme - the name of your theme folder

stylesheet – the name of your theme folder


问:
Masstransit+ RabbitMQ. Share one queue among two different message types
I have a publisher, which publishes messages to rabbitmq://localhost/test123 queue. One message has TestMessage type, the other TestMessage2 type.

Publisher config:

```<code> sbc.UseRabbitMq(r => r.ConfigureHost(new MessageUrn("rabbitmq://localhost/test123"), c => { }));
 sbc.UseLog4Net();
 sbc.UseJsonSerializer();
 sbc.EnableMessageTracing();
 sbc.ReceiveFrom(new MessageUrn("rabbitmq://localhost/test123"));
</code>```

I have two seprate consumers per message type (2 consumers), consumer 1:

```<code>  //config stuff
  sbc.ReceiveFrom("rabbitmq://localhost/test678?prefetch=20");
  sbc.Subscribe(subs => { subs.Handler<TestMessage>(msg => { Logger.Info(msg.Text); }); });
</code>```

consumer 2:

```<code> //config stuff
 sbc.ReceiveFrom("rabbitmq://localhost/test678");
            sbc.Subscribe(
                subs =>
                {
                    subs.Handler<TestMessage2>(
                        msg => { Logger.Info(String.Format("rcv:txt= {0}, number= {1}", msg.Text, msg.Number)); });
                });
</code>```

So when I stop publisher and run one of the consumers, he consumes all messages of his type and move other to error queue. Exchange for test678 has bindings for both types.

Is it normal behavior that 2 different consumers will try to read their message while moving other messages to error queue? Why I can't share one queue among different consumers with different interested types?

(I believe it is not masstransit issue, rather rabbitmq design considerations or limitation)

Thanks in advance.

答: If you have more than one service bus instance receiving from the same queue, you need to ensure that the consumers registered on that service bus instance are the same. Otherwise, messages consumed by the service will be moved to the _error queue for message type which have no consumer on that service instance.</p>

Body:
I have a publisher, which publishes messages to rabbitmq://localhost/test123 queue. One message has TestMessage type, the other TestMessage2 type.

Publisher config:

 sbc.UseRabbitMq(r => r.ConfigureHost(new MessageUrn("rabbitmq://localhost/test123"), c => { }));
 sbc.UseLog4Net();
 sbc.UseJsonSerializer();
 sbc.EnableMessageTracing();
 sbc.ReceiveFrom(new MessageUrn("rabbitmq://localhost/test123"));

I have two seprate consumers per message type (2 consumers), consumer 1:

  //config stuff
  sbc.ReceiveFrom("rabbitmq://localhost/test678?prefetch=20");
  sbc.Subscribe(subs => { subs.Handler<TestMessage>(msg => { Logger.Info(msg.Text); }); });

consumer 2:

 //config stuff
 sbc.ReceiveFrom("rabbitmq://localhost/test678");
            sbc.Subscribe(
                subs =>
                {
                    subs.Handler<TestMessage2>(
                        msg => { Logger.Info(String.Format("rcv:txt= {0}, number= {1}", msg.Text, msg.Number)); });
                });

So when I stop publisher and run one of the consumers, he consumes all messages of his type and move other to error queue. Exchange for test678 has bindings for both types.

Is it normal behavior that 2 different consumers will try to read their message while moving other messages to error queue? Why I can't share one queue among different consumers with different interested types?

(I believe it is not masstransit issue, rather rabbitmq design considerations or limitation)

Thanks in advance.


答:
I think this does the trick with d the requested tibble:

```<code>library(dplyr)

new.y <- lapply(y, function(x) if(is.null(x)) data.frame(a = NA, b = NA) else x)
d <- cbind(z = c(1, 2, 3), bind_rows(new.y)) %>% tbl_df()

# # A tibble: 3 x 3
#     z      a      b
#  <dbl> <fctr> <fctr>
# 1   1      a      A
# 2   2     NA     NA
# 3   3      b      B
</code>```

Title: R: Extract columns from list of data.frames in a tibble

Body:
I think this does the trick with d the requested tibble:

library(dplyr)

new.y <- lapply(y, function(x) if(is.null(x)) data.frame(a = NA, b = NA) else x)
d <- cbind(z = c(1, 2, 3), bind_rows(new.y)) %>% tbl_df()

# # A tibble: 3 x 3
#     z      a      b
#  <dbl> <fctr> <fctr>
# 1   1      a      A
# 2   2     NA     NA
# 3   3      b      B


问:
XCode fails to run app on device, saying the program being debugged is not being run
I'm running Xcode, trying to get my app to run on my iphone. I'm getting the error message "the program being debugged is not being run."</p>

答: You should check which certificate you ase using, remember to use developer provision for debug on you device and ensure all configuration is done.</p>


问:
yum install mongodb 3.2 fails
I am trying to install mongodb 3.2 on a CentOS 7 machine and facing issues in locating the packages.

I have updated the repo file as per the documentation:

```<code>[mongodb-org-3.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/
gpgcheck=0
enabled=1
</code>```

When running sudo yum install mongodb-org I am getting this error:

```<code>[centos@ip-10-24-1-228 ~]$ sudo yum install mongodb-org
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: ftp.osuosl.org
 * epel: linux.mirrors.es.net
 * extras: mirror.lax.hugeserver.com
 * updates: mirror.hmc.edu
No package mongodb-org available.
Error: Nothing to do
</code>```

Why do I get this message?

答:
Create a mongodb-org.repo file
    sudo vi /etc/yum.repos.d/mongodb-org.repo

```<code>Add following content
[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-
org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc
Then execute sudo yum install mongodb-org
</code>```

Reference:docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/

Title: yum install mongodb 3.2 fails

Body:
I am trying to install mongodb 3.2 on a CentOS 7 machine and facing issues in locating the packages.

I have updated the repo file as per the documentation:

[mongodb-org-3.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/
gpgcheck=0
enabled=1

When running sudo yum install mongodb-org I am getting this error:

[centos@ip-10-24-1-228 ~]$ sudo yum install mongodb-org
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: ftp.osuosl.org
 * epel: linux.mirrors.es.net
 * extras: mirror.lax.hugeserver.com
 * updates: mirror.hmc.edu
No package mongodb-org available.
Error: Nothing to do

Why do I get this message?

Body:
Create a mongodb-org.repo file
    sudo vi /etc/yum.repos.d/mongodb-org.repo

Add following content
[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-
org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc
Then execute sudo yum install mongodb-org

Reference:docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/


问:
Proper way to include new font and reference it?
In the ReactQL file structure, is there a recommended place to store a custom font, and how would you reference that font?

For example, I've tried adding the font into ./static, and referencing it in styles.global.css, but no such luck.

Any recommendations?

答:
You can reference fonts (or images) in three ways:

1. From within your JS code

You can import a font/img just like any other code, using ES6 module syntax:

// imports will start looking in your project root
image someFont from 'src/fonts/whatever.ttf'; // someFont = public path to font
```

<p>In this case, <code>someFont</code> will equal a string of the font file path that's processed by Webpack, and dumped in the resulting <code>dist</code> folder. That's done for you automatically; you don't need to put the fonts or images anywhere special.</p>

<p>You can then reference this in your React components wherever you'd normally need the full file path; the string will be publicly accessible from the ReactQL web server:</p>

<pre class="lang-js prettyprint-override"><code>// The regular, pre-processed PNG image
import logoImage from 'src/images/logo.png';

// A component that uses the image
const ShowLogo = () => (
   <img src={logoImage} />
);
</code>```

In this case, logoImage might wind up as /assets/img/logo.d41d8cd98f00b204e980.png after Webpack has processed it and dumped the constant in the resulting Javascript bundle.

By convention, I'd recommend you keep static assets in the same folder as the calling React component. If you have multiple components pointing to the same assets, just choose a sensible name - like src/fonts/ or src/images, or even just /images.

2. From within your CSS

Inside any .css|sass|scss|less| or *.global. versions of the same, you can import using the regular @import syntax:

styles.global.css

```<code>@font-face {
    font-family: 'Starjout';
    src: url('./Starjout.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

html {
  padding: 0;
  border: 0;
  font-family: 'Starjout';
  font-size: 16px;
}
</code>```

To ensure the font is resolved correctly, import relative to the CSS file. In this case, Starjout.ttf resides in the same folder as styles.global.css.

3. Inside /static

Anything you put in /static will be placed in the resulting dist/public folder as-is. It won't be processed by Webpack- this means, images won't be compressed in production and no .gz or .br versions will be created. They'll simply be copied over.

To reference the file, you can then use the full URL inside your CSS. If you use a relative path, Webpack will expect to find the file relative to the source CSS and it won't work. Likewise, putting things in /static means the file will be copied over in its original form, so importing via JS won't work properly either.

The basic rule is: Any static file you want to consider 'source', put in src/ or anywhere else in your project route. Anything you want to copy without processing or being able to import dynamically, put in /static

Body:
You can reference fonts (or images) in three ways:

1. From within your JS code

You can import a font/img just like any other code, using ES6 module syntax:

// imports will start looking in your project root
image someFont from 'src/fonts/whatever.ttf'; // someFont = public path to font

In this case, someFont will equal a string of the font file path that's processed by Webpack, and dumped in the resulting dist folder. That's done for you automatically; you don't need to put the fonts or images anywhere special.

You can then reference this in your React components wherever you'd normally need the full file path; the string will be publicly accessible from the ReactQL web server:

// The regular, pre-processed PNG image
import logoImage from 'src/images/logo.png';

// A component that uses the image
const ShowLogo = () => (
   <img src={logoImage} />
);

In this case, logoImage might wind up as /assets/img/logo.d41d8cd98f00b204e980.png after Webpack has processed it and dumped the constant in the resulting Javascript bundle.

By convention, I'd recommend you keep static assets in the same folder as the calling React component. If you have multiple components pointing to the same assets, just choose a sensible name - like src/fonts/ or src/images, or even just /images.

2. From within your CSS

Inside any .css|sass|scss|less| or *.global. versions of the same, you can import using the regular @import syntax:

styles.global.css

@font-face {
    font-family: 'Starjout';
    src: url('./Starjout.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

html {
  padding: 0;
  border: 0;
  font-family: 'Starjout';
  font-size: 16px;
}

To ensure the font is resolved correctly, import relative to the CSS file. In this case, Starjout.ttf resides in the same folder as styles.global.css.

3. Inside /static

Anything you put in /static will be placed in the resulting dist/public folder as-is. It won't be processed by Webpack- this means, images won't be compressed in production and no .gz or .br versions will be created. They'll simply be copied over.

To reference the file, you can then use the full URL inside your CSS. If you use a relative path, Webpack will expect to find the file relative to the source CSS and it won't work. Likewise, putting things in /static means the file will be copied over in its original form, so importing via JS won't work properly either.

The basic rule is: Any static file you want to consider 'source', put in src/ or anywhere else in your project route. Anything you want to copy without processing or being able to import dynamically, put in /static


问:
Why do I get an error upon entering user into a database?
I'm teaching myself Mongodb.  At first, I ran npm install --save mongoose uuid in Terminal to start things off.  The goal of my program is to store a user in the database.

In Terminal, after running node index.js I want it to say:

```<code>About to save!
Saved!
</code>```

But what I'm seeing in Terminal is (below):

Here's index.js

```<code>var mongoose = require('mongoose');
var uuid = require('uuid');

var Schema = mongoose.Schema;

/* New code from suggested website in error */

var promise = mongoose.connect('mongodb://localhost:testMongo/testMongo', {
    useMongoClient: true,
});

promise.then(function(db) {

    db.model();
    connection.openUri('mongodb://localhost:testMongo/testMongo', { /* options */ });

var userSchema = new Schema({
    email: {
        type: String,
        unique: true
    },
    password: {type: String},

    todos: [
        {
            text: {type: String}
        }
    ]
});

userSchema.pre('save', function(next) {
    console.log("About to save!");
    var user = this;
    user.password = uuid.v4();
    next();
});

 var User = mongoose.model('user', userSchema);
 var email = 'test@test.com';

// var user = new User({
//     email: email
// });
//
// user.save(function(err) {
//     if(err) {
//         return console.log(err);
//     } else {
//         return console.log("User was saved!");
//     }
// })
//
// console.log("Outside of callback!");

var text = "This is a todo.";

User.findOne({email: email}, function(user, err) {
   if(err) {
       return console.log(err);
   }

   if(!user) {
       return console.log("Couldn't find user!");
   }

   var count = user.todos.push({
       text: text
   });

   console.log(count);

   user.save(function(err){
      if(err) {
          console.log(err);
      } else {
          console.log("Saved!");
      }
   });
});
</code>```

Error in Terminal:

```<code>(node:14312) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
{ _id: 595fe7c14a9810330c75aacc,
  password: '297d5907-d9d7-49ef-800c-97a56aa395f7',
  email: 'test@test.com',
  __v: 0,
  todos: [] }
</code>```

答:
That is not an error. It clearly says it's a warning: DeprecationWarning.
Also the message gives you a link to resolve the warning: http://mongoosejs.com/docs/connections.html#use-mongo-client

Body:
I'm teaching myself Mongodb.  At first, I ran npm install --save mongoose uuid in Terminal to start things off.  The goal of my program is to store a user in the database.

In Terminal, after running node index.js I want it to say:

About to save!
Saved!

But what I'm seeing in Terminal is (below):

Here's index.js

var mongoose = require('mongoose');
var uuid = require('uuid');

var Schema = mongoose.Schema;

/* New code from suggested website in error */

var promise = mongoose.connect('mongodb://localhost:testMongo/testMongo', {
    useMongoClient: true,
});

promise.then(function(db) {

    db.model();
    connection.openUri('mongodb://localhost:testMongo/testMongo', { /* options */ });

var userSchema = new Schema({
    email: {
        type: String,
        unique: true
    },
    password: {type: String},

    todos: [
        {
            text: {type: String}
        }
    ]
});

userSchema.pre('save', function(next) {
    console.log("About to save!");
    var user = this;
    user.password = uuid.v4();
    next();
});

 var User = mongoose.model('user', userSchema);
 var email = 'test@test.com';

// var user = new User({
//     email: email
// });
//
// user.save(function(err) {
//     if(err) {
//         return console.log(err);
//     } else {
//         return console.log("User was saved!");
//     }
// })
//
// console.log("Outside of callback!");

var text = "This is a todo.";

User.findOne({email: email}, function(user, err) {
   if(err) {
       return console.log(err);
   }

   if(!user) {
       return console.log("Couldn't find user!");
   }

   var count = user.todos.push({
       text: text
   });

   console.log(count);

   user.save(function(err){
      if(err) {
          console.log(err);
      } else {
          console.log("Saved!");
      }
   });
});

Error in Terminal:

(node:14312) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
{ _id: 595fe7c14a9810330c75aacc,
  password: '297d5907-d9d7-49ef-800c-97a56aa395f7',
  email: 'test@test.com',
  __v: 0,
  todos: [] }


问:
Scrolltop animation not working
I am using this js to scroll to the id of the page.  I took it from w3 schools and it works on my other site, so I don't understand why it doesn't work on my new site.  It goes to the correct part of the page, but it doesn't do the scroll animation.

js:

```<code><script>
    $(document).ready(function () {

        $(".navbar a, footer a[href='#myPage']").on('click', function (event) {

            if (this.hash !== "") {

                event.preventDefault();

                var hash = this.hash;

                $('html, body').animate({
                    scrollTop: $(hash).offset().top
                }, 900, function () {

                    window.location.hash = hash;
                });
            }
        });
    })
</script>
</code>```

html navbar code:

```<code><nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

        </div>
        <div class="collapse navbar-collapse" id="myNavbar">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="#about">ABOUT</a></li>
                <li><a href="#clients">CLIENTS</a></li>
                <li><a href="#sessions">SESSIONS</a></li>
                <li><a href="#contact">CONTACT</a></li>
            </ul>
        </div>
    </div>
</nav>
</code>```

Please let me know if you need to see any other code. Thanks!

答:
That should work.

Are you positive that the new site is using jQuery and that the IDs of the element that you are scrolling to are correct?

Is your console displaying an error?

Title: Scrolltop animation not working

Body:
I am using this js to scroll to the id of the page.  I took it from w3 schools and it works on my other site, so I don't understand why it doesn't work on my new site.  It goes to the correct part of the page, but it doesn't do the scroll animation.

js:

html navbar code:

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

            </button>

ABOUT

CLIENTS

SESSIONS

CONTACT

Please let me know if you need to see any other code. Thanks!


问:
Creating custom Label in C# and passing data in events
I had been playing around with an idea for a game, and implementation was going fairly well, but I have hit a stumbling block.

Basically, I have a form, which will show talent trees.  I am just going to use labels to display the relevant details, and I want to create them programmatically.  The display part is working fine, the part I am having trouble with is adding an event handler to the labels.

I want to be able to pass data during the event handling, so that I can identify which specific label was clicked, but I am hitting a brick wall.  So when a particular label is clicked, the name of its associated skill (just passing a string) will be sent to the event handler.  Any help would be appreciated.  Here is the relevant code that I have:

```<code>        public void DisplayTree()
    {
        int i=0;
        startPoint.X = 40;
        startPoint.Y = 125;

        foreach(SkillNode s in tree.tier1)
        {
            for (i=0; i < s.labels.Count;i++ )
            {
                //Displays a label for each available rank for a skill
                s.labels.ElementAt(i).Text = (i+1).ToString()+"/"+s.maxRank.ToString();
                s.labels.ElementAt(i).Location = startPoint;
                startPoint.Y += s.labels.ElementAt(i).Height + 2;
                s.labels.ElementAt(i).Name = "lbl"+s.name+i.ToString();

                //Only enable it to be clicked if the user is at the correct rank
                if (s.rank == i)
                {
                    s.labels.ElementAt(i).Enabled = true;
                }
                else
                {
                    s.labels.ElementAt(i).Enabled = false;
                }
                //Add Event here
                //I want to pass the name of the skill with the event

                this.Controls.Add(s.labels.ElementAt(i));
            }
            startPoint.X += s.title.Width + 5;
            startPoint.Y = 125;
        }
    }
    public void LabelClick()
    {
        //Code here to pick out the name of the label

    }
</code>```

答:
Try this:</p>

```<code>    public void LabelClick()
    {
       Console.WriteLine(((Control)sender).Name);
    }
</code>```

Body:
I had been playing around with an idea for a game, and implementation was going fairly well, but I have hit a stumbling block.

Basically, I have a form, which will show talent trees.  I am just going to use labels to display the relevant details, and I want to create them programmatically.  The display part is working fine, the part I am having trouble with is adding an event handler to the labels.

I want to be able to pass data during the event handling, so that I can identify which specific label was clicked, but I am hitting a brick wall.  So when a particular label is clicked, the name of its associated skill (just passing a string) will be sent to the event handler.  Any help would be appreciated.  Here is the relevant code that I have:

        public void DisplayTree()
    {
        int i=0;
        startPoint.X = 40;
        startPoint.Y = 125;

        foreach(SkillNode s in tree.tier1)
        {
            for (i=0; i < s.labels.Count;i++ )
            {
                //Displays a label for each available rank for a skill
                s.labels.ElementAt(i).Text = (i+1).ToString()+"/"+s.maxRank.ToString();
                s.labels.ElementAt(i).Location = startPoint;
                startPoint.Y += s.labels.ElementAt(i).Height + 2;
                s.labels.ElementAt(i).Name = "lbl"+s.name+i.ToString();

                //Only enable it to be clicked if the user is at the correct rank
                if (s.rank == i)
                {
                    s.labels.ElementAt(i).Enabled = true;
                }
                else
                {
                    s.labels.ElementAt(i).Enabled = false;
                }
                //Add Event here
                //I want to pass the name of the skill with the event

                this.Controls.Add(s.labels.ElementAt(i));
            }
            startPoint.X += s.title.Width + 5;
            startPoint.Y = 125;
        }
    }
    public void LabelClick()
    {
        //Code here to pick out the name of the label

    }

Body:
Try this:

    public void LabelClick()
    {
       Console.WriteLine(((Control)sender).Name);
    }


问:
Why does visual studio add "p:" to all my controls?
I've noticed that if I add a control by dragging it from the toolbox, the letter p, followed by a colon, is appended to the beginning of the control name, and also some of it's properties. The "XAML Styler" extension also seems to do the same when you format.

I've noticed that everything (at least seems to) have the same exact behavior if you take off all the p's.

Is there any benefit to having, say

```<code><p:Rectangle
    x:Name="leftPanel"
    Grid.Row="1"
    Fill="#FF2F3136" />
</code>```

rather than

```<code><Rectangle
    x:Name="leftPanel"
    Grid.Row="1"
    Fill="#FF2F3136" />
</code>```

答:
It is just adding the reference to the namespace which would be defined at the top of the XAML document, like for example here:

```<code><Page x:Class="WPFApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:SDKSample;assembly=SDKSampleLibrary">
  ...
  <custom:ExampleClass/>
...
</Page>
</code>```

You should probably find a reference to System.Windows.Shapes defined in the namespaces at the top of your document

Body:
I've noticed that if I add a control by dragging it from the toolbox, the letter p, followed by a colon, is appended to the beginning of the control name, and also some of it's properties. The "XAML Styler" extension also seems to do the same when you format.

I've noticed that everything (at least seems to) have the same exact behavior if you take off all the p's.

Is there any benefit to having, say

rather than

<Rectangle
    x:Name="leftPanel"
    Grid.Row="1"
    Fill="#FF2F3136" />

Body:
It is just adding the reference to the namespace which would be defined at the top of the XAML document, like for example here:

<Page x:Class="WPFApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:SDKSample;assembly=SDKSampleLibrary">
  ...
  <custom:ExampleClass/>
...
</Page>

You should probably find a reference to System.Windows.Shapes defined in the namespaces at the top of your document


问:
How can i make this div match the size of the other column?
I have this table with Peoples names and several weeks with each week a selection of football teams, i need to make it so the column with all the names in it is the same as the weekly columns but the weekly columns keeps going large unless i specifically give it a height but i don't know exactly how big i just want it to get bigger as the more entry's there are to it.

```<code>    <div class="container">
        <div class="col-xs-3 text-center">
            <div class="row bg-blue">Names</div>
            <div class="row">Bob</div>
            <div class="row">Alex</div>
            <div class="row">Steve</div>
            <div class="row">Steve</div>
            <div class="row">Steve</div>
            <div class="row">Steve</div>
            <div class="row">Steve</div>
            <div class="row">Steve</div>
            <div class="row">Steve</div>
            <div class="row">Steve</div>
            <div class="row">Steve</div>
            <div class="row">Steve</div>
        </div>
        <div class="col-xs-9 demo">
            <div class="col-xs-3 item">
                <div class="row bg-blue">Week 1</div>
                <div class="row">Man C</div>
                <div class="row">Arsen</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
            </div>
            <div class="col-xs-3 item">
                <div class="row bg-blue">Week 2</div>
                <div class="row">Man C</div>
                <div class="row">Arsen</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
                <div class="row">Chel</div>
            </div>
            <div class="col-xs-3 item">
                <div class="row bg-blue">Week 3</div>
                <div class="row">Man C</div>
                <div class="row">Arsen</div>
                <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 4</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 5</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 6</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 7</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 8</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 9</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 10</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 11</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 12</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
        <div class="col-xs-3 item">
            <div class="row bg-blue">Week 13</div>
            <div class="row">Man C</div>
            <div class="row">Arsen</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
            <div class="row">Chel</div>
        </div>
    </div>
</div>

    <br /><br />

  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript" src="js/dragend.js"></script>

  <script>

    $(function() {
      var BODY = $("body"),
          container = $(".demo"),
          pageElements;

      $(window).on("ready resize", function(event) {

        var width = $(this).width(),
            itemsInPage = 1;

        if (width > 1000) {
          itemsInPage = 5
        } else if (width > 600) {
          itemsInPage = 4;
        } else if (width > 400) {
          itemsInPage = 2;
        }

        container.dragend({
          pageContainer: "#container",
          itemsInPage: itemsInPage,
          pageClass: "item",
          afterInitialize: function() {
            this.container.style.visibility = "visible";
          }
        });

      });

    });

  </script>
</code>```

Here is the css im using:

```<code>.demo {
    background: #457;
    cursor: hand;
    cursor: -moz-grab;
    cursor: -webkit-grab;
    cursor: grab;
    color:#fff;
    text-align: center;
    height:50%;
}

.item {
    background: #354;
}

.item:nth-child(2n+0) {
    background: #333;
}
</code>```

Here is a live demo: http://olli460.com/fc/index.php?page=test

答:
your inline style is overwriting bootstrap style col-xs-3:

Try to remove the width: 171px; or add it to your name col.

Body:
I have this table with Peoples names and several weeks with each week a selection of football teams, i need to make it so the column with all the names in it is the same as the weekly columns but the weekly columns keeps going large unless i specifically give it a height but i don't know exactly how big i just want it to get bigger as the more entry's there are to it.

Names

Bob

Alex

Steve

Steve

Steve

Steve

Steve

Steve

Steve

Steve

Steve

Steve

Week 1

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 2

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 3

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 4

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 5

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 6

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 7

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 8

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 9

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 10

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 11

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 12

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Week 13

Man C

Arsen

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Chel

Here is the css im using:

.demo {
    background: #457;
    cursor: hand;
    cursor: -moz-grab;
    cursor: -webkit-grab;
    cursor: grab;
    color:#fff;
    text-align: center;
    height:50%;
}

.item {
    background: #354;
}

.item:nth-child(2n+0) {
    background: #333;
}

Here is a live demo: http://olli460.com/fc/index.php?page=test

Body:
your inline style is overwriting bootstrap style col-xs-3:

<div class="col-xs-3 item" style="margin: 0px; float: left; overflow-y: auto; overflow-x: hidden; padding: 0px; display: block; height: 320px; width: 171px;">

Try to remove the width: 171px; or add it to your name col.


问:
How to perform basic Multiple Sequence Alignments in R?
(I've tried asking this on BioStars, but for the slight chance that someone from text mining would think there is a better solution, I am also reposting this here)

The task I'm trying to achieve is to align several sequences.

I don't have a basic pattern to match to.  All that I know is that the "True" pattern should be of length "30" and that the sequences I have had missing values introduced to them at random points.

Here is an example of such sequences, were on the left we see what is the real location of the missing values, and on the right we see the sequence that we will be able to observe.

My goal is to reconstruct the left column using only the sequences I've got on the right column (based on the fact that many of the letters in each position are the same)

```<code>                     Real_sequence           The_sequence_we_see
1   CGCAATACTAAC-AGCTGACTTACGCACCG CGCAATACTAACAGCTGACTTACGCACCG
2   CGCAATACTAGC-AGGTGACTTCC-CT-CG   CGCAATACTAGCAGGTGACTTCCCTCG
3   CGCAATGATCAC--GGTGGCTCCCGGTGCG  CGCAATGATCACGGTGGCTCCCGGTGCG
4   CGCAATACTAACCA-CTAACT--CGCTGCG   CGCAATACTAACCACTAACTCGCTGCG
5   CGCACGGGTAAGAACGTGA-TTACGCTCAG CGCACGGGTAAGAACGTGATTACGCTCAG
6   CGCTATACTAACAA-GTG-CTTAGGC-CTG   CGCTATACTAACAAGTGCTTAGGCCTG
7   CCCA-C-CTAA-ACGGTGACTTACGCTCCG   CCCACCTAAACGGTGACTTACGCTCCG
</code>```

Here is an example code to reproduce the above example:

```<code>ATCG <- c("A","T","C","G")
set.seed(40)
original.seq <- sample(ATCG, 30, T)
seqS <- matrix(original.seq,200,30, T)
change.letters <- function(x, number.of.changes = 15, letters.to.change.with = ATCG)
{
    number.of.changes <- sample(seq_len(number.of.changes), 1)
    new.letters <- sample(letters.to.change.with , number.of.changes, T)
    where.to.change.the.letters <- sample(seq_along(x) , number.of.changes, F)
    x[where.to.change.the.letters] <- new.letters
    return(x)
}
change.letters(original.seq)
insert.missing.values <- function(x) change.letters(x, 3, "-")
insert.missing.values(original.seq)

seqS2 <- t(apply(seqS, 1, change.letters))
seqS3 <- t(apply(seqS2, 1, insert.missing.values))

seqS4 <- apply(seqS3,1, function(x) {paste(x, collapse = "")})
require(stringr)
# library(help=stringr)
all.seqS <- str_replace(seqS4,"-" , "")

# how do we allign this?
data.frame(Real_sequence = seqS4, The_sequence_we_see = all.seqS)
</code>```

I understand that if all I had was a string and a pattern I would be able to use

```<code>library(Biostrings)
pairwiseAlignment(...)
</code>```

But in the case I present we are dealing with many sequences to align to one another (instead of aligning them to one pattern).

Is there a known method for doing this in R?

答:
You are looking for a global alignment algorithm on multiple sequences.
Did you look at Wikipedia before asking ?

First learn what global alignment is, then look for multiple sequence alignment.

Wikipedia doesn't give a lot of details about algorithms, but this paper is better.

Body:
(I've tried asking this on BioStars, but for the slight chance that someone from text mining would think there is a better solution, I am also reposting this here)

The task I'm trying to achieve is to align several sequences.

I don't have a basic pattern to match to.  All that I know is that the "True" pattern should be of length "30" and that the sequences I have had missing values introduced to them at random points.

Here is an example of such sequences, were on the left we see what is the real location of the missing values, and on the right we see the sequence that we will be able to observe.

My goal is to reconstruct the left column using only the sequences I've got on the right column (based on the fact that many of the letters in each position are the same)

                     Real_sequence           The_sequence_we_see
1   CGCAATACTAAC-AGCTGACTTACGCACCG CGCAATACTAACAGCTGACTTACGCACCG
2   CGCAATACTAGC-AGGTGACTTCC-CT-CG   CGCAATACTAGCAGGTGACTTCCCTCG
3   CGCAATGATCAC--GGTGGCTCCCGGTGCG  CGCAATGATCACGGTGGCTCCCGGTGCG
4   CGCAATACTAACCA-CTAACT--CGCTGCG   CGCAATACTAACCACTAACTCGCTGCG
5   CGCACGGGTAAGAACGTGA-TTACGCTCAG CGCACGGGTAAGAACGTGATTACGCTCAG
6   CGCTATACTAACAA-GTG-CTTAGGC-CTG   CGCTATACTAACAAGTGCTTAGGCCTG
7   CCCA-C-CTAA-ACGGTGACTTACGCTCCG   CCCACCTAAACGGTGACTTACGCTCCG

Here is an example code to reproduce the above example:

ATCG <- c("A","T","C","G")
set.seed(40)
original.seq <- sample(ATCG, 30, T)
seqS <- matrix(original.seq,200,30, T)
change.letters <- function(x, number.of.changes = 15, letters.to.change.with = ATCG)
{
    number.of.changes <- sample(seq_len(number.of.changes), 1)
    new.letters <- sample(letters.to.change.with , number.of.changes, T)
    where.to.change.the.letters <- sample(seq_along(x) , number.of.changes, F)
    x[where.to.change.the.letters] <- new.letters
    return(x)
}
change.letters(original.seq)
insert.missing.values <- function(x) change.letters(x, 3, "-")
insert.missing.values(original.seq)

seqS2 <- t(apply(seqS, 1, change.letters))
seqS3 <- t(apply(seqS2, 1, insert.missing.values))

seqS4 <- apply(seqS3,1, function(x) {paste(x, collapse = "")})
require(stringr)
# library(help=stringr)
all.seqS <- str_replace(seqS4,"-" , "")

# how do we allign this?
data.frame(Real_sequence = seqS4, The_sequence_we_see = all.seqS)

I understand that if all I had was a string and a pattern I would be able to use

library(Biostrings)
pairwiseAlignment(...)

But in the case I present we are dealing with many sequences to align to one another (instead of aligning them to one pattern).

Is there a known method for doing this in R?


问:
QQuickWidget with transparent background
I added in a QDialog aQQuickWidget to load a .qml but its background color is white. My qml declares a Rectangle not filling all QQuickWidget surface. I need the not filled surface having the same background color of the dialog. What is the way to have a transparent background?

答:
It's explained in the QQuickWidget documentation : QQuickWidget Limitations

Putting other widgets underneath and making the QQuickWidget transparent will not lead to the expected results: the widgets underneath will not be visible. This is because in practice the QQuickWidget is drawn before all other regular, non-OpenGL widgets, and so see-through types of solutions are not feasible. Other type of layouts, like having widgets on top of the QQuickWidget, will function as expected.

When absolutely necessary, this limitation can be overcome by setting the Qt::WA_AlwaysStackOnTop attribute on the QQuickWidget. Be aware, however that this breaks stacking order. For example it will not be possible to have other widgets on top of the QQuickWidget, so it should only be used in situations where a semi-transparent QQuickWidget with other widgets visible underneath is required.


问:
How to convert Select with Inner Join query in Spring Query
This is my SQL statement which works properly:

SELECT cedula FROM paciente INNER JOIN titular ON paciente.id = titular.paciente_id WHERE cedula = '19163676';

returns cedula field from paciente table when the ids match

I've read this post: How To Define a JPA Repository Query with a Join

But in that post the relationship is One-to-One.

In my case, the relationship is Many-to-One where the father model is paciente and the child model is titular

This is my Paciente domain:

Paciente.java

```<code>@Id
@Column(name="pacienteId")
@SequenceGenerator(name="paciente_id_seq",
    sequenceName="paciente_id_seq",
    allocationSize=1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
    generator="paciente_id_seq")
private Long id;

@NotNull
@Column(name = "cedula", nullable = false)
private String cedula;
</code>```

And this is my Titular domain with the relationship:

Titular.java

```<code> @Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
@JoinColumn(name="pacienteId")
private Paciente paciente;
</code>```

And this is my PacienteRepository.java which will contain the query:

```<code>public interface PacienteRepository extends JpaRepository<Paciente,Long> {
List<Paciente> findByNombreContainsIgnoreCase(String nombre);
List<Paciente> findByNombreLikeIgnoreCaseAndApellidoLikeIgnoreCase(String nombre, String apellido);
List<Paciente> findByCedula(String cedula);
Page<Paciente> findByCedulaStartsWith(String cedula, Pageable pageable);
</code>```

}

How can I do it?

答:
SOLVED (2017-07-06):

JPQL isn't the same that SQL. JPQL can return the desired object through Entities (even, inside of a different Java repository Entity), no needs Inner Join command.

i.e.:

PacienteRepository.java:

```<code>@Query("select titular.paciente from Titular titular where titular.paciente.cedula in ?1")
Page<Paciente> findByCedulaEndsWith(String cedula, Pageable pageable);
</code>```

That returns the patient from Titular table (owners), when its 'cedula' (ID card, DNI, etc) match with 'cedula' from Paciente (patients) table. Else, returns an empty array.

Body:
This is my SQL statement which works properly:

SELECT cedula FROM paciente INNER JOIN titular ON paciente.id = titular.paciente_id WHERE cedula = '19163676';

returns cedula field from paciente table when the ids match

I've read this post: How To Define a JPA Repository Query with a Join

But in that post the relationship is One-to-One.

In my case, the relationship is Many-to-One where the father model is paciente and the child model is titular

This is my Paciente domain:

Paciente.java

@Id
@Column(name="pacienteId")
@SequenceGenerator(name="paciente_id_seq",
    sequenceName="paciente_id_seq",
    allocationSize=1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
    generator="paciente_id_seq")
private Long id;

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

And this is my Titular domain with the relationship:

Titular.java

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

@ManyToOne
@JoinColumn(name="pacienteId")
private Paciente paciente;

And this is my PacienteRepository.java which will contain the query:

public interface PacienteRepository extends JpaRepository<Paciente,Long> {
List<Paciente> findByNombreContainsIgnoreCase(String nombre);
List<Paciente> findByNombreLikeIgnoreCaseAndApellidoLikeIgnoreCase(String nombre, String apellido);
List<Paciente> findByCedula(String cedula);
Page<Paciente> findByCedulaStartsWith(String cedula, Pageable pageable);

}

How can I do it?

Body:
SOLVED (2017-07-06):

JPQL isn't the same that SQL. JPQL can return the desired object through Entities (even, inside of a different Java repository Entity), no needs Inner Join command.

i.e.:

PacienteRepository.java:

@Query("select titular.paciente from Titular titular where titular.paciente.cedula in ?1")
Page<Paciente> findByCedulaEndsWith(String cedula, Pageable pageable);

That returns the patient from Titular table (owners), when its 'cedula' (ID card, DNI, etc) match with 'cedula' from Paciente (patients) table. Else, returns an empty array.


问:
Chaining & to_proc on symbol
It's well known to Rubyist & will call to_proc on a symbol, so

```<code>[:a, :b, :c].map(&:to_s)
</code>```

is equivalent to

```<code>[:a, :b, :c].map { |e| e.to_s } # => ["a", "b", "c"]
</code>```

Say I want to call another method right after to_s, these two implementations will work:

```<code>[:a, :b, :c].map { |e| e.to_s.upcase }
[:a, :b, :c].map(&:to_s).map(&:upcase)
</code>```

My question is, is there a way to chain the & Symbol#to_proc call in one parameter? Something like:

```<code>[:a, :b, :c].map(&:to_s:upcase)
</code>```

Thanks!

答:
While we're playing with syntax, how about monkey-patching Array with a to_proc method?

```<code>class Array
  def to_proc
    return :itself.to_proc if empty?
    ->(obj) { drop(1).to_proc.call(first.to_proc.call(obj)) }
  end
end

["foo", "bar", "baz"].map(&[:capitalize, :swapcase, :chars, ->a{ a.join("-") }])
# => ["f-O-O", "b-A-R", "b-A-Z"]
</code>```

See it on repl.it: https://repl.it/JS4B/1

Title: Chaining & to_proc on symbol

Body:
It's well known to Rubyist & will call to_proc on a symbol, so

[:a, :b, :c].map(&:to_s)

is equivalent to

[:a, :b, :c].map { |e| e.to_s } # => ["a", "b", "c"]

Say I want to call another method right after to_s, these two implementations will work:

[:a, :b, :c].map { |e| e.to_s.upcase }
[:a, :b, :c].map(&:to_s).map(&:upcase)

My question is, is there a way to chain the & Symbol#to_proc call in one parameter? Something like:

[:a, :b, :c].map(&:to_s:upcase)

Thanks!

Body:
While we're playing with syntax, how about monkey-patching Array with a to_proc method?

class Array
  def to_proc
    return :itself.to_proc if empty?
    ->(obj) { drop(1).to_proc.call(first.to_proc.call(obj)) }
  end
end

["foo", "bar", "baz"].map(&[:capitalize, :swapcase, :chars, ->a{ a.join("-") }])
# => ["f-O-O", "b-A-R", "b-A-Z"]

See it on repl.it: https://repl.it/JS4B/1


问:
T-SQL: 'A2000' to 'A2999' in Where clause
In my Where Clause I want to return all rows where the 'Code' is from 'A2000' all the way to 'A2999'.

I am using Like 'A2%' for now because I know that this currently returns only values between A2000 and A2999. But this could change and there could be values like A216 or A27 or A2 ... in the future.

Is there a way achieve what I want without listing one thousand consecutive codes [from A2000 to A2999]?

Thanks!

答:
It's worth noting that you can you BETWEEN for this kind of problem.

```<code>-- Sample data
WITH E(N) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))x(x)),
iTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1))+999 FROM E a, E b, E c, E d),
sc(someCode) AS (SELECT CONCAT('A', N) FROM iTally UNION ALL SELECT CONCAT('B', N) FROM iTally)
SELECT SomeCode INTO #codes FROM sc;

-- Solution
SELECT someCode
FROM #codes
WHERE someCode BETWEEN 'A2000' AND 'A2999';
</code>```

Update (20170713):

Sorry for the late update, I must the second comment below. I just read it.

It is correct that my WHERE clause would pick up the value "A22"; it would also pick up "A2X00". That said, if the if the format you are working with looks like this: CDDDD (with C being a character and D being digit) then my solution is correct and SARGable. This is one of the reasons it's best to include DDL when posting a SQL Question. Note this article.

Update #2

Re: the question about how I generated the sample data.

I like explaining this because it invlolves tally tables - one of my favorite SQL topics ans one too view developers have any knowledge of.
My sample data coded generates the values A1000, A1001, A1002... though ...B15638, B15639, B15640. This provides a mix of "good" and bad values for you to test my logic against.
Tally tables are indispensible. Here's three of my favorite articles on the topic:

The "Numbers" or "Tally" Table: What it is and how it replaces a loop -- Jeff Moden

Tally Tables in T-SQL -- Dwain Camps

Virtual Auxiliary Table of Numbers -- Itzik Ben-Gan

So here's what the code does:

Creates 10 dummy values in the first CTE (E)

Cross Joins the values to themselves three times in the second CTE (iTally)
This very quicky generates 10,000 rows (10*10*10*10)

Numbers the rows 1-10000 using ROW_NUMBER (still in the iTally CTE)

Cross joins the numbers 1-10000 to the Values "A" and "B" then concatinates the letters & numbers

Does a SELECT INTO to create a temp table to hold the values.

Notice I don't return the "dummy values" in my final SELECT statement; they only exist so that ROW_NUMBER() can generate the numbers.
ROW_NUMBER() requires an OVER (ORDER BY) clause - which can cause a sort in the execution plan and slow my query down. ORDER (BY )
acceptable syntax as far as SQL Server 2005+ is concerned and this circumvents that nasty sort.

On my laptop (an HP with 32gb, 4 2.8ghz CPU - 8 logical CPU, 7200 rpm disk) I can generate the numbers 1 to 1,000,000,000 in 70-90 seconds.
This is one of many reasons I love tally tables.

Body:
It's worth noting that you can you BETWEEN for this kind of problem.

-- Sample data
WITH E(N) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))x(x)),
iTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1))+999 FROM E a, E b, E c, E d),
sc(someCode) AS (SELECT CONCAT('A', N) FROM iTally UNION ALL SELECT CONCAT('B', N) FROM iTally)
SELECT SomeCode INTO #codes FROM sc;

-- Solution
SELECT someCode
FROM #codes
WHERE someCode BETWEEN 'A2000' AND 'A2999';

Update (20170713):

Sorry for the late update, I must the second comment below. I just read it.

It is correct that my WHERE clause would pick up the value "A22"; it would also pick up "A2X00". That said, if the if the format you are working with looks like this: CDDDD (with C being a character and D being digit) then my solution is correct and SARGable. This is one of the reasons it's best to include DDL when posting a SQL Question. Note this article.

Update #2

Re: the question about how I generated the sample data.

I like explaining this because it invlolves tally tables - one of my favorite SQL topics ans one too view developers have any knowledge of.
My sample data coded generates the values A1000, A1001, A1002... though ...B15638, B15639, B15640. This provides a mix of "good" and bad values for you to test my logic against.
Tally tables are indispensible. Here's three of my favorite articles on the topic:

The "Numbers" or "Tally" Table: What it is and how it replaces a loop -- Jeff Moden

Tally Tables in T-SQL -- Dwain Camps

Virtual Auxiliary Table of Numbers -- Itzik Ben-Gan

So here's what the code does:

Creates 10 dummy values in the first CTE (E)

Cross Joins the values to themselves three times in the second CTE (iTally)
This very quicky generates 10,000 rows (10*10*10*10)

Numbers the rows 1-10000 using ROW_NUMBER (still in the iTally CTE)

Cross joins the numbers 1-10000 to the Values "A" and "B" then concatinates the letters & numbers

Does a SELECT INTO to create a temp table to hold the values.

Notice I don't return the "dummy values" in my final SELECT statement; they only exist so that ROW_NUMBER() can generate the numbers.
ROW_NUMBER() requires an OVER (ORDER BY) clause - which can cause a sort in the execution plan and slow my query down. ORDER (BY )
acceptable syntax as far as SQL Server 2005+ is concerned and this circumvents that nasty sort.

On my laptop (an HP with 32gb, 4 2.8ghz CPU - 8 logical CPU, 7200 rpm disk) I can generate the numbers 1 to 1,000,000,000 in 70-90 seconds.
This is one of many reasons I love tally tables.


问:
how to set the tabbar items color other than default blue, if we had more than 5 tabbar items?
I am using tab bar controller with more than 5 tab items with color as green (ie customized) in my application. As we know 5th, 6th.. tabbar items are handled automatically by MoreViewController.
My question is
  1) if I select the More Tabbar item, blue color item I did get.
  2) If I switch from More Tabbar item into previous one, I also did get the items color as blue.
So, how to make the tabbar items color as green in both cases?</p>

答: In apple documentation there is no solution for this. I ended with my own faked tabbar with customized buttons.</p>