问:
Memory problems with ScrollableCursor in Payara/EclipseLink with Postgres
I'm using Payara 4.1 (Eclipselink 2.6), Postgres 9.6.

I'm trying to use a ScrollableCursor to access data results that can be quite large. In testing we had gotten an java.lang.OutOfMemoryError trying to run the query so I did some heapdump troubleshooting with a smaller amount of data and found a lot of memory taken up by org.postgresql.jdbc.PgResultSet in the rows ArrayList.

Based on EclipseLink documentation you just provide one hint to get the ScrollableCursor, but after attaching the Postgres JDBC driver source code and debugging I found that it was going to load the whole data result if we didn't set the fetch size, so I added QueryHints.JDBC_FETCH_SIZE. What I'm finding though is that it is still fetching the whole query results and saving them to memory initially.

In org.postgresql.v3.QueryExecutorImpl sendOneQuery it only sets the initial rows to the fetch size if the QUERY_FORWARD_CURSOR flag is set.

In org.postgresql.jdbc.PgStatement executeInternal it only sets the QUERY_FORWARD_CURSOR flage if there is a fetch size, the result set isn't scrollable, the connection isn't autoCommit, and the result set isn't holdable.

When debugging my connection is set to autocommit even though I'm calling from a @TransactionAttribute(TransactionAttributeType.REQUIRED) in a @Stateless ejb called from another @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) method in another @Stateless ejb.

I don't see why my query seems to be using a new connection defaulted to autocommit. Before I was using QueryHints.READ_ONLY which is non-transactional, so it probably uses a new connection, but I removed that. Is one of my other query hints causing a new connection? Is there an additional hint I should be using? Is there a bug with Payara/Eclipselink and Postgres so that it never actually scrolls when using ScrollableCursor?

```<code>private static <T> void executeScrollableQuery(@NotNull final Query query, final Consumer<T> recordConsumer) {
    query.setHint(QueryHints.RESULT_SET_TYPE, ResultSetType.ForwardOnly)
            .setHint(QueryHints.SCROLLABLE_CURSOR, HintValues.TRUE)
            .setHint(QueryHints.MAINTAIN_CACHE, HintValues.FALSE).setHint(QueryHints.JDBC_FETCH_SIZE, 500);

    ScrollableCursor cursor = null;
    try {
        cursor = (ScrollableCursor) query.getSingleResult();
        while (cursor.hasNext()) {
            recordConsumer.accept((T) cursor.next());
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
</code>```

答:
As far as I can tell it is a bug with the Postgres JDBC driver. As a work around I was able to pass the entity manager in too and unwrap the connection on the entity manager before getting the query result and this made the connection not autocommit so that it used the supplied fetch size and didn't get the whole query results in memory.

I think the reason this works is that unwrapping the connection makes the transaction dirty, and then the cursor reads using the write connection instead of a new autocommit read connection.

```<code>    private static <T> void executeScrollableQuery(@NotNull final EntityManager em, @NotNull final Query query,
        final Consumer<T> recordConsumer) {
    query.setHint(QueryHints.RESULT_SET_TYPE, ResultSetType.ForwardOnly)
            .setHint(QueryHints.SCROLLABLE_CURSOR, HintValues.TRUE)
            .setHint(QueryHints.MAINTAIN_CACHE, HintValues.FALSE).setHint(QueryHints.JDBC_FETCH_SIZE, 500);

    em.unwrap(Connection.class);

    ScrollableCursor cursor = null;
    try {
        cursor = (ScrollableCursor) query.getSingleResult();
        while (cursor.hasNext()) {
            recordConsumer.accept((T) cursor.next());
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
</code>```

Ok, based on this documentation I guess the postgres driver may be working as intended and it's really an issue with payara/eclipselink that it's allowing an autocommit connection to be used with the eclipselink.cursor.scrollable hint.

Body:
I'm using Payara 4.1 (Eclipselink 2.6), Postgres 9.6.

I'm trying to use a ScrollableCursor to access data results that can be quite large. In testing we had gotten an java.lang.OutOfMemoryError trying to run the query so I did some heapdump troubleshooting with a smaller amount of data and found a lot of memory taken up by org.postgresql.jdbc.PgResultSet in the rows ArrayList.

Based on EclipseLink documentation you just provide one hint to get the ScrollableCursor, but after attaching the Postgres JDBC driver source code and debugging I found that it was going to load the whole data result if we didn't set the fetch size, so I added QueryHints.JDBC_FETCH_SIZE. What I'm finding though is that it is still fetching the whole query results and saving them to memory initially.

In org.postgresql.v3.QueryExecutorImpl sendOneQuery it only sets the initial rows to the fetch size if the QUERY_FORWARD_CURSOR flag is set.

In org.postgresql.jdbc.PgStatement executeInternal it only sets the QUERY_FORWARD_CURSOR flage if there is a fetch size, the result set isn't scrollable, the connection isn't autoCommit, and the result set isn't holdable.

When debugging my connection is set to autocommit even though I'm calling from a @TransactionAttribute(TransactionAttributeType.REQUIRED) in a @Stateless ejb called from another @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) method in another @Stateless ejb.

I don't see why my query seems to be using a new connection defaulted to autocommit. Before I was using QueryHints.READ_ONLY which is non-transactional, so it probably uses a new connection, but I removed that. Is one of my other query hints causing a new connection? Is there an additional hint I should be using? Is there a bug with Payara/Eclipselink and Postgres so that it never actually scrolls when using ScrollableCursor?

private static <T> void executeScrollableQuery(@NotNull final Query query, final Consumer<T> recordConsumer) {
    query.setHint(QueryHints.RESULT_SET_TYPE, ResultSetType.ForwardOnly)
            .setHint(QueryHints.SCROLLABLE_CURSOR, HintValues.TRUE)
            .setHint(QueryHints.MAINTAIN_CACHE, HintValues.FALSE).setHint(QueryHints.JDBC_FETCH_SIZE, 500);

    ScrollableCursor cursor = null;
    try {
        cursor = (ScrollableCursor) query.getSingleResult();
        while (cursor.hasNext()) {
            recordConsumer.accept((T) cursor.next());
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

Body:
As far as I can tell it is a bug with the Postgres JDBC driver. As a work around I was able to pass the entity manager in too and unwrap the connection on the entity manager before getting the query result and this made the connection not autocommit so that it used the supplied fetch size and didn't get the whole query results in memory.

I think the reason this works is that unwrapping the connection makes the transaction dirty, and then the cursor reads using the write connection instead of a new autocommit read connection.

    private static <T> void executeScrollableQuery(@NotNull final EntityManager em, @NotNull final Query query,
        final Consumer<T> recordConsumer) {
    query.setHint(QueryHints.RESULT_SET_TYPE, ResultSetType.ForwardOnly)
            .setHint(QueryHints.SCROLLABLE_CURSOR, HintValues.TRUE)
            .setHint(QueryHints.MAINTAIN_CACHE, HintValues.FALSE).setHint(QueryHints.JDBC_FETCH_SIZE, 500);

    em.unwrap(Connection.class);

    ScrollableCursor cursor = null;
    try {
        cursor = (ScrollableCursor) query.getSingleResult();
        while (cursor.hasNext()) {
            recordConsumer.accept((T) cursor.next());
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

Ok, based on this documentation I guess the postgres driver may be working as intended and it's really an issue with payara/eclipselink that it's allowing an autocommit connection to be used with the eclipselink.cursor.scrollable hint.


来源: stackexchange

问:
Scala - design choices when splitting code over traits, classes, objects
My code is always a mess, and I think I lack some foundational knowledge.  When I try to split functionality out over traits and objects, I'm not quite sure what a best practice would be...  or why to choose one form over another.  I've used the three approaches below, but I'm not necessarily clear on why to choose one over the others.  Can anyone help me think about different ways to structure these kinds of dependencies?

Option 1 - simplest approach, modular, call as needed...  honestly, my inclination is to go this route always to keep things simple...  though it often requires passing loads of arguments into the methods in anything more complicated than this simple example, so it's not very elegant.

```<code>object A {
  def run(x: T): Unit = ??? // do stuff with x
}

object Main {
  val x: T = ???
  def main(args: Array[String]): Unit = {
    A.run(x)
  }
}
</code>```

Option 2 - I've mostly used this approach in my code historically...  if the code in trait A was designed for object Main, and I'm simply splitting it out to make things easier to follow...  this logically makes sense to me.  It also minimizes the arguments passed around to functions, which feels cleaner.  But...  this makes code harder to reuse.  If six months from now I need one function out of trait A somewhere other than object Main because I've extended a project in an unanticipated way, it becomes difficult.

```<code>trait A {
  def x: T
  def run: Unit = ??? // do stuff with x
}

object Main extends A {
  val x: T = ???

  def main(args: Array[String]): Unit = {
    run
  }
}
</code>```

Option 3 - I think this is best when stirring together lots of dependencies?  Honestly I'm not really sure.  Again, this becomes really difficult to reuse pieces as projects expand in functionality.  Likely due to poor design choices by me.

```<code>trait A {
  this: Main =>
  val runner: Runner
  class Runner(x: T) {
    def run: Unit = ??? // do stuff with x
  }
}

object Main extends A {
  val x: T = ???
  val runner = new Runner(x)

  def main(args: Array[String]): Unit = {
    runner.run
  }
}
</code>```

Any thoughts on why to choose one vs. the others to help me take one step towards writing better code?  Does it come down to simply what is most readable and balancing the tradeoffs of passing fewer arguments around vs. making things cleaner and more readable, or is there a smarter way to think about program design.

Any recommendations for places to learn how to make these kinds of decisions better?

答:
I use an object when you want a simple interface to do stuff that doesn't change any state (pure functions). Think in the Math class as an example of this. Also, if you want to implement the singleton dessing pattern you can use object too.

I use a trait if you know that a bunch of different class of objects will have the same interface. If you don't, It could be overkill to define a trait.

And if you want a real object instance of a class is beacuse you need to encapsulate transformation of private properties. I usually do that when I know that I need an abstract data-type, that is, a data structure or entity that will hide implementation details.

Please note that, as Jörg W Mittag says, this is not like Java, because in scala you can define objects using classes.

ContentLicense: CC BY-SA 3.0

Body:
My code is always a mess, and I think I lack some foundational knowledge.  When I try to split functionality out over traits and objects, I'm not quite sure what a best practice would be...  or why to choose one form over another.  I've used the three approaches below, but I'm not necessarily clear on why to choose one over the others.  Can anyone help me think about different ways to structure these kinds of dependencies?

Option 1 - simplest approach, modular, call as needed...  honestly, my inclination is to go this route always to keep things simple...  though it often requires passing loads of arguments into the methods in anything more complicated than this simple example, so it's not very elegant.

object A {
  def run(x: T): Unit = ??? // do stuff with x
}

object Main {
  val x: T = ???
  def main(args: Array[String]): Unit = {
    A.run(x)
  }
}

Option 2 - I've mostly used this approach in my code historically...  if the code in trait A was designed for object Main, and I'm simply splitting it out to make things easier to follow...  this logically makes sense to me.  It also minimizes the arguments passed around to functions, which feels cleaner.  But...  this makes code harder to reuse.  If six months from now I need one function out of trait A somewhere other than object Main because I've extended a project in an unanticipated way, it becomes difficult.

trait A {
  def x: T
  def run: Unit = ??? // do stuff with x
}

object Main extends A {
  val x: T = ???

  def main(args: Array[String]): Unit = {
    run
  }
}

Option 3 - I think this is best when stirring together lots of dependencies?  Honestly I'm not really sure.  Again, this becomes really difficult to reuse pieces as projects expand in functionality.  Likely due to poor design choices by me.

trait A {
  this: Main =>
  val runner: Runner
  class Runner(x: T) {
    def run: Unit = ??? // do stuff with x
  }
}

object Main extends A {
  val x: T = ???
  val runner = new Runner(x)

  def main(args: Array[String]): Unit = {
    runner.run
  }
}

Any thoughts on why to choose one vs. the others to help me take one step towards writing better code?  Does it come down to simply what is most readable and balancing the tradeoffs of passing fewer arguments around vs. making things cleaner and more readable, or is there a smarter way to think about program design.

Any recommendations for places to learn how to make these kinds of decisions better?


问:
How to pass input through a switch statement in another class
I'm new to coding and have a question regarding using switch statements from other classes. This is my original functional class which takes user input and then gives information about the pricing of a condo. First the user is asked to choose a condo type (#1-3), then they are prompted to decide whether they want a parking spot or a garage (1 or 2). I am trying to split the class apart so that only the methods are in one class and the rest of the code in the main method is in another (test class). The problem I've been running into is figuring out a way to pass user input through the switch statement. I've tried to look up ways to do so, but haven't had any luck.

```<code>import java.util.Scanner;

public class CondoSales

{

public static void main(String[] args)

{

System.out.println("Please select one of the following for pricing
information: " +
"1 for a condo with a park view, 2 for a condo with a golf course view, or 3
for a condo with a lake view.");

Scanner input = new Scanner(System.in);
int priceSelection;
priceSelection = input.nextInt();

final int PARK_VIEW = 150000;
final int GOLF_COURSE_VIEW = 175000;
final int LAKE_VIEW = 210000;
int parkingCost;

  switch(priceSelection)

  {

     case (1):
        System.out.println("The condo with a park view costs $" + PARK_VIEW);
        parkingCost = PARK_VIEW;
     break;

     case (2):
        System.out.println("The condo with a golf course view costs $" + GOLF_COURSE_VIEW);
        parkingCost = GOLF_COURSE_VIEW;
     break;

     case (3):
        System.out.println("The condo with a lake view costs $" + LAKE_VIEW + ".");
        parkingCost = LAKE_VIEW;
     break;

     default:
        System.out.println("$0");
        parkingCost = 0;

  }

 System.out.println("Select 1 for a parking spot or 2 for a garage:");

  int parkingSpecification;
  parkingSpecification = input.nextInt();

  switch(parkingSpecification)

  {

     case (1):
        System.out.println("With a parking spot, the cost is $" + parkingCost);
     break;

     case (2):
        System.out.println("With a garage, the cost is $" + (parkingCost + 5000));
     break;

     default:
        System.out.println("You have entered an invalid response; the condo will cost $" + parkingCost + ".");
 }
 }
 }
</code>```

Here is the test class which I have yet to figure out how to pass the price selection input through to the switch from the original class. Any help would be greatly appreciated, as I've been hitting my head against a wall trying to figure this out. Thanks!

```<code>import java.util.Scanner;

public class TestCondoSales

{

final int PARK_VIEW = 150000;
final int GOLF_COURSE_VIEW = 175000;
final int LAKE_VIEW = 210000;
int parkingCost;

public static void main(String[] args)

{

CondoSales methodRetrieval = new CondoSales();

System.out.println("Please select one of the following for pricing
information: " +
"1 for a condo with a park view, 2 for a condo with a golf course view, or 3
for a condo with a lake view.");

Scanner input = new Scanner(System.in);
int priceSelection;
priceSelection = input.nextInt();

methodRetrieval.priceReturn(priceSelection);

System.out.println("Select 1 for a parking spot or 2 for a garage:");

int parkingSpecification;
Scanner input2 = new Scanner(System.in);
parkingSpecification = input.nextInt();

methodRetrieval.parkingReturn(parkingSpecification);

}
}
</code>```

答:
Try using the switch criteria as a method parameter in another class, and then passing the input to that method.  For instance:</p>

```<code>import java.util.Scanner;

public class CondoPriceSelector {

    public static void main(String[] args) {
        PriceSelector selector = new PriceSelector();
        try(Scanner scan = new Scanner(System.in)){
            int priceSelection = scan.nextInt();
            selector.printPrice(priceSelection);
        }
    }
}

class PriceSelector {
    final int parkingCost = 5000;

    public void printPrice(int selection) {
        switch (selection) {
            case (1):
                System.out.println("With a parking spot, the cost is $" + parkingCost);
                break;
            case (2):
                System.out.println("With a garage, the cost is $" + (parkingCost + 5000));
                break;

            default:
                System.out.println("You have entered an invalid response; the condo will cost $" + parkingCost + ".");
        }
    }
}
</code>```

Body:
I'm new to coding and have a question regarding using switch statements from other classes. This is my original functional class which takes user input and then gives information about the pricing of a condo. First the user is asked to choose a condo type (#1-3), then they are prompted to decide whether they want a parking spot or a garage (1 or 2). I am trying to split the class apart so that only the methods are in one class and the rest of the code in the main method is in another (test class). The problem I've been running into is figuring out a way to pass user input through the switch statement. I've tried to look up ways to do so, but haven't had any luck.

import java.util.Scanner;

public class CondoSales

{

public static void main(String[] args)

{

System.out.println("Please select one of the following for pricing
information: " +
"1 for a condo with a park view, 2 for a condo with a golf course view, or 3
for a condo with a lake view.");

Scanner input = new Scanner(System.in);
int priceSelection;
priceSelection = input.nextInt();

final int PARK_VIEW = 150000;
final int GOLF_COURSE_VIEW = 175000;
final int LAKE_VIEW = 210000;
int parkingCost;

  switch(priceSelection)

  {

     case (1):
        System.out.println("The condo with a park view costs $" + PARK_VIEW);
        parkingCost = PARK_VIEW;
     break;

     case (2):
        System.out.println("The condo with a golf course view costs $" + GOLF_COURSE_VIEW);
        parkingCost = GOLF_COURSE_VIEW;
     break;

     case (3):
        System.out.println("The condo with a lake view costs $" + LAKE_VIEW + ".");
        parkingCost = LAKE_VIEW;
     break;

     default:
        System.out.println("$0");
        parkingCost = 0;

  }

 System.out.println("Select 1 for a parking spot or 2 for a garage:");

  int parkingSpecification;
  parkingSpecification = input.nextInt();

  switch(parkingSpecification)

  {

     case (1):
        System.out.println("With a parking spot, the cost is $" + parkingCost);
     break;

     case (2):
        System.out.println("With a garage, the cost is $" + (parkingCost + 5000));
     break;

     default:
        System.out.println("You have entered an invalid response; the condo will cost $" + parkingCost + ".");
 }
 }
 }

Here is the test class which I have yet to figure out how to pass the price selection input through to the switch from the original class. Any help would be greatly appreciated, as I've been hitting my head against a wall trying to figure this out. Thanks!

import java.util.Scanner;

public class TestCondoSales

{

final int PARK_VIEW = 150000;
final int GOLF_COURSE_VIEW = 175000;
final int LAKE_VIEW = 210000;
int parkingCost;

public static void main(String[] args)

{

CondoSales methodRetrieval = new CondoSales();

System.out.println("Please select one of the following for pricing
information: " +
"1 for a condo with a park view, 2 for a condo with a golf course view, or 3
for a condo with a lake view.");

Scanner input = new Scanner(System.in);
int priceSelection;
priceSelection = input.nextInt();

methodRetrieval.priceReturn(priceSelection);

System.out.println("Select 1 for a parking spot or 2 for a garage:");

int parkingSpecification;
Scanner input2 = new Scanner(System.in);
parkingSpecification = input.nextInt();

methodRetrieval.parkingReturn(parkingSpecification);

}
}

Body:
Try using the switch criteria as a method parameter in another class, and then passing the input to that method.  For instance:

import java.util.Scanner;

public class CondoPriceSelector {

    public static void main(String[] args) {
        PriceSelector selector = new PriceSelector();
        try(Scanner scan = new Scanner(System.in)){
            int priceSelection = scan.nextInt();
            selector.printPrice(priceSelection);
        }
    }
}

class PriceSelector {
    final int parkingCost = 5000;

    public void printPrice(int selection) {
        switch (selection) {
            case (1):
                System.out.println("With a parking spot, the cost is $" + parkingCost);
                break;
            case (2):
                System.out.println("With a garage, the cost is $" + (parkingCost + 5000));
                break;

            default:
                System.out.println("You have entered an invalid response; the condo will cost $" + parkingCost + ".");
        }
    }
}


问:
Reference a field on a form within a query using SQL
I have an Access 2007 database that will be housing tables which refer to the bill of materials for multiple products.  On the main form I want a user to be able to select one of the products - OK, easy.  Now, I want two queries to run once they press a button after choosing their product from a dropdown.  The first query is a simple delete query to delete all information on a table.  The second query is where I'm having my issue with my SQL syntax.  I want the information from a static table to be appended to the table where the delete query just removed everything from.

Now, each table that houses the bill of material for each product is labeled with the product's name.  So I want the dropdown (combo0) to be the reference point for the table name in the FROM clause within the SQL string.  Code is as follows:

```<code>INSERT INTO tblTempSassyInfo (Concat, TableName, AddressName, PartNumber, [L/R], FeederSize, QtyPerBoard, SASSYname, RawBoard)
SELECT TableName & AddressName & PartNumber, TableName, AddressName, PartNumber, [L/R], FeederSize, QtyPerBoard, SassyName, RawBoard
FROM [FORMS]![DASHBOARD]![Combo0];
</code>```

So you can see where I'm trying to reference the product name in the dropdown on the form as the table name.  Please let me know if this is possible.

答:
This is 100% possible in MS Access 2010 onward based on my experience. I've not used 2007, but MS says it is possible (see link below). I'm using parametrized queries in a few databases.

```<code>PARAMETERS  [forms].[dash].[dt_val] DateTime;
SELECT a.F3 AS AdEnt, [forms].[dash].[dt_val] AS Expr1...
</code>```

The important thing I've found is using a form the user will be interacting with and setting the Date as "DateTime" within the parameter. Here is a video from Microsoft that shows how to and says that it applies to 2007.

Use Parameters in MS Access Queries

Additionally, if you want to do a delete or append, save it as a query then place a button on the form that executes the docmd.runquery for the name of that saved delete/append query.

Body:
I have an Access 2007 database that will be housing tables which refer to the bill of materials for multiple products.  On the main form I want a user to be able to select one of the products - OK, easy.  Now, I want two queries to run once they press a button after choosing their product from a dropdown.  The first query is a simple delete query to delete all information on a table.  The second query is where I'm having my issue with my SQL syntax.  I want the information from a static table to be appended to the table where the delete query just removed everything from.

Now, each table that houses the bill of material for each product is labeled with the product's name.  So I want the dropdown (combo0) to be the reference point for the table name in the FROM clause within the SQL string.  Code is as follows:

INSERT INTO tblTempSassyInfo (Concat, TableName, AddressName, PartNumber, [L/R], FeederSize, QtyPerBoard, SASSYname, RawBoard)
SELECT TableName & AddressName & PartNumber, TableName, AddressName, PartNumber, [L/R], FeederSize, QtyPerBoard, SassyName, RawBoard
FROM [FORMS]![DASHBOARD]![Combo0];

So you can see where I'm trying to reference the product name in the dropdown on the form as the table name.  Please let me know if this is possible.

Body:
This is 100% possible in MS Access 2010 onward based on my experience. I've not used 2007, but MS says it is possible (see link below). I'm using parametrized queries in a few databases.

PARAMETERS  [forms].[dash].[dt_val] DateTime;
SELECT a.F3 AS AdEnt, [forms].[dash].[dt_val] AS Expr1...

The important thing I've found is using a form the user will be interacting with and setting the Date as "DateTime" within the parameter. Here is a video from Microsoft that shows how to and says that it applies to 2007.

Use Parameters in MS Access Queries

Additionally, if you want to do a delete or append, save it as a query then place a button on the form that executes the docmd.runquery for the name of that saved delete/append query.


问:
Navigate between Screens
In my application,I have complex navigation.

I have Shopping Details .Which is View Controller of Tab bar controller.

When I select the any Store Name from Shopping Details View Controller .It will pop to a Shopping List View Controller which is embed in Navigation Controller.

When Select the Edit Button from Shopping List View Controller .It will pop to another View controller which ADD Screen. It is also embed in Navigation Controller

When I click save from Add Screen .It will go to the Shopping List View Controller

When I click Done button from the Shopping List View Controller  .I have to navigate to  Shopping Details View Controller of Tab bar controller.

Please provide me input. How to traverse to Tab Bar Controller ?

I have tried below Code. It is navigate to StoreDetails View Controller.Not displaying Tab Bar Items

```<code>let storeDetails = self.storyboard?.instantiateViewController(withIdentifier: "StoreDetailsController") as! StoreDetailsController
        storeDetails.managedContext = managedContext
        storeDetails.coreData = coreData
        storeDetails.back = true
self.navigationController?.pushViewController(storeDetails, animated: false)
</code>```

答:
From what i can tell you're trying to push the controller you originated from to the stack instead of poping back to it. It's a bit confusing to get the whole picture from your post, can you share that part of storyboard as a screenshot? Can you at least provide a diagram if you're not comfortable sharing the storyboard? Thanks.

EDIT:

For poping back to your controller you could use something like this:

```<code>for controller in (self.navigationController?.viewControllers)! {

  if let vc = controller as? StoreDetailsController {

    self.navigationController?.popToViewController(vc, animated: true)
  }
}
</code>```

But i really can't tell if you don't share at least the diagram on how your controllers are arranged and where are they embedded.

Title: Navigate between Screens

Body:
In my application,I have complex navigation.

I have Shopping Details .Which is View Controller of Tab bar controller.

When I select the any Store Name from Shopping Details View Controller .It will pop to a Shopping List View Controller which is embed in Navigation Controller.

When Select the Edit Button from Shopping List View Controller .It will pop to another View controller which ADD Screen. It is also embed in Navigation Controller

When I click save from Add Screen .It will go to the Shopping List View Controller

When I click Done button from the Shopping List View Controller  .I have to navigate to  Shopping Details View Controller of Tab bar controller.

Please provide me input. How to traverse to Tab Bar Controller ?

I have tried below Code. It is navigate to StoreDetails View Controller.Not displaying Tab Bar Items

let storeDetails = self.storyboard?.instantiateViewController(withIdentifier: "StoreDetailsController") as! StoreDetailsController
        storeDetails.managedContext = managedContext
        storeDetails.coreData = coreData
        storeDetails.back = true
self.navigationController?.pushViewController(storeDetails, animated: false)

Body:
From what i can tell you're trying to push the controller you originated from to the stack instead of poping back to it. It's a bit confusing to get the whole picture from your post, can you share that part of storyboard as a screenshot? Can you at least provide a diagram if you're not comfortable sharing the storyboard? Thanks.

EDIT:

For poping back to your controller you could use something like this:

for controller in (self.navigationController?.viewControllers)! {

  if let vc = controller as? StoreDetailsController {

    self.navigationController?.popToViewController(vc, animated: true)
  }
}

But i really can't tell if you don't share at least the diagram on how your controllers are arranged and where are they embedded.


问:
Build relay queries dynamically
I´m using Relay Modern as my client GraphQL interface. I wish to know if is possible to build my query statement dynamically inside Relay Modern, something like changing that original:

```<code>const ComponentQuery = graphql`
    query ComponentQuery ($companyId: ID!) {
        viewer {
            company(id: $companyId) {
                id
                name
                enabled
                users {
                    id
                    username
                    email
                    firstName
                    lastName
                    jobTitle
                    phone
                }
            }
        }
    }
`;
</code>```

To the following:

```<code>let queryFields = ['name', 'enabled'];
let userFields = ['username', 'email', 'firstName', 'lastName', 'jobTitle', 'phone' ];

const ComponentQuery = graphql`
    query ComponentQuery ($companyId: ID!) {
        viewer {
            company(id: $companyId) {
                id
                queryFields
                name
                enabled
                users {
                    id
                    userFields
                }
            }
        }
    }
`;
</code>```

Naturally, as the GraphQL Schema is static, the fields must all be present in the GraphQL schema. All I want is to build the query dynamically, not having a dynamic GraphQL schema.

答:
All your queries and mutations in Relay need to be statically available for the compiler to generate the runtime artifacts. Any dynamic behavior needs to be controlled by graphql variables and fragments. Make sure you look through the graphql spec well.

For your case above a fragment would serve you well. The fragment can even be defined in a different file. I will give an example where you define a child component called UserComponent that will be responsible for displaying user info and a fragment that specifies what fields are required. You can then use the fragment in the parent component query. Assuming you are using react and your user type is called User.

```<code>/UserComponent.js
...
const UserComponent = ({ user }) => {...};
...
export default createFragmentContainer(
  ChildComponent,
  graphql`
    fragment UserComponent_user on User {
      id
      username
      email
      firstName
      lastName
      jobTitle
      phone
    }
  `
);

/Component.js
const ComponentQuery = graphql`
query ComponentQuery ($companyId: ID!) {
  viewer {
    company(id: $companyId) {
      id
      name
      enabled
      users {
        ...UserComponent_user
      }
    }
  }
}`;
</code>```

Every time you need to render the UserComponent make sure you include that fragment in some top level query.

Title: Build relay queries dynamically

Body:
I´m using Relay Modern as my client GraphQL interface. I wish to know if is possible to build my query statement dynamically inside Relay Modern, something like changing that original:

const ComponentQuery = graphql`
    query ComponentQuery ($companyId: ID!) {
        viewer {
            company(id: $companyId) {
                id
                name
                enabled
                users {
                    id
                    username
                    email
                    firstName
                    lastName
                    jobTitle
                    phone
                }
            }
        }
    }
`;

To the following:

let queryFields = ['name', 'enabled'];
let userFields = ['username', 'email', 'firstName', 'lastName', 'jobTitle', 'phone' ];

const ComponentQuery = graphql`
    query ComponentQuery ($companyId: ID!) {
        viewer {
            company(id: $companyId) {
                id
                queryFields
                name
                enabled
                users {
                    id
                    userFields
                }
            }
        }
    }
`;

Naturally, as the GraphQL Schema is static, the fields must all be present in the GraphQL schema. All I want is to build the query dynamically, not having a dynamic GraphQL schema.

Body:
All your queries and mutations in Relay need to be statically available for the compiler to generate the runtime artifacts. Any dynamic behavior needs to be controlled by graphql variables and fragments. Make sure you look through the graphql spec well.

For your case above a fragment would serve you well. The fragment can even be defined in a different file. I will give an example where you define a child component called UserComponent that will be responsible for displaying user info and a fragment that specifies what fields are required. You can then use the fragment in the parent component query. Assuming you are using react and your user type is called User.

/UserComponent.js
...
const UserComponent = ({ user }) => {...};
...
export default createFragmentContainer(
  ChildComponent,
  graphql`
    fragment UserComponent_user on User {
      id
      username
      email
      firstName
      lastName
      jobTitle
      phone
    }
  `
);

/Component.js
const ComponentQuery = graphql`
query ComponentQuery ($companyId: ID!) {
  viewer {
    company(id: $companyId) {
      id
      name
      enabled
      users {
        ...UserComponent_user
      }
    }
  }
}`;

Every time you need to render the UserComponent make sure you include that fragment in some top level query.


问:
Hide horizontal off-screen overflow of a div that has a large width
How do I hide the horizontal, off-screen overflow of a
 that has a large width set on it? For example:

HTML:

```<code><div class="example">
</div>
</code>```

CSS:

```<code>.example {
  height: 100px;
  width: 10000px;
  background-color: black;
  position: absolute;
  overflow: hidden;
}
</code>```

Here is an example fiddle that shows the scrollbar appearing, I wish for that to not happen if the div is very large like this.

Edit: Adding hidden overflow-x on the parent element does not work on small width iOS devices.

答: You can use overflow-x: hidden in CSS to hidde only horizontal scroll.

Body:
How do I hide the horizontal, off-screen overflow of a
 that has a large width set on it? For example:

HTML:

CSS:

.example {
  height: 100px;
  width: 10000px;
  background-color: black;
  position: absolute;
  overflow: hidden;
}

Here is an example fiddle that shows the scrollbar appearing, I wish for that to not happen if the div is very large like this.

Edit: Adding hidden overflow-x on the parent element does not work on small width iOS devices.


问:
how to access object attributes of an array
I recently found out that in the chrome console I was able to do something really unusual.

Here's a simple example using an array of objects.

```<code>g = [{age: 23}, {age:33}];

g.foo = "bar";
> (2) [{…}, {…}, foo: "bar"]
</code>```

I think I'm able to do this because all js data structures are objects? Is there any way get access to foo:bar without knowing what it is beforehand?

```<code>g = g.filter(function(e){
          return e.age !== 33;
          });

> (2) [{…}]
</code>```

Specifically I'm trying to filter an array, without losing the object attributes that I set like foo:"bar".

The filtered arrays I'm getting back do not contain the object attributes I had before.

So my question is what is the best way to get access to attributes that I set on an array object when I treat it like an object in this strange way?

Ideally I could run something(g) and get back {foo: 'bar'}, or a list of all the props that exist on this object that aren't related to the array aspect of it.

Or is this just a super hacky idea and I shouldn't do it like this in the first place?

Thanks!

答:
This code get all enumeral keys in your object:

```<code> let g = [{age: 23}, {age:33}];

    g.foo = "bar";
    let keys = [];
    for(var x in g){
      keys.push(x);
    }
    console.log(keys)
</code>```

But this code get all keys( from prototype also), best way for get keys -use Object.keys(g)

If you want  get  all keys without prototype : use Object.getOwnPropertyNames(g)

Body:
I recently found out that in the chrome console I was able to do something really unusual.

Here's a simple example using an array of objects.

g = [{age: 23}, {age:33}];

g.foo = "bar";
> (2) [{…}, {…}, foo: "bar"]

I think I'm able to do this because all js data structures are objects? Is there any way get access to foo:bar without knowing what it is beforehand?

g = g.filter(function(e){
          return e.age !== 33;
          });

> (2) [{…}]

Specifically I'm trying to filter an array, without losing the object attributes that I set like foo:"bar".

The filtered arrays I'm getting back do not contain the object attributes I had before.

So my question is what is the best way to get access to attributes that I set on an array object when I treat it like an object in this strange way?

Ideally I could run something(g) and get back {foo: 'bar'}, or a list of all the props that exist on this object that aren't related to the array aspect of it.

Or is this just a super hacky idea and I shouldn't do it like this in the first place?

Thanks!

Body:
This code get all enumeral keys in your object:

 let g = [{age: 23}, {age:33}];

    g.foo = "bar";
    let keys = [];
    for(var x in g){
      keys.push(x);
    }
    console.log(keys)

But this code get all keys( from prototype also), best way for get keys -use Object.keys(g)

If you want  get  all keys without prototype : use Object.getOwnPropertyNames(g)


问:
converting units (ft to cm) entered as factors to integers in R
I'm trying write a function in R that converts heights entered in different units into centimeters.

In the dataframe, heights are either entered in centimeters (e.g. 175), meters, (e.g. 1.83), or feet and inches (e.g. 5ft4, or even 5ft9.5).
What I need to do is convert factors containing characters ("ft" or ".") into integers, but I have no idea how to approach this practically.

Any help would be more than welcome :)

答:
This might work.</p>

```<code>  library(dplyr)
  library(stringr)

  df <- tibble(measurementType = c("feet", "cm", "m"), height = c("5ft8.5", 175, 1.83))

  df %>% mutate(height = ifelse(measurementType == "feet",
                                 as.numeric(unlist(str_split(height, "ft"))[1]) * 12 + as.numeric(unlist(str_split(height, "ft"))[2]),
                                as.numeric(height))) %>%
       mutate(heightInCm = case_when(measurementType == "feet" ~ height * 2.54,
                                     measurementType == "m" ~ height * 100,
                                     TRUE ~ height))
</code>```

Body:
This might work.

  library(dplyr)
  library(stringr)

  df <- tibble(measurementType = c("feet", "cm", "m"), height = c("5ft8.5", 175, 1.83))

  df %>% mutate(height = ifelse(measurementType == "feet",
                                 as.numeric(unlist(str_split(height, "ft"))[1]) * 12 + as.numeric(unlist(str_split(height, "ft"))[2]),
                                as.numeric(height))) %>%
       mutate(heightInCm = case_when(measurementType == "feet" ~ height * 2.54,
                                     measurementType == "m" ~ height * 100,
                                     TRUE ~ height))


问:
Rails Query to show all posts that have no comments by current_user
I have an app that I need to see all the requests that have no quotes by the current user. I want to see Requests that have no quotes and requests that have quotes from other users.

For no quotes I have been using:

```<code>Request.includes(:quotes).where( quotes: { id: nil } ).order(created_at: :desc)
</code>```

and for the Where Not query I was using:

```<code>Requests.joins(:quotes).where.not(quotes: { service_center_id: current_service_center.id })
</code>```

This works with one quote. If I quote on a Request, the Request is no longer in the list, but as soon as someone else quotes it comes back into my list. It as if the query sees the other quotes are not by me so if shows the request, even though I have also quoted.

Here is a link to a Thoughtbot blog on where not that inspired me to look into models. Towards the bottom he does the same query. I have emailed the author but not reply yet.
https://robots.thoughtbot.com/activerecords-wherenot

Here are my models:

User:

```<code>devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable

validates :first_name,  presence: true
alidates :last_name,   presence: true
validates :zipcode,     presence: true

has_many :autos
has_many :requests
has_many :quotes, through: :requests
has_many :appointments, through: :quotes
</code>```

Request:

```<code>belongs_to :user
belongs_to :auto
has_many :quotes, dependent: :destroy
has_many :appointments, through: :quotes

validates :service, presence: true

serialize :service

validates_associated :quotes
</code>```

Quote:

```<code>belongs_to :request
belongs_to :service_center
</code>```

Service_center:

```<code>devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable

has_many :quotes
has_many :requests, through: :quotes
</code>```

答:
Here is how you can achieve your three goals.

Requests with no quotes:

```<code>Request.includes(:quotes).where( quotes: { id: nil } ).order(created_at: :desc)
</code>```

Requests with quotes from other service centers:

```<code>Requests.joins(:quotes).where.not(quotes: { service_center_id: current_service_center.id })
</code>```

Here is the answer to your question:

Requests with no quotes from your service center:

```<code>Request.where.not(
  id: Request.joins(:quotes)
        .where(quotes: { service_center_id: current_service_center.id })
        .select(:id)
)
</code>```

This is somewhat janky, but it should work.  The subquery gets all of the requests that have a quote from the current service center.  The outer query returns all of the requests that are not in the first list.  It should still run fast with one query in the database.

Another solution which will yield the same result is to use NOT EXISTS:

```<code>Request.joins(:quotes).where(
  Quote
    .where('requests.id = quotes.request_id')
    .where('quotes.service_center_id = ? ', current_service_center.id)
    .exists.not
)
</code>```

This will result in a NOT EXISTS subquery in SQL.  It should result in roughly the same performance as the other query.  I suppose it is just a matter of preference.

Body:
I have an app that I need to see all the requests that have no quotes by the current user. I want to see Requests that have no quotes and requests that have quotes from other users.

For no quotes I have been using:

Request.includes(:quotes).where( quotes: { id: nil } ).order(created_at: :desc)

and for the Where Not query I was using:

Requests.joins(:quotes).where.not(quotes: { service_center_id: current_service_center.id })

This works with one quote. If I quote on a Request, the Request is no longer in the list, but as soon as someone else quotes it comes back into my list. It as if the query sees the other quotes are not by me so if shows the request, even though I have also quoted.

Here is a link to a Thoughtbot blog on where not that inspired me to look into models. Towards the bottom he does the same query. I have emailed the author but not reply yet.
https://robots.thoughtbot.com/activerecords-wherenot

Here are my models:

User:

devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable

validates :first_name,  presence: true
alidates :last_name,   presence: true
validates :zipcode,     presence: true

has_many :autos
has_many :requests
has_many :quotes, through: :requests
has_many :appointments, through: :quotes

Request:

belongs_to :user
belongs_to :auto
has_many :quotes, dependent: :destroy
has_many :appointments, through: :quotes

validates :service, presence: true

serialize :service

validates_associated :quotes

Quote:

belongs_to :request
belongs_to :service_center

Service_center:

devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable

has_many :quotes
has_many :requests, through: :quotes

Body:
Here is how you can achieve your three goals.

Requests with no quotes:

Request.includes(:quotes).where( quotes: { id: nil } ).order(created_at: :desc)

Requests with quotes from other service centers:

Requests.joins(:quotes).where.not(quotes: { service_center_id: current_service_center.id })

Here is the answer to your question:

Requests with no quotes from your service center:

Request.where.not(
  id: Request.joins(:quotes)
        .where(quotes: { service_center_id: current_service_center.id })
        .select(:id)
)

This is somewhat janky, but it should work.  The subquery gets all of the requests that have a quote from the current service center.  The outer query returns all of the requests that are not in the first list.  It should still run fast with one query in the database.

Another solution which will yield the same result is to use NOT EXISTS:

Request.joins(:quotes).where(
  Quote
    .where('requests.id = quotes.request_id')
    .where('quotes.service_center_id = ? ', current_service_center.id)
    .exists.not
)

This will result in a NOT EXISTS subquery in SQL.  It should result in roughly the same performance as the other query.  I suppose it is just a matter of preference.


问:
Python: adding the same string to the end of each row
I'm modifying a CSV file with two fieldnames and I would like to add a string to the end of each row under an additional fieldname. I've figured out how to add the fieldname, but not how to add things to it. It seems like it should be simple, but I'm stumped.

```<code>import csv

with open('test2l.csv', 'r') as inny:
    reader = csv.DictReader(inny)

    with open('outfile.csv', 'w') as outty:
        fieldnames = ["Genus", "Species", "Source"]
        writer = csv.DictWriter(outty, fieldnames = fieldnames)
        writer.writeheader()

        for record in reader:
             g = record['Genus']
             s = record['Species']
</code>```

Everything I tried has just added the string to the existing string in 'Species' and I haven't been able to create a record for 'Source', I assume because it's empty.

Thanks!

答:
Simply write:

```<code>for record in reader:
    record["Source"] = "whateversource"
</code>```

And do so before the step where you are writing to a file.`

Body:
I'm modifying a CSV file with two fieldnames and I would like to add a string to the end of each row under an additional fieldname. I've figured out how to add the fieldname, but not how to add things to it. It seems like it should be simple, but I'm stumped.

import csv

with open('test2l.csv', 'r') as inny:
    reader = csv.DictReader(inny)

    with open('outfile.csv', 'w') as outty:
        fieldnames = ["Genus", "Species", "Source"]
        writer = csv.DictWriter(outty, fieldnames = fieldnames)
        writer.writeheader()

        for record in reader:
             g = record['Genus']
             s = record['Species']

Everything I tried has just added the string to the existing string in 'Species' and I haven't been able to create a record for 'Source', I assume because it's empty.

Thanks!

Body:
Simply write:

for record in reader:
    record["Source"] = "whateversource"

And do so before the step where you are writing to a file.`


问:
I need a code which sums different numbers
I got a very difficult assignment as I am new to python, I hope you will be able to help me.
I wrote this code:

```<code>def hours_per_student(student_course,course_hours):
    new={}
    for key in student_course.keys():
        for val in student_course.values():
               for m in range(len(val)):
                   if not new.has_key(key):
                        new[key]=course_hours[val[m]]
                   else:
                        new[key]=new[key]+course_hours[val[m]]

    return new
</code>```

for these dictionaries:

```<code>student_course = {'rina' : ['math', 'python'], 'yossi' : ['chemistry', 'biology'], 'riki' : ['python']}
course_hours = {'math' : 4, 'python' : 4, 'chemistry' : 6, 'biology' : 5}
</code>```

And I need to get this:

```<code>hours_per_student(student_course, course_hours)
</code>```

to return this:

```<code>{'rina': 8, 'yossi': 11, 'riki': 4}
</code>```

But I keep getting identical numbers for each key.

答:
Here are the things I found lacking in your code:

When iterating over your students, you could have just created a key for each of them, and then add the hours per course.

Naming variables so you understand what they mean is confused, refrain from using new, key or val.

You don't have to use keys() function, iterating a dictionary using for key in dictionary works the same way.

Here's a fixed code snippet:

```<code>def hours_per_student(students, course_hours):
    total_hours = {}
    for student in students:
        courses = students[student]
        total_hours[student] = 0
        for course in courses:
            total_hours[student] += course_hours[course]
    return total_hours
</code>```

Body:
I got a very difficult assignment as I am new to python, I hope you will be able to help me.
I wrote this code:

def hours_per_student(student_course,course_hours):
    new={}
    for key in student_course.keys():
        for val in student_course.values():
               for m in range(len(val)):
                   if not new.has_key(key):
                        new[key]=course_hours[val[m]]
                   else:
                        new[key]=new[key]+course_hours[val[m]]

    return new

for these dictionaries:

student_course = {'rina' : ['math', 'python'], 'yossi' : ['chemistry', 'biology'], 'riki' : ['python']}
course_hours = {'math' : 4, 'python' : 4, 'chemistry' : 6, 'biology' : 5}

And I need to get this:

hours_per_student(student_course, course_hours)

to return this:

{'rina': 8, 'yossi': 11, 'riki': 4}

But I keep getting identical numbers for each key.

Body:
Here are the things I found lacking in your code:

When iterating over your students, you could have just created a key for each of them, and then add the hours per course.

Naming variables so you understand what they mean is confused, refrain from using new, key or val.

You don't have to use keys() function, iterating a dictionary using for key in dictionary works the same way.

Here's a fixed code snippet:

def hours_per_student(students, course_hours):
    total_hours = {}
    for student in students:
        courses = students[student]
        total_hours[student] = 0
        for course in courses:
            total_hours[student] += course_hours[course]
    return total_hours


问:
How to change Redmine to support versioned files in every issue
Its redmine, a Ruby on Rails application. Currently, every issue can have one or more files. But if a user decide to update/change them, the old files are replaced. My task is to develop something to allow versioned files for every issue: so, if a user update the content of an existing issue, the previous state of the issue is preserved and it can be displayed in some form.

I'm new to RoR and Redmine development.

答:
I guess the best thing in this case is to modify Redmine so that instead of uploading files to the issue, you put the files into a subversion repository and then add a link in the issue.

Alternatively, allow multiple files to be added, and modify to code to rename them everytime one is uploaded - appending a suffix (_1, _2 etc) to each filename.

ContentLicense: CC BY-SA 2.5


问:
android create drawable that is intersection between circle and rectangle
I would like to create an android xml drawable. That is the intersection between a circle and a rectangle.

Basically, i would like to have a rectangle. And then on the corner of this rectangle, draw a circle.

I would like to have the intersection of these two shapes to be used for a background.

This circle should have a radius slightly less than the height of the rectangle. So the intersection is not just 1/4 of the circle.

Is this something that can be created in a XML drawable in android?

Here is a very poorly drawn image using a trackpad..

The rectangle is what I would like to have for my background image. The shaded area should be able to have some color that I can change manually in the xml.

答:
I would use a <vector> drawable here.

```<code><vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="80dp"
    android:viewportWidth="48"
    android:viewportHeight="80">

    <path
        android:pathData="M48 0 a80 80 0 1 0 0.1 0z"
        android:fillColor="#caf"/>

</vector>
</code>```

You can then apply this to your layout using the android:background attribute:

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/circle_rect_intersection"
    ...>
</code>```

You can even tint it (to get different colors) using android:backgroundTint on your root view.

Body:
I would use a <vector> drawable here.

<vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="80dp"
    android:viewportWidth="48"
    android:viewportHeight="80">

    <path
        android:pathData="M48 0 a80 80 0 1 0 0.1 0z"
        android:fillColor="#caf"/>

</vector>

You can then apply this to your layout using the android:background attribute:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/circle_rect_intersection"
    ...>

You can even tint it (to get different colors) using android:backgroundTint on your root view.


问:
Linking a specific library with gcc
This may be a basic question, but how do you find what library you need to link against with gcc? I am trying to compile a shared library that uses #include <signal.h>, but when I try to use it, it gives me a CANNOT LINK EXECUTABLE because it can't locate any of the symbols.
I am assuming I have to link specifically against the library with the flag -l in gcc, but I don't know where/what that library is.

At a more broad example, -ldl links against libdl.so, what -l can I use to link against the #include <signal.h>?

EDIT:

```<code>soinfo_link_image(linker.cpp:1617): could not load library "mylib.so" needed by "/bin/test";
cause by soinfo_relocate(linker.cpp:975): cannot locate symbol "signal" referenced by "mylib.so"...CANNOT LINK EXECUTABLE
</code>```

Compiled using:

```<code>gcc -fPIC -c -g -o mylib.o mylib.c
gcc -shared -o mylib.so mylib.o -ldl
</code>```

答:
This is more of a linker question than a GCC question.  Often, the library name is mentioned in the library documentation.  On GNU/Linux distributions, many libraries have .pc files for pkg-config.  If not, you can use commands such as

```<code>dpkg -S /usr/include/signal.h
</code>```

and

```<code>rpm -qf /usr/include/signal.h
</code>```

to find the -dev/-devel packages which provided the header file, and then proceed to look at

```<code>dpkg -L libc6-dev
</code>```

or

```<code>rpm -ql glibc-devel
</code>```

output to determine the name of the .so files used for linking.  Defined symbols can be viewed using objdump -T, nm -Dg, or eu-readelf --symbols=.dynsym (so many choices).

Title: Linking a specific library with gcc

Body:
This may be a basic question, but how do you find what library you need to link against with gcc? I am trying to compile a shared library that uses #include <signal.h>, but when I try to use it, it gives me a CANNOT LINK EXECUTABLE because it can't locate any of the symbols.
I am assuming I have to link specifically against the library with the flag -l in gcc, but I don't know where/what that library is.

At a more broad example, -ldl links against libdl.so, what -l can I use to link against the #include <signal.h>?

EDIT:

soinfo_link_image(linker.cpp:1617): could not load library "mylib.so" needed by "/bin/test";
cause by soinfo_relocate(linker.cpp:975): cannot locate symbol "signal" referenced by "mylib.so"...CANNOT LINK EXECUTABLE

Compiled using:

gcc -fPIC -c -g -o mylib.o mylib.c
gcc -shared -o mylib.so mylib.o -ldl

Body:
This is more of a linker question than a GCC question.  Often, the library name is mentioned in the library documentation.  On GNU/Linux distributions, many libraries have .pc files for pkg-config.  If not, you can use commands such as

dpkg -S /usr/include/signal.h

and

rpm -qf /usr/include/signal.h

to find the -dev/-devel packages which provided the header file, and then proceed to look at

dpkg -L libc6-dev

or

rpm -ql glibc-devel

output to determine the name of the .so files used for linking.  Defined symbols can be viewed using objdump -T, nm -Dg, or eu-readelf --symbols=.dynsym (so many choices).


答:
You shouldn't be iterating over .values() if you're already iterating over .keys(), just use the key to get the value. Or where you have for m in len(val), just do for m in val and then reference m instead of val[m](the naming here stinks but I discuss that later). Python is much better at iteration than that. For instance, instead of the line

```<code>for val in student_course.values():
</code>```

you should try something like

```<code>for courses in student_course[key]:
    for course in courses:
        if key not in new:
            new[key] = course_hours[course]
        else:
            new[key] += course_hours[course]
</code>```

Naming your variables intelligently will make it easier for you to keep track of what's happening. For example, each value in student_course is a list of courses, so you should name it that, not something ambiguous like val. Similarly, each element in courses is the name of a course, so name it as such.

Title: I need a code which sums different numbers

Body:
You shouldn't be iterating over .values() if you're already iterating over .keys(), just use the key to get the value. Or where you have for m in len(val), just do for m in val and then reference m instead of val[m](the naming here stinks but I discuss that later). Python is much better at iteration than that. For instance, instead of the line

for val in student_course.values():

you should try something like

for courses in student_course[key]:
    for course in courses:
        if key not in new:
            new[key] = course_hours[course]
        else:
            new[key] += course_hours[course]

Naming your variables intelligently will make it easier for you to keep track of what's happening. For example, each value in student_course is a list of courses, so you should name it that, not something ambiguous like val. Similarly, each element in courses is the name of a course, so name it as such.


问:
How to prevent IntelliJ to stop continuing double-slash comments on the next line?
Short version

When pressing <enter> at the end of a // comment, Intellij sometimes decides to continue the // comment on the next line.  How can I prevent that?  Is there a setting somewhere to disable this automation?

Long version

There is a thing I do regularily, it is to break a long expression with a double-slash.

Let's say I have a line like

```<code>boolean isHex = c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
</code>```

and I want to split it like that

```<code>boolean isHex = c >= '0' && c <= '9' //
        || c >= 'A' && c <= 'F' //
        || c >= 'a' && c <= 'f';
</code>```

Note that I want the final // in order to prevent any formatter to join the lines again.

So I insert a double-slash-return after the '9', by pressing //<enter>.  But Intellij will auto-continue the comment on the next line.

```<code>boolean isHex = c >= '0' && c <= '9' //
// || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
</code>```

It forces me to uncomment and reindent the line manually.

I want Intellij to not continue the comment on the next line and optionally indent my code:

```<code>boolean isHex = c >= '0' && c <= '9' //
        || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
</code>```

So I want to disable this "continue // comment after <enter>" feature.  Is it possible?  I haven't found any setting related to that.

答: Go to Settings → Code Style → Java → Wrapping and Braces and check "Line breaks" under "Keep when reformatting". This will make IntelliJ's formatter respect any manual line breaks, even if they contradict other formatting rules.

Body:
Short version

When pressing <enter> at the end of a // comment, Intellij sometimes decides to continue the // comment on the next line.  How can I prevent that?  Is there a setting somewhere to disable this automation?

Long version

There is a thing I do regularily, it is to break a long expression with a double-slash.

Let's say I have a line like

boolean isHex = c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';

and I want to split it like that

boolean isHex = c >= '0' && c <= '9' //
        || c >= 'A' && c <= 'F' //
        || c >= 'a' && c <= 'f';

Note that I want the final // in order to prevent any formatter to join the lines again.

So I insert a double-slash-return after the '9', by pressing //<enter>.  But Intellij will auto-continue the comment on the next line.

boolean isHex = c >= '0' && c <= '9' //
// || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';

It forces me to uncomment and reindent the line manually.

I want Intellij to not continue the comment on the next line and optionally indent my code:

boolean isHex = c >= '0' && c <= '9' //
        || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';

So I want to disable this "continue // comment after <enter>" feature.  Is it possible?  I haven't found any setting related to that.


问:
how to display state inside input tag
I'm building the following react component and trying to add hidden to my input box.

```<code>class FontChooser extends React.Component {

constructor(props) {
super(props);
this.state={display:'hidden'};
}

render() {

return(
       <div>
          <input type="checkbox" id="boldCheckbox" this.state.display />
       </div>
);
}
}
</code>```

I also tried {this.state.display} but I get unexpected token

答:
If you specifically need hidden as a prop on the tag, to show in your code like <input type="checkbox" id="boldCheckbox" hidden />, which I believe that's what you're asking...you have to make a slight change to your code:

```<code>constructor(props) {
  super(props);
  this.state = {
    display: {
      hidden: undefined
    }
  };
}

render() {
  return (
    <div>
      <input type="checkbox" id="boldCheckbox" {...this.state.display} />
    </div>
  )
}
</code>```

In order to hide, you set the state of hidden under display to anything not null or undefined.

So: this.setState({display: { hidden: <STATECHANGE>}})

Title: how to display state inside input tag

Body:
I'm building the following react component and trying to add hidden to my input box.

class FontChooser extends React.Component {

constructor(props) {
super(props);
this.state={display:'hidden'};
}

render() {

return(

          <input type="checkbox" id="boldCheckbox" this.state.display />

);
}
}

I also tried {this.state.display} but I get unexpected token

Body:
If you specifically need hidden as a prop on the tag, to show in your code like <input type="checkbox" id="boldCheckbox" hidden />, which I believe that's what you're asking...you have to make a slight change to your code:

constructor(props) {
  super(props);
  this.state = {
    display: {
      hidden: undefined
    }
  };
}

render() {
  return (
    <div>
      <input type="checkbox" id="boldCheckbox" {...this.state.display} />
    </div>
  )
}

In order to hide, you set the state of hidden under display to anything not null or undefined.

So: this.setState({display: { hidden: <STATECHANGE>}})


问:
ASP.NET MVC 5 : persisting variables in Controller
I instantiate the 'plate' object in the GET request of the view and then access it when the form is posted. The plate object is populated with the data from the form. Can I also use it to store the passed coordinates? Or what is the idiomatic way of doing what I'm trying to achieve?

Thanks!

```<code>public class DrawingController : Controller
{

        Plate plate;

        [HttpGet]
        public ActionResult Index()
        {
            plate = new Plate()
            {
              Holes = new Holes()
            }
            return View(plate);
        }

        // called by ajax when user clicks on "Save" to save the input coordinates
        [HttpPost]
        public void PassCoordinates(string coordinates)
        {
          // why is plate null here?
          plate.Holes.coordinates = coordinates;
        }

        [HttpPost]
        public ActionResult Index(Plate plate)
        {
         // I want to access plate.Holes.coordinates that I set in 'PassCoordinates'
         // how can I achieve this?
        }
}
</code>```

答:
What you see is the expected behavior, because Http is stateless.

Every time you make a call to your action method, a new object of the controller will be created. So in your case when you make the ajax call, it will create a new object of the DrawingController and this object will have a property of type Plate, but is not initialized to a Plate object. (which you do in your Index method call)

If you want to get the same plate instance, in your PassCoordinates action method you can do in different ways

Have your ajax call post the js object of Plate structure and have a parameter in your action method of Plate type. when the request is submitted, the model binder will be able to build the new object and map the values of different proeprties

Store the Plate object in a persistent meedium and read it. So in your Index action method, you will create the object, intialize the proprety values and store it to a db table/Session state etc. You can read it again from this place in your second action method.  Using a Static variable is another option

If you are going for the option #2 and choose to use Session/Static variable, keep in mind that you are trying to add stateful behavior to the stateless http. :(

IMHO, Option 1 is the way to go. Keep the stateless behavior of Http. Have your client code (the code which makes the ajax call) send the JS object representing the plate object and have the model binder build the object for you.

When i am looking at your code, the only thing PassCoordinates method is doing is, simply setting the Holes.coordinates property value of the Plate object (which you though will be available in the controller). You can totally remove that method and make sure that you do that in the input elements in your form so that when you submit the form to the HttpPost index action method, it will be available in the request body and model binder will map it to your Plate  parameter.

```<code>@model Plate
@using (Html.BeginForm("Index", "Home"))
{
     @Html.TextBoxFor(a=>a.Holes.coordinates)
    <button type="submit" class="btn" >Save</button>
}
</code>```

This will create an input element with name Holes.coordinates inside the form.

```<code><input id="Holes_coordinates" name="Holes.coordinates" type="text" value="">
</code>```

Enter some value to it and submit the form. Now if you put a breakpoint in the HttpPost action method, you can see that your plate objects Hole proprety is populated and you can access the value you entered in the text box in the coordinates property.

Now all you have to do is, whatever client side code was making the ajax call, instead of making the ajax call, set the value of this input.

```<code>$("#Holes_coordinates").val("some value you want");
</code>```

Once everything is working, you can convert the visible text box to a hidden input by simply switching the call to HiddenFor helper.

```<code>@Html.HiddenFor(a=>a.Holes.coordinates)
</code>```

Body:
I instantiate the 'plate' object in the GET request of the view and then access it when the form is posted. The plate object is populated with the data from the form. Can I also use it to store the passed coordinates? Or what is the idiomatic way of doing what I'm trying to achieve?

Thanks!

public class DrawingController : Controller
{

        Plate plate;

        [HttpGet]
        public ActionResult Index()
        {
            plate = new Plate()
            {
              Holes = new Holes()
            }
            return View(plate);
        }

        // called by ajax when user clicks on "Save" to save the input coordinates
        [HttpPost]
        public void PassCoordinates(string coordinates)
        {
          // why is plate null here?
          plate.Holes.coordinates = coordinates;
        }

        [HttpPost]
        public ActionResult Index(Plate plate)
        {
         // I want to access plate.Holes.coordinates that I set in 'PassCoordinates'
         // how can I achieve this?
        }
}

Body:
What you see is the expected behavior, because Http is stateless.

Every time you make a call to your action method, a new object of the controller will be created. So in your case when you make the ajax call, it will create a new object of the DrawingController and this object will have a property of type Plate, but is not initialized to a Plate object. (which you do in your Index method call)

If you want to get the same plate instance, in your PassCoordinates action method you can do in different ways

Have your ajax call post the js object of Plate structure and have a parameter in your action method of Plate type. when the request is submitted, the model binder will be able to build the new object and map the values of different proeprties

Store the Plate object in a persistent meedium and read it. So in your Index action method, you will create the object, intialize the proprety values and store it to a db table/Session state etc. You can read it again from this place in your second action method.  Using a Static variable is another option

If you are going for the option #2 and choose to use Session/Static variable, keep in mind that you are trying to add stateful behavior to the stateless http. :(

IMHO, Option 1 is the way to go. Keep the stateless behavior of Http. Have your client code (the code which makes the ajax call) send the JS object representing the plate object and have the model binder build the object for you.

When i am looking at your code, the only thing PassCoordinates method is doing is, simply setting the Holes.coordinates property value of the Plate object (which you though will be available in the controller). You can totally remove that method and make sure that you do that in the input elements in your form so that when you submit the form to the HttpPost index action method, it will be available in the request body and model binder will map it to your Plate  parameter.

@model Plate
@using (Html.BeginForm("Index", "Home"))
{
     @Html.TextBoxFor(a=>a.Holes.coordinates)
    <button type="submit" class="btn" >Save</button>
}

This will create an input element with name Holes.coordinates inside the form.

<input id="Holes_coordinates" name="Holes.coordinates" type="text" value="">

Enter some value to it and submit the form. Now if you put a breakpoint in the HttpPost action method, you can see that your plate objects Hole proprety is populated and you can access the value you entered in the text box in the coordinates property.

Now all you have to do is, whatever client side code was making the ajax call, instead of making the ajax call, set the value of this input.

$("#Holes_coordinates").val("some value you want");

Once everything is working, you can convert the visible text box to a hidden input by simply switching the call to HiddenFor helper.

@Html.HiddenFor(a=>a.Holes.coordinates)


问:
What is an easy way to stub / dummy a restful web service?
I want to create an android application, this application will make RESTful calls to a web service to obtain some data.

I know what the RESTful interface will be, but I don't want the hassle of creating my own implementation. Is there an easy way to create a stub RESTful web service that will return some static data without having to write a full blown WS application to do this?

答:
Beeceptor (disclaimer, I'm the author) shall help you for the exact use-case here. Create an API endpoint, define a mock path and response. Use it in hackathons to build mock APIs in seconds.

Beeceptor is more than a mocking service. It is an HTTP proxy for APIs. For example, if you have a real API, use the real API as ultimate target. Beecetor intercepts traffic and using rules,

when rules are matched, APIs are mocked

when no rule matches, your target endpoint is hit as usual.

With Mocky.io, you shall have different API paths, with Beeceptor your base URL is going to be same all the time.


问:
Package destination of restore of .net-core projects is always global package directory
We have a solution in which some projects are .net-core projects and some are "normal" .net 4.6.1 projects.
On solution level we have a NuGet.config-File which sets the repositoryPath:

```<code><configuration>
  <config>
    <add key="repositoryPath" value="packages" />
  </config>
</configuration>
</code>```

The packages listed in the projects packages.config-Files are getting downloaded into the path specified in Nuget.config -> repositoryPath but the packages specified in the .net-core Project files (via PackageReference) are all downloaded into the global package directory in C:\Users\USERNAME\.nuget\packages.

It doesn't matter if i use Visual Studio 2017 or do it manually via nuget.exe.
The .net-core projects just ignore the NuGet.config.

What are we doing wrong here?

答:
Okay. Got it. Adding the following tag to the .csproj file does the trick:

    <PropertyGroup>
      ...
      <RestorePackagesPath>packages</RestorePackagesPath>
    </PropertyGroup>
```

Source: https://github.com/NuGet/Home/wiki/%5BSpec%5D-NuGet-settings-in-MSBuild

Body:
We have a solution in which some projects are .net-core projects and some are "normal" .net 4.6.1 projects.
On solution level we have a NuGet.config-File which sets the repositoryPath:

<configuration>
  <config>
    <add key="repositoryPath" value="packages" />
  </config>
</configuration>

The packages listed in the projects packages.config-Files are getting downloaded into the path specified in Nuget.config -> repositoryPath but the packages specified in the .net-core Project files (via PackageReference) are all downloaded into the global package directory in C:\Users\USERNAME\.nuget\packages.

It doesn't matter if i use Visual Studio 2017 or do it manually via nuget.exe.
The .net-core projects just ignore the NuGet.config.

What are we doing wrong here?

Body:
Okay. Got it. Adding the following tag to the .csproj file does the trick:

    <PropertyGroup>
      ...
      <RestorePackagesPath>packages</RestorePackagesPath>
    </PropertyGroup>

Source: https://github.com/NuGet/Home/wiki/%5BSpec%5D-NuGet-settings-in-MSBuild

ContentLicense: CC BY-SA 4.0


问:
Webpack AngularJS Sourcemaps issue
I've been struggling with getting my source-maps working in my app for quite a while. I have set

```<code>devtool:  'source-map',
</code>```

in the webpack configuration, but they are still not available in the Chrome devtools.

I pushed a really simple app using my FE Stack hoping someone could identify the issue, whether it is with webpack, angular, or some other library. https://github.com/coreysnyder/Angular-Webpack3-Seed

Here are the versions I'm running:

```<code>{
  CoreyApp: '1.0.0',
  npm: '4.4.4',
  ares: '1.10.1-DEV',
  http_parser: '2.7.0',
  icu: '57.1',
  modules: '48',
  node: '6.9.0',
  openssl: '1.0.2j',
  uv: '1.9.1',
  v8: '5.1.281.84',
  zlib: '1.2.8'
}
OSX 10.12.6
</code>```

答:
You will probably have to setup source map for different loaders individually.

For 'ng-annotate-loader' (Docs)

```<code>use: [{
    loader: 'ng-annotate-loader',
    options: {
        add: true,
        single_quotes: true ,
        map: { inline: true, inFile: 'app.js', sourceRoot: __dirname + '/app' }}
}]
</code>```

For less you can use documentation option like @ahmedelgabri suggested

```<code>use: [{
    loader: "style-loader"
}, {
    loader: "css-loader", options: {
        sourceMap: true
    }
}, {
    loader: "less-loader", options: {
        sourceMap: true
    }
}]
</code>```

Old post before OP github changes.

Other option is to add devtoolLineToLine: true in your output, if you want to use devtool: 'source-map'. But devtoolLineToLine is deprecated, so consider changing devtool to something else.  devtool: 'source-map' demo image

```<code>output: isTest ? {} : {
    devtoolLineToLine: true, // <= this line

    sourceMapFilename: '[name].map',
    path: __dirname + '/dist',
    filename: '[name].bundle.js',
    publicPath: publicPath
},
</code>```

Alternatively you could use devtool: 'eval' or some variation of eval, like cheap-module-eval-source-map (similar behavior, but without file names) also works fine for me

Title: Webpack AngularJS Sourcemaps issue

Body:
I've been struggling with getting my source-maps working in my app for quite a while. I have set

devtool:  'source-map',

in the webpack configuration, but they are still not available in the Chrome devtools.

I pushed a really simple app using my FE Stack hoping someone could identify the issue, whether it is with webpack, angular, or some other library. https://github.com/coreysnyder/Angular-Webpack3-Seed

Here are the versions I'm running:

{
  CoreyApp: '1.0.0',
  npm: '4.4.4',
  ares: '1.10.1-DEV',
  http_parser: '2.7.0',
  icu: '57.1',
  modules: '48',
  node: '6.9.0',
  openssl: '1.0.2j',
  uv: '1.9.1',
  v8: '5.1.281.84',
  zlib: '1.2.8'
}
OSX 10.12.6

Body:
You will probably have to setup source map for different loaders individually.

For 'ng-annotate-loader' (Docs)

use: [{
    loader: 'ng-annotate-loader',
    options: {
        add: true,
        single_quotes: true ,
        map: { inline: true, inFile: 'app.js', sourceRoot: __dirname + '/app' }}
}]

For less you can use documentation option like @ahmedelgabri suggested

use: [{
    loader: "style-loader"
}, {
    loader: "css-loader", options: {
        sourceMap: true
    }
}, {
    loader: "less-loader", options: {
        sourceMap: true
    }
}]

Old post before OP github changes.

Other option is to add devtoolLineToLine: true in your output, if you want to use devtool: 'source-map'. But devtoolLineToLine is deprecated, so consider changing devtool to something else.  devtool: 'source-map' demo image

output: isTest ? {} : {
    devtoolLineToLine: true, // <= this line

    sourceMapFilename: '[name].map',
    path: __dirname + '/dist',
    filename: '[name].bundle.js',
    publicPath: publicPath
},

Alternatively you could use devtool: 'eval' or some variation of eval, like cheap-module-eval-source-map (similar behavior, but without file names) also works fine for me


问:
firebase dataSnapshot.getValue(String.class) returns null
Trying to get "Dio" from char_data

```<code>private View.OnClickListener saveBtnList;
    {
        saveBtnList = new View.OnClickListener() {
            public void onClick(View v) {
                characterName = (EditText)findViewById(R.id.charNameXML);
                str = characterName.getText().toString();

                DatabaseReference ref = charNameDatabaseReference.child("User/char_data");

                if(str.length() > 0) {
                    final CharacterInfoAdapter CIAdapter = new CharacterInfoAdapter(str);
                    charNameDatabaseReference.child("User/char_data").setValue(CIAdapter);

                    ref.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            String value = dataSnapshot.child("User/char_data").getValue(String.class);
                            System.out.println("You ight... Character Name is: " + value);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            System.out.println("You Thought :3");
                        }
                    });

                }
                saved = true;
                intent = new Intent(basic_info.this, character_select.class);
            }
        };
    }
</code>```

The issue that I run into is that I can update the database but can’t pull the information as it always returns null. If I use String value = dataSnapshot.getValue(String.class) I get a cannot convert Hash to String error.

答:
```<code>public void onDataChange(DataSnapshot dataSnapshot) {
    String value = null;
    for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
        value = postSnapshot.getValue(String.class);
    }
    System.out.println("You ight... Character Name is: " + value);
}
</code>```

<p>----instead of------</p>

```<code>public void onDataChange(DataSnapshot dataSnapshot) {
                        String value = dataSnapshot.child("User/char_data").getValue(String.class);
                        System.out.println("You ight... Character Name is: " + value);
                    }
</code>```

Body:
Trying to get "Dio" from char_data

private View.OnClickListener saveBtnList;
    {
        saveBtnList = new View.OnClickListener() {
            public void onClick(View v) {
                characterName = (EditText)findViewById(R.id.charNameXML);
                str = characterName.getText().toString();

                DatabaseReference ref = charNameDatabaseReference.child("User/char_data");

                if(str.length() > 0) {
                    final CharacterInfoAdapter CIAdapter = new CharacterInfoAdapter(str);
                    charNameDatabaseReference.child("User/char_data").setValue(CIAdapter);

                    ref.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            String value = dataSnapshot.child("User/char_data").getValue(String.class);
                            System.out.println("You ight... Character Name is: " + value);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            System.out.println("You Thought :3");
                        }
                    });

                }
                saved = true;
                intent = new Intent(basic_info.this, character_select.class);
            }
        };
    }

The issue that I run into is that I can update the database but can’t pull the information as it always returns null. If I use String value = dataSnapshot.getValue(String.class) I get a cannot convert Hash to String error.

Body:
public void onDataChange(DataSnapshot dataSnapshot) {
    String value = null;
    for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
        value = postSnapshot.getValue(String.class);
    }
    System.out.println("You ight... Character Name is: " + value);
}

----instead of------

public void onDataChange(DataSnapshot dataSnapshot) {
                        String value = dataSnapshot.child("User/char_data").getValue(String.class);
                        System.out.println("You ight... Character Name is: " + value);
                    }


问:
Order array of strings based on a portion of each string
How can i order an array from this:

```<code>$unordered_array = array('11196311|3','17699636|13','11196111|0','156875|2','17699679|6','11196237|7','3464760|10');
</code>```

To this

```<code>$ordered_array = array('11196111', '156875', '11196311', '17699679','11196237','3464760', '17699636');
</code>```

The number after the "|" defines the position, and the array needs to be ordered from lower to higher, and remove the position number in the final array.

答:
Why you don't try by yourself ? You take more writing your answer than doing it by yourself.</p>

```<code>$array = array();
foreach($unordered_array as $value) {
    $value = explode('|', $value);
    $array [$value[1]]= $value[0];
}
ksort($array);
$ordered_array = array_values($array);

var_dump($ordered_array);
</code>```

Body:
How can i order an array from this:

$unordered_array = array('11196311|3','17699636|13','11196111|0','156875|2','17699679|6','11196237|7','3464760|10');

To this

$ordered_array = array('11196111', '156875', '11196311', '17699679','11196237','3464760', '17699636');

The number after the "|" defines the position, and the array needs to be ordered from lower to higher, and remove the position number in the final array.

Body:
Why you don't try by yourself ? You take more writing your answer than doing it by yourself.

$array = array();
foreach($unordered_array as $value) {
    $value = explode('|', $value);
    $array [$value[1]]= $value[0];
}
ksort($array);
$ordered_array = array_values($array);

var_dump($ordered_array);


问:
Algorithm to multiply edges of a Networkx graph
So my problem is to find the longest path from a node to another node (or the same node) in a graph implemented with Networkx library.

I don't want to add the edges' weights but multiply them and take the biggest result. Obviously, passing only once by each node or not at all.

For example if I want to go from node 1 to node 4, the best result would be : 2 x 14 x 34 x 58

Graph example

Thank you for your help !

答:
This may work:

```<code>import networkx as nx

G = nx.Graph()

# create the graph
G.add_edge(1, 2, weight=2 )
G.add_edge(1, 4, weight=5 )
G.add_edge(2, 3, weight=14 )
G.add_edge(2, 4, weight=5 )
G.add_edge(2, 5, weight=4 )
G.add_edge(3, 5, weight=34 )
G.add_edge(4, 5, weight=58 )

start = 1 # start node
end = 4   # end node

all_paths = [path for path in nx.all_simple_paths(G, start, end)]

# initialize result
largest_path = None
largest_path_weight = None

# iterate through all paths to find the largest
for p in all_paths:                                       # keep track of each path
    for _ in range(len(p)):                               # for each node in this path
        pairs = zip(p, p[1:])                             # get sequence of nodes
        product = 1                                       # reset product for this paths calculation
        for pair in pairs:                                # for each pair of nodes in this path
            an_edge = G.get_edge_data(pair[0], pair[1])   # get this edge's data
            product *= an_edge['weight']                  # multiply all weights
    if product > largest_path_weight:                     # check if this path's product is greater
        largest_path = p                                  # if True, set largest to this path
        largest_path_weight = product                     # save the weight of this path

# display result
print 'largest path:', largest_path
print 'weight:', largest_path_weight
</code>```

for this example:

```<code>largest path: [1, 2, 3, 5, 4]
weight: 55216
</code>```

Body:
This may work:

import networkx as nx

G = nx.Graph()

# create the graph
G.add_edge(1, 2, weight=2 )
G.add_edge(1, 4, weight=5 )
G.add_edge(2, 3, weight=14 )
G.add_edge(2, 4, weight=5 )
G.add_edge(2, 5, weight=4 )
G.add_edge(3, 5, weight=34 )
G.add_edge(4, 5, weight=58 )

start = 1 # start node
end = 4   # end node

all_paths = [path for path in nx.all_simple_paths(G, start, end)]

# initialize result
largest_path = None
largest_path_weight = None

# iterate through all paths to find the largest
for p in all_paths:                                       # keep track of each path
    for _ in range(len(p)):                               # for each node in this path
        pairs = zip(p, p[1:])                             # get sequence of nodes
        product = 1                                       # reset product for this paths calculation
        for pair in pairs:                                # for each pair of nodes in this path
            an_edge = G.get_edge_data(pair[0], pair[1])   # get this edge's data
            product *= an_edge['weight']                  # multiply all weights
    if product > largest_path_weight:                     # check if this path's product is greater
        largest_path = p                                  # if True, set largest to this path
        largest_path_weight = product                     # save the weight of this path

# display result
print 'largest path:', largest_path
print 'weight:', largest_path_weight

for this example:

largest path: [1, 2, 3, 5, 4]
weight: 55216


问:
Reference a .Net 4.6.2 project in a .NetCore project (VS2017 15.4.4)
I have a .Net core 2.0 project which needs to reference a .Net 4.6.2 projets (BLL and Entities on the picture) in the same solution on Visual Studio 2017 (v 15.4.4). I saw this post, but event with .Net version 4.6.2, I still have the problem.

In my .Net core 2.0 project references, I have:

When I try to use a class defined in .Net 4.6.2 projects, I have following error: "Cannot resolve symbole 'BLL'" (for BLL project).

Do you have any idea what to do to use .Net 4.6.2 project in a net core 2.0 project?

答:
As user magicandre1981 said, you should downgrade from .NET Framework version 4.6.2 to 4.6.1.

Taking a look at the .NET Standard version table, you can see that version 4.6.1 is supported by .NET Standard 2.0 (and thus .NET Core 2.0), but 4.6.2 is not listed (therefore not supported).

For those unable to click through, I took the following screen shot of the table presented on the above linked page:

(image is correct as on Nov 17, 2017)

I'd also recommend taking a look through the documentation for the .NET Standard or at the videos that Immo Landwerth (who is the PM in charge of .NET Standard) has put out about it.


答:
Here you go:</p>

```<code>solution = {student: sum([hours.get(course, 0) for course in s_courses]) for student, s_courses in student_course.items()}
</code>```

Body:
I got a very difficult assignment as I am new to python, I hope you will be able to help me.
I wrote this code:

def hours_per_student(student_course,course_hours):
    new={}
    for key in student_course.keys():
        for val in student_course.values():
               for m in range(len(val)):
                   if not new.has_key(key):
                        new[key]=course_hours[val[m]]
                   else:
                        new[key]=new[key]+course_hours[val[m]]

    return new

for these dictionaries:

student_course = {'rina' : ['math', 'python'], 'yossi' : ['chemistry', 'biology'], 'riki' : ['python']}
course_hours = {'math' : 4, 'python' : 4, 'chemistry' : 6, 'biology' : 5}

And I need to get this:

hours_per_student(student_course, course_hours)

to return this:

{'rina': 8, 'yossi': 11, 'riki': 4}

But I keep getting identical numbers for each key.

Body:
Here you go:

solution = {student: sum([hours.get(course, 0) for course in s_courses]) for student, s_courses in student_course.items()}


问:
Hide horizontal off-screen overflow of a div that has a large width
How do I hide the horizontal, off-screen overflow of a
 that has a large width set on it? For example:

HTML:

```<code><div class="example">
</div>
</code>```

CSS:

```<code>.example {
  height: 100px;
  width: 10000px;
  background-color: black;
  position: absolute;
  overflow: hidden;
}
</code>```

Here is an example fiddle that shows the scrollbar appearing, I wish for that to not happen if the div is very large like this.

Edit: Adding hidden overflow-x on the parent element does not work on small width iOS devices.

答:
You're nearly there!

Setting the overflow of the .example class is only hiding any overflowing content inside of it, though.

You would need to set the overflow of the parent container of .example, for this to work - i.e. whatever container it is inside of.

As you mentioned in your OP, you want to hide horizontal scrollbars.

For this, you would need to set

```<code>overflow-x: hidden
</code>```

But (as mentioned), be sure this is on the parent container of .example.

This could be the body, or another div etc. HTH.

e.g.:

```<code>body, .parent-container {
    overflow-x: hidden;
}
</code>```

Body:
How do I hide the horizontal, off-screen overflow of a
 that has a large width set on it? For example:

HTML:

CSS:

.example {
  height: 100px;
  width: 10000px;
  background-color: black;
  position: absolute;
  overflow: hidden;
}

Here is an example fiddle that shows the scrollbar appearing, I wish for that to not happen if the div is very large like this.

Edit: Adding hidden overflow-x on the parent element does not work on small width iOS devices.

Body:
You're nearly there!

Setting the overflow of the .example class is only hiding any overflowing content inside of it, though.

You would need to set the overflow of the parent container of .example, for this to work - i.e. whatever container it is inside of.

As you mentioned in your OP, you want to hide horizontal scrollbars.

For this, you would need to set

overflow-x: hidden

But (as mentioned), be sure this is on the parent container of .example.

This could be the body, or another div etc. HTH.

e.g.:

body, .parent-container {
    overflow-x: hidden;
}


问:
Is nesting ARM Thumb2 "IT" instructions well defined?
If I have an ARM Thumb 2 instruction stream that looks like the following:

```<code>itt NZ
mov r1,r2
it MI
mov r3,r4
</code>```

The IT block of the first IT instruction contains mov and a second it. Is this sequence allowable, or is it undefined behavior?

答: An IT block must not contain another IT instruction. The result of your code is unpredictable.</p>

Body:
If I have an ARM Thumb 2 instruction stream that looks like the following:

itt NZ
mov r1,r2
it MI
mov r3,r4

The IT block of the first IT instruction contains mov and a second it. Is this sequence allowable, or is it undefined behavior?


问:
using postgreSQL and jsondb in the same web app
My site is written in ruby (rails) and it's very easy to persist the results of an offsite json feed with using jsondb, so I have an app that would benefit from this, but I think I'd like to keep the rest of the site running on postgrs

Would I be better off moving everything to one database (jsondb?) or does rails easily allow me to use multiple ORM's in the same app

```<code># just notes, ignore if you like cos the answers are subjective
# Perhaps I should build two web apps?
</code>```

答:
Sometimes it is practical to use multiple databases.

I'd take a hard look at the tenacity gem, which was introduced recently as a way to manage multiple databases within Rails .. and even relationships between them.

It doesn't look like it currently supports jsondb, but given its architecture, it should be possible to write your own adapter (... and then contribute it back?)

OwnerDisplayName: stephenmurdoch

Body:
My site is written in ruby (rails) and it's very easy to persist the results of an offsite json feed with using jsondb, so I have an app that would benefit from this, but I think I'd like to keep the rest of the site running on postgrs

Would I be better off moving everything to one database (jsondb?) or does rails easily allow me to use multiple ORM's in the same app

# just notes, ignore if you like cos the answers are subjective
# Perhaps I should build two web apps?