问:
VertX and Log4j cannot get configuration
I am working with VertX, I want to use Log4J as logger for my code and for the exthernal libraries.

So I wrote down this piece of code:

```<code>import org.apache.log4j.Logger;

public class Main extends AbstractVerticle {

   final static Logger logger = Logger.getLogger("Gimli");

   @Override
   public void start(Future<Void> fut) throws Exception {
      System.setProperty("vertx.logger-delegate-factory-class-name", " io.vertx.core.logging.Log4j2LogDelegateFactory"); // Default logger

    logger.debug("Debug log");
    logger.error("Error log");
    logger.warn("Warning log");
  }
}
</code>```

and I put into src/main/resources the file log4j.xml

```<code><?xml version="1.0" encoding="UTF-8" ?>
<Configuration>
  <Appenders>
    <RollingFile name="app_file" append="true" fileName="/var/log/seachlog.log" filePattern="/var/log/vertx/$${date:yyyy-MM}/seachlog-%d{MM-dd-yyyy}-%i.log.gz">
        <PatternLayout pattern="%d{ISO8601} %-5p %c:%L - %m%n" />
        <Policies>
            <OnStartupTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="5MB" />
            <TimeBasedTriggeringPolicy />
        </Policies>
    </RollingFile>
    <RollingFile name="vertx_file" append="true" fileName="/var/log/vertx.log" filePattern="/var/log/vertx/$${date:yyyy-MM}/vertx-%d{MM-dd-yyyy}-%i.log.gz">
        <PatternLayout pattern="%d{ISO8601} %-5p %c:%L - %m%n" />
        <Policies>
            <OnStartupTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="5MB" />
            <TimeBasedTriggeringPolicy />
        </Policies>
    </RollingFile>
    <Console name="STDOUT" target="SYSTEM_OUT">
        <!-- <LogStashJSONLayout/> -->
        <PatternLayout pattern="%d{ISO8601} %-5p %c:%L - sfsdfsdfsdfsdf %m%n" />
    </Console>
</Appenders>

<Loggers>
    <Logger name="Gimli" level="DEBUG">
        <!-- <AppenderRef ref="vertx_rollingFile" /> -->
        <!-- <AppenderRef ref="vertx_socket" /> -->
        <AppenderRef ref="STDOUT"/>
        <AppenderRef ref="vertx_file" />
    </Logger>
    <Root level="DEBUG">
        <!-- <AppenderRef ref="vertx_socket" /> -->
        <AppenderRef ref="STDOUT"/>
        <AppenderRef ref="app_file" />
    </Root>
</Loggers>
</code>```

But the output seems not changing:

```<code>2017-12-09 09:21:34,503 DEBUG [vert.x-eventloop-thread-0] [Gimli] Debug log (Main.java:31)
2017-12-09 09:21:34,505 ERROR [vert.x-eventloop-thread-0] [Gimli] Error log (Main.java:32)
2017-12-09 09:21:34,507 WARN  [vert.x-eventloop-thread-0] [Gimli] Warning log (Main.java:33)
</code>```

How can I set the configuration file correctly?

答:
First of all it looks like you are combining log4j with log4j2 config file. That could be reason why your config is not loaded.

But I recommend to use vert.x logging feature - you can use log4j or log4j2 with it too. You will define your loggers as this:

```<code>import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

Logger logger = LoggerFactory.getLogger("Gimli");
</code>```

then use this normally as you did. so:

```<code>logger.debug("Debug log");
logger.error("Error log");
logger.warn("Warning log");
</code>```

next you will keep your config in src/main/resources. Just be careful because this is log4j2 config. So it should be named log4j2.xml.

And now you just need to specify logger delegate factory for vertx. For log4j or log4j2 its:

```<code>io.vertx.core.logging.Log4jLogDelegateFactory
</code>```

or

```<code>io.vertx.core.logging.Log4j2LogDelegateFactory
</code>```

you can setup system property vertx.logger-delegate-factory-class-name or you can specify VM argument as this:

```<code>-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.Log4j2LogDelegateFactory
</code>```

(for log4j2)

More info in documentation

Body:
I am working with VertX, I want to use Log4J as logger for my code and for the exthernal libraries.

So I wrote down this piece of code:

import org.apache.log4j.Logger;

public class Main extends AbstractVerticle {

   final static Logger logger = Logger.getLogger("Gimli");

   @Override
   public void start(Future<Void> fut) throws Exception {
      System.setProperty("vertx.logger-delegate-factory-class-name", " io.vertx.core.logging.Log4j2LogDelegateFactory"); // Default logger

    logger.debug("Debug log");
    logger.error("Error log");
    logger.warn("Warning log");
  }
}

and I put into src/main/resources the file log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<Configuration>
  <Appenders>
    <RollingFile name="app_file" append="true" fileName="/var/log/seachlog.log" filePattern="/var/log/vertx/$${date:yyyy-MM}/seachlog-%d{MM-dd-yyyy}-%i.log.gz">
        <PatternLayout pattern="%d{ISO8601} %-5p %c:%L - %m%n" />
        <Policies>
            <OnStartupTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="5MB" />
            <TimeBasedTriggeringPolicy />
        </Policies>
    </RollingFile>
    <RollingFile name="vertx_file" append="true" fileName="/var/log/vertx.log" filePattern="/var/log/vertx/$${date:yyyy-MM}/vertx-%d{MM-dd-yyyy}-%i.log.gz">
        <PatternLayout pattern="%d{ISO8601} %-5p %c:%L - %m%n" />
        <Policies>
            <OnStartupTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="5MB" />
            <TimeBasedTriggeringPolicy />
        </Policies>
    </RollingFile>
    <Console name="STDOUT" target="SYSTEM_OUT">

        <PatternLayout pattern="%d{ISO8601} %-5p %c:%L - sfsdfsdfsdfsdf %m%n" />
    </Console>
</Appenders>

<Loggers>
    <Logger name="Gimli" level="DEBUG">

        <AppenderRef ref="STDOUT"/>
        <AppenderRef ref="vertx_file" />
    </Logger>
    <Root level="DEBUG">

        <AppenderRef ref="STDOUT"/>
        <AppenderRef ref="app_file" />
    </Root>
</Loggers>

But the output seems not changing:

2017-12-09 09:21:34,503 DEBUG [vert.x-eventloop-thread-0] [Gimli] Debug log (Main.java:31)
2017-12-09 09:21:34,505 ERROR [vert.x-eventloop-thread-0] [Gimli] Error log (Main.java:32)
2017-12-09 09:21:34,507 WARN  [vert.x-eventloop-thread-0] [Gimli] Warning log (Main.java:33)

How can I set the configuration file correctly?

Body:
First of all it looks like you are combining log4j with log4j2 config file. That could be reason why your config is not loaded.

But I recommend to use vert.x logging feature - you can use log4j or log4j2 with it too. You will define your loggers as this:

import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

Logger logger = LoggerFactory.getLogger("Gimli");

then use this normally as you did. so:

logger.debug("Debug log");
logger.error("Error log");
logger.warn("Warning log");

next you will keep your config in src/main/resources. Just be careful because this is log4j2 config. So it should be named log4j2.xml.

And now you just need to specify logger delegate factory for vertx. For log4j or log4j2 its:

io.vertx.core.logging.Log4jLogDelegateFactory

or

io.vertx.core.logging.Log4j2LogDelegateFactory

you can setup system property vertx.logger-delegate-factory-class-name or you can specify VM argument as this:

-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.Log4j2LogDelegateFactory

(for log4j2)

More info in documentation


来源: stackexchange

问:
How can I change locale programmatically with Swift
I am making ios app on XCODE 6.3 by Swift.
And my app will have the choose language function like the image below

I already have storyboard for my local language.
But i can't find out how to change the localization programmatically off the app by the button.

Anyone know how to do it

答:
Here is an updated answer for Swift 4</p>

```<code>let language = "es" // replace with Locale code
guard let path = Bundle.main.path(forResource: language, ofType: "lproj") else {
  return self
}
guard let bundle = Bundle(path: path) else {
  return self
}
return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is an updated answer for Swift 4

let language = "es" // replace with Locale code
guard let path = Bundle.main.path(forResource: language, ofType: "lproj") else {
  return self
}
guard let bundle = Bundle(path: path) else {
  return self
}
return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")

ContentLicense: CC BY-SA 3.0


问:
How to update table based on count of entries of another table
I've table as below

```<code>Sample
 Source | Action |   DueDate            | Status
  A        Act_1    08DEC2017:00:00:00     Open
  A        Act_1    09DEC2017:00:00:00     closed
  A        Act_2    09DEC2017:00:00:00     Open
  A        Act_2    09DEC2017:00:00:00     closed
  A        Act_3    09DEC2017:00:00:00     Open
  B        Act_1    09DEC2017:00:00:00     Open
  B        Act_2    09DEC2017:00:00:00     closed
</code>```

I want to  add data in my final table according to the count of entries of each Action with respect to the source.

my final table as

```<code>final
 Source | Action | Total_Received | Total_closed | OverDue
   A       Act_1      2                1              1
   A       Act_2      2                1              0
   A       Act_3      1                0              0
   B       Act_1      1                0              0
   B       Act_2      1                1              0
</code>```

Total_Received is Total number of entries/rows

Total_Closed   is Total number of closed entries

Total_overdue  is Total number of open entries whose DueDate is passed

date of this time is 9DEC2017

Kindly tell me to update my table dynamically because there can be many Source types and Action Types in my system.

Have a nice day.

答:
First let's turn your data listing into a dataset so we have an example to code from.

```<code>data sample;
  input source $ action $ duedate :datetime. status $ ;
  format duedate datetime20.;
cards;
  A  Act_1  08DEC2017:00:00:00 Open
  A  Act_1  09DEC2017:00:00:00 closed
  A  Act_2  09DEC2017:00:00:00 Open
  A  Act_2  09DEC2017:00:00:00 closed
  A  Act_3  09DEC2017:00:00:00 Open
  B  Act_1  09DEC2017:00:00:00 Open
  B  Act_2  09DEC2017:00:00:00 closed
;
</code>```

Counting records that meet a condition is easy in PROC SQL because SAS will evaluate boolean expressions to 1/0 values. So you can just SUM() the result to get a count of the number that are true.  If you want to compare datetime values to a date you need to convert one or the other.  I have used a date literal below but if you want today's date you could use the DATE() function.

```<code>proc sql ;
create table final as
select
  source
 ,action
 ,count(*) as Total_Received
 ,sum( status='closed' ) as Total_Closed
 ,sum( status='Open' and datepart(duedate)< '09DEC2017'd) as OverDue
from sample
group by 1,2
;
quit;
</code>```

Body:
I've table as below

Sample
 Source | Action |   DueDate            | Status
  A        Act_1    08DEC2017:00:00:00     Open
  A        Act_1    09DEC2017:00:00:00     closed
  A        Act_2    09DEC2017:00:00:00     Open
  A        Act_2    09DEC2017:00:00:00     closed
  A        Act_3    09DEC2017:00:00:00     Open
  B        Act_1    09DEC2017:00:00:00     Open
  B        Act_2    09DEC2017:00:00:00     closed

I want to  add data in my final table according to the count of entries of each Action with respect to the source.

my final table as

final
 Source | Action | Total_Received | Total_closed | OverDue
   A       Act_1      2                1              1
   A       Act_2      2                1              0
   A       Act_3      1                0              0
   B       Act_1      1                0              0
   B       Act_2      1                1              0

Total_Received is Total number of entries/rows

Total_Closed   is Total number of closed entries

Total_overdue  is Total number of open entries whose DueDate is passed

date of this time is 9DEC2017

Kindly tell me to update my table dynamically because there can be many Source types and Action Types in my system.

Have a nice day.

Body:
First let's turn your data listing into a dataset so we have an example to code from.

data sample;
  input source $ action $ duedate :datetime. status $ ;
  format duedate datetime20.;
cards;
  A  Act_1  08DEC2017:00:00:00 Open
  A  Act_1  09DEC2017:00:00:00 closed
  A  Act_2  09DEC2017:00:00:00 Open
  A  Act_2  09DEC2017:00:00:00 closed
  A  Act_3  09DEC2017:00:00:00 Open
  B  Act_1  09DEC2017:00:00:00 Open
  B  Act_2  09DEC2017:00:00:00 closed
;

Counting records that meet a condition is easy in PROC SQL because SAS will evaluate boolean expressions to 1/0 values. So you can just SUM() the result to get a count of the number that are true.  If you want to compare datetime values to a date you need to convert one or the other.  I have used a date literal below but if you want today's date you could use the DATE() function.

proc sql ;
create table final as
select
  source
 ,action
 ,count(*) as Total_Received
 ,sum( status='closed' ) as Total_Closed
 ,sum( status='Open' and datepart(duedate)< '09DEC2017'd) as OverDue
from sample
group by 1,2
;
quit;


问:
How to change asp.net DropDownList SelectedValue using javascript?
I have three dropdownlist controls in my asp.net web app project from which the user will choose items. What I want is that the user must not choose the same values, meaning that the value selected in the one Dropdownlist can not be selected in the other dropdownlist, and if the user tries to select the same value I want to reset the selectedValue property to that dropdownlist. Is there anyway I can achieve this using javascript? It's better to make it on the client side.

Thank you!

The Dropdownlist Looks like this: Image here

答:
First add same class name  in all three dropdowns. e.g
'class=dropdownClass'

Add dropdown Number as attribute in all
three dropdowns -> 'dropdownNo=1' , 'dropdownNo=2' , 'dropdownNo=3'

Also add ids (it must be different)-> dropdownId1 , dropdownId2 ,
dropdownId3 respectivitely

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

$('.dropdownClass').on('change', function () {
    //when ever any dropdown change (class name is same)
    //get the attribe no

    var CurrentdropdownNo = $(this).attr('dropdownNo')
    var CurrentdropdownValue = $(this).val();

    if (CurrentdropdownNo == 1) {
        var value2 =  $('#dropdownId2').val() ;
        var value3 =  $('#dropdownId3').val() ;
       //check with dropdown 2,3
        if (CurrentdropdownValue == value2 || CurrentdropdownValue == value3)
        {
            //reset the current dropdown
            //do stuff here , what you want
        }

   }
    if (CurrentdropdownNo == 2) {
        var value1 = $('#dropdownId1').val();
        var value3 = $('#dropdownId3').val();
        //check with dropdown 1,3
        if (CurrentdropdownValue == value1 || CurrentdropdownValue == value3) {
            //reset the current dropdown
            //do stuff here , what you want
        }
   }
    if (CurrentdropdownNo == 3) {
        var value1 = $('#dropdownId1').val();
        var value2 = $('#dropdownId2').val();
       //check with dropdown 1,2
        if (CurrentdropdownValue == value1 || CurrentdropdownValue == value2) {
            //reset the current dropdown
            //do stuff here , what you want
        }

   }

})
</code>```

})

Note: Change class name Or id name as want ..

Body:
First add same class name  in all three dropdowns. e.g
'class=dropdownClass'

Add dropdown Number as attribute in all
three dropdowns -> 'dropdownNo=1' , 'dropdownNo=2' , 'dropdownNo=3'

Also add ids (it must be different)-> dropdownId1 , dropdownId2 ,
dropdownId3 respectivitely

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

$('.dropdownClass').on('change', function () {
    //when ever any dropdown change (class name is same)
    //get the attribe no

    var CurrentdropdownNo = $(this).attr('dropdownNo')
    var CurrentdropdownValue = $(this).val();

    if (CurrentdropdownNo == 1) {
        var value2 =  $('#dropdownId2').val() ;
        var value3 =  $('#dropdownId3').val() ;
       //check with dropdown 2,3
        if (CurrentdropdownValue == value2 || CurrentdropdownValue == value3)
        {
            //reset the current dropdown
            //do stuff here , what you want
        }

   }
    if (CurrentdropdownNo == 2) {
        var value1 = $('#dropdownId1').val();
        var value3 = $('#dropdownId3').val();
        //check with dropdown 1,3
        if (CurrentdropdownValue == value1 || CurrentdropdownValue == value3) {
            //reset the current dropdown
            //do stuff here , what you want
        }
   }
    if (CurrentdropdownNo == 3) {
        var value1 = $('#dropdownId1').val();
        var value2 = $('#dropdownId2').val();
       //check with dropdown 1,2
        if (CurrentdropdownValue == value1 || CurrentdropdownValue == value2) {
            //reset the current dropdown
            //do stuff here , what you want
        }

   }

})

})

Note: Change class name Or id name as want ..


问:
columns with same name but other with calculated one Linq
I have data in database like

```<code>1     CP     12
2     OB     8
1     CP     19
3     AB     22
2     OB     33
1     CP     19
3     AB     22
</code>```

What I want after running query on it

```<code>2     OB     41
1     CP     60
3     AB     44
</code>```

What I tried

```<code> var abc = db.OilVolumes.GroupBy(x => new { x.OilType.OilTypeName, x.Weight }).Select(y => new
{
oilType = y.Key.OilTypeName,
weight = y.Sum(z => z.Weight)
});
</code>```

But I failed... Give me a in similar format

Thanks

答:
Remove x.Weight from your GroupBy

```<code>var abc = db.OilVolumes.GroupBy(x => new { x.OilType.OilTypeName }).Select(y => new
    {
     oilType = y.Key.OilTypeName,
     weight = y.Sum(z => z.Weight)
    });
</code>```

Body:
I have data in database like

1     CP     12
2     OB     8
1     CP     19
3     AB     22
2     OB     33
1     CP     19
3     AB     22

What I want after running query on it

2     OB     41
1     CP     60
3     AB     44

What I tried

 var abc = db.OilVolumes.GroupBy(x => new { x.OilType.OilTypeName, x.Weight }).Select(y => new
{
oilType = y.Key.OilTypeName,
weight = y.Sum(z => z.Weight)
});

But I failed... Give me a in similar format

Thanks

Body:
Remove x.Weight from your GroupBy

var abc = db.OilVolumes.GroupBy(x => new { x.OilType.OilTypeName }).Select(y => new
    {
     oilType = y.Key.OilTypeName,
     weight = y.Sum(z => z.Weight)
    });


问:
Symfony form hidden relation to foreign entity
I am trying to create a form in symfony 3. It has a hidden field for a relation to another entity. It is defined as

```<code>$builder->add('course', HiddenType::class, array('property_path' => 'course.id'))
</code>```

Doing so when i submit the form i get an error, because the id property is not visible and there's no setter obviously.

```<code>Could not determine access type for property "id".
</code>```

What should i do? Adding a setter for id would probably be a bad idea. There's a reason why there is none by default. Other fields than the id are not unique so i cannot use any of those.

I guess one option might be a custom type, that queries the database for the referring entity. But is there a simpler way for this pretty standard use case?

Edit

Okay obviously my question was misunderstood. So i'll explain better. It's not about Doctrine. My Datamodel is fine, the field is a proper relation and not something else. The problem is only about the Symfony Form component, specifically that HiddenField seemingly cannot handle a relation by default. First it would result in an error upon display of the Form Cannot serialize type Model to string, which i can solve with the property_path directive for the display of the form. But once it is submitted it cannot create the related entity because it cannot set the id property (see the property_path) of the related doctrine entity.

A working solution is to use a DataTransformerInterface class instead of something like the property path. But one must implement one for every entity needed. So i was wondering if there was a easier solution because it seemed to me to be a pretty standard usecase.

答:
Here is what i did:

I used a Symfony\Component\Form\DataTransformerInterface on the field, to serialize the model and then upon form transmission load it again from the database via doctrine. Probably not what everybody wants in every case and also means the form needs the entity manager as an option.

In the form

```<code>/**
 * Some form
 */
class SomeType extends AbstractType
{
    // Configure
    public function configureOptions(OptionsResolver $resolver) {
        [...]
        $resolver->setRequired('entity_manager');
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('course', HiddenType::class);

        [...]

        $builder->get('course')
           ->addModelTransformer(new CourseTransformer($options['entity_manager']));
    }
}
</code>```

And here is the CourseTransformer

```<code>class CourseTransformer implements DataTransformerInterface
{
    // The object manager
    private $manager;

    //Constructor
    public function __construct(ObjectManager $manager) {
        $this->manager = $manager;
    }

    /**
     * Transforms an object (course) to a string (id).
     */
    public function transform($course)
    {
        if (null === $course) return '';
        return $course->getId();
    }

    /**
     * Transforms a string (id) to an object (course).
     */
    public function reverseTransform($courseId)
    {
        // no course id? It's optional, so that's ok
        if (!$courseId) {
            return;
        }

        $course = $this->manager
            ->getRepository('MyBundle:Course')
            // query for the issue with this id
            ->find($courseId)
        ;

        if (null === $course) {
            // causes a validation error
            // this message is not shown to the user
            throw new TransformationFailedException(sprintf(
                'An course with id "%s" does not exist!',
                $courseId
            ));
        }

        return $course;
    }
}
</code>```

Body:
I am trying to create a form in symfony 3. It has a hidden field for a relation to another entity. It is defined as

$builder->add('course', HiddenType::class, array('property_path' => 'course.id'))

Doing so when i submit the form i get an error, because the id property is not visible and there's no setter obviously.

Could not determine access type for property "id".

What should i do? Adding a setter for id would probably be a bad idea. There's a reason why there is none by default. Other fields than the id are not unique so i cannot use any of those.

I guess one option might be a custom type, that queries the database for the referring entity. But is there a simpler way for this pretty standard use case?

Edit

Okay obviously my question was misunderstood. So i'll explain better. It's not about Doctrine. My Datamodel is fine, the field is a proper relation and not something else. The problem is only about the Symfony Form component, specifically that HiddenField seemingly cannot handle a relation by default. First it would result in an error upon display of the Form Cannot serialize type Model to string, which i can solve with the property_path directive for the display of the form. But once it is submitted it cannot create the related entity because it cannot set the id property (see the property_path) of the related doctrine entity.

A working solution is to use a DataTransformerInterface class instead of something like the property path. But one must implement one for every entity needed. So i was wondering if there was a easier solution because it seemed to me to be a pretty standard usecase.

Body:
Here is what i did:

I used a Symfony\Component\Form\DataTransformerInterface on the field, to serialize the model and then upon form transmission load it again from the database via doctrine. Probably not what everybody wants in every case and also means the form needs the entity manager as an option.

In the form

/**
 * Some form
 */
class SomeType extends AbstractType
{
    // Configure
    public function configureOptions(OptionsResolver $resolver) {
        [...]
        $resolver->setRequired('entity_manager');
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('course', HiddenType::class);

        [...]

        $builder->get('course')
           ->addModelTransformer(new CourseTransformer($options['entity_manager']));
    }
}

And here is the CourseTransformer

class CourseTransformer implements DataTransformerInterface
{
    // The object manager
    private $manager;

    //Constructor
    public function __construct(ObjectManager $manager) {
        $this->manager = $manager;
    }

    /**
     * Transforms an object (course) to a string (id).
     */
    public function transform($course)
    {
        if (null === $course) return '';
        return $course->getId();
    }

    /**
     * Transforms a string (id) to an object (course).
     */
    public function reverseTransform($courseId)
    {
        // no course id? It's optional, so that's ok
        if (!$courseId) {
            return;
        }

        $course = $this->manager
            ->getRepository('MyBundle:Course')
            // query for the issue with this id
            ->find($courseId)
        ;

        if (null === $course) {
            // causes a validation error
            // this message is not shown to the user
            throw new TransformationFailedException(sprintf(
                'An course with id "%s" does not exist!',
                $courseId
            ));
        }

        return $course;
    }
}


问:
Can guava be used for reflection on classes that are loaded by name?
In this question I was referred to guava as a solution for reflection on generics, and it looks awesome except that I get errors trying to use this on classes loaded by name:

```<code>Class clazz = Class.forName("net.redpoint.scratch.Derived");
TypeToken tt = new TypeToken(clazz) {};
</code>```

This results in the error: java.lang.IllegalArgumentException: class com.google.common.reflect.TypeToken isn't parameterized

Is there some way to use TypeToken without having the class at compile-time?  Note that I also do not have source to these classes.

答: As M Prokhorov says, "use TypeToken.of(class)"</p>

Body:
In this question I was referred to guava as a solution for reflection on generics, and it looks awesome except that I get errors trying to use this on classes loaded by name:

Class clazz = Class.forName("net.redpoint.scratch.Derived");
TypeToken tt = new TypeToken(clazz) {};

This results in the error: java.lang.IllegalArgumentException: class com.google.common.reflect.TypeToken isn't parameterized

Is there some way to use TypeToken without having the class at compile-time?  Note that I also do not have source to these classes.


问:
JS alert function executed before if condition modifying the DOM even though alert is inside if . Why?
Why in this jQuery example, jsFiddle alert function is executed before jquery modifying the .parent's background even though if(p.css('background-color', 'yellow')) is evaluated first.

CSS

```<code>.parent {
  width: 400px;
  padding: 10px;
  margin: 10px;
  border: 1px solid;
  background-color: green;
}
</code>```

HTML

```<code><div class="parent">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti qui esse illum, unde labore. Repellendus sunt, quidem eligendi aliquid architecto animi officia itaque ducimus impedit, enim laudantium quis, cupiditate optio.</div>
</code>```

jQuery

```<code>var p = $('.parent');
p.css('border', '3px solid blue');

if(p.css('background-color', 'yellow')){
    alert('cool')
  } else {
  alert( 'Not COOL')
  }
</code>```

jsFiddle

Thanks

答:
The browser does not update the graphics when you modify the DOM. It only does so when there's no more javascript to execute. This process is called reflow.

Basically this is how the browser works:

Event loop
    ┌──────────┐
    │          │
    │          │
    │          ▼
    │        check if there's any new ───────▶ parse data
    │        data on the network                    │
    │          │                                    │
    │          ▼                                    │
    │        check if we need to execute  ◀─────────┘
    │        any javascript ──────────────────▶ execute
    │          │                               javascript
    │          ▼                                  │
    │        check if we need to ◀────────────────┘
    │        redraw the page  ──────────────▶ redraw page
    │          │                                   │
    │          │                                   │
    └────◀─────┴─────────────────◀─────────────────┘
```

However, by definition the alert() function does not wait for reflow and interrupts the execution of javascript.

Therefore when you change the background color to yellow the following happens:

DOM is modified and the background is changed to yellow

Alert is called and the alert dialog is displayed

Other bits of javascript is executed until there's nothing else to execute

Reflow is triggered and the browser finally draws the yellow background to screen

Reflow behaves this way as an optimization. Constantly redrawing everything potentially slows down browsers so even if reflow isn't described by the specification the very fact that Microsoft, Mozilla, Google and Apple are constantly competing to be the best browser means the over time reflow becomes more and more a batch process.

Body:
Why in this jQuery example, jsFiddle alert function is executed before jquery modifying the .parent's background even though if(p.css('background-color', 'yellow')) is evaluated first.

CSS

.parent {
  width: 400px;
  padding: 10px;
  margin: 10px;
  border: 1px solid;
  background-color: green;
}

HTML

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti qui esse illum, unde labore. Repellendus sunt, quidem eligendi aliquid architecto animi officia itaque ducimus impedit, enim laudantium quis, cupiditate optio.

jQuery

var p = $('.parent');
p.css('border', '3px solid blue');

if(p.css('background-color', 'yellow')){
    alert('cool')
  } else {
  alert( 'Not COOL')
  }

jsFiddle

Thanks

Body:
The browser does not update the graphics when you modify the DOM. It only does so when there's no more javascript to execute. This process is called reflow.

Basically this is how the browser works:

Event loop
    ┌──────────┐
    │          │
    │          │
    │          ▼
    │        check if there's any new ───────▶ parse data
    │        data on the network                    │
    │          │                                    │
    │          ▼                                    │
    │        check if we need to execute  ◀─────────┘
    │        any javascript ──────────────────▶ execute
    │          │                               javascript
    │          ▼                                  │
    │        check if we need to ◀────────────────┘
    │        redraw the page  ──────────────▶ redraw page
    │          │                                   │
    │          │                                   │
    └────◀─────┴─────────────────◀─────────────────┘

However, by definition the alert() function does not wait for reflow and interrupts the execution of javascript.

Therefore when you change the background color to yellow the following happens:

DOM is modified and the background is changed to yellow

Alert is called and the alert dialog is displayed

Other bits of javascript is executed until there's nothing else to execute

Reflow is triggered and the browser finally draws the yellow background to screen

Reflow behaves this way as an optimization. Constantly redrawing everything potentially slows down browsers so even if reflow isn't described by the specification the very fact that Microsoft, Mozilla, Google and Apple are constantly competing to be the best browser means the over time reflow becomes more and more a batch process.


问:
structureMap in a multiTier application
I have a asp.net mvc app having three layers
1. dataAccess layer (class library)
2. business layer (class library)
3. web layer (asp.net mvc project)

and also have a domain project (class library for poco)

I am doing the structureMap mappings in my Application_start of the MVC project, but to map the TYPES in dataAccesslayer (for eg. personRepository with IPersonReository) i need the reference of the DAL in my web layer, which i dont think is correct.

What are your suggestions
Thanks

答:
As a pragmatic approach what you are doing may be okay if you can keep the discipline and never use the DAL from the Web Layer. However, once the reference is there, this can be surprisingly hard to do - and what about other developers on the project?

A better option is to split the web layer into two layers:

The Application Bootstrapping layer. This is the real web project, but apart from bootstrapping the container and implementing the Views (.aspx pages) there should be nothing else. This is what we call a Humble Executable. It will contain references to all other projects in order to compose them (via the DI container), but otherwise it doesn't do anything. We call this the Register Resolve Release pattern.

An Application Model layer. This project would contain all of your application logic (as opposed to domain logic): View Models and Controllers. It needs no reference to the DAL, but will get implementations injected into it by the DI container.

ContentLicense: CC BY-SA 2.5

Title: structureMap in a multiTier application


问:
Changing the model without redirecting to the update page
In my controller there's the update method, I want it like this, If I click the update button the $model->status = ('Done'); without redirecting it to the update page.

What I have tried so far, the page refreshes but the $model->status doesn't change into 'Done'

```<code> public function actionUpdate($id)
{
    $model = $this->findModel($id);

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
       return $this->redirect(['view', 'id' => $model->id]);
    } else {
        $model->status = ('Done');
        $model->time_end = date('y-m-d h-i-s');
        return $this->redirect(['view', 'id' => $model->id]);

    }
}
</code>```

答:
Nevermind I've already found the solution:</p>

```<code>public function actionUpdate($id)
{
    $model = $this->findModel($id);
    $model->status = ('Done');
    $model->time_end = date('y-m-d h-i-s');

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
       return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('view', [
            'model' => $model,
        ]);
    }
}
</code>```

Body:
In my controller there's the update method, I want it like this, If I click the update button the $model->status = ('Done'); without redirecting it to the update page.

What I have tried so far, the page refreshes but the $model->status doesn't change into 'Done'

 public function actionUpdate($id)
{
    $model = $this->findModel($id);

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
       return $this->redirect(['view', 'id' => $model->id]);
    } else {
        $model->status = ('Done');
        $model->time_end = date('y-m-d h-i-s');
        return $this->redirect(['view', 'id' => $model->id]);

    }
}

Body:
Nevermind I've already found the solution:

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    $model->status = ('Done');
    $model->time_end = date('y-m-d h-i-s');

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
       return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('view', [
            'model' => $model,
        ]);
    }
}


问:
django project, mezzanine of "from mezzanine.conf import settings"
Using Mezzanine Resource, I find some files are missing in source folder, but project is not except error, i really want know why! i want know this file in where?

look:
./mezzanine-master/mezzanine/blog/views.py #this file import this line
"from mezzanine.conf import settings"

when i goto this ./mezzanine-master/mezzanine/conf folder and list files:

```<code>total 96
drwxr-xr-x@ 13 Elone  staff   416B Nov 12 15:28 .
drwxr-xr-x@ 19 Elone  staff   608B Nov 12 15:28 ..
-rwxr-xr-x@  1 Elone  staff    10K Nov 12 15:28 __init__.py
-rwxr-xr-x@  1 Elone  staff   2.2K Nov 12 15:28 admin.py
-rwxr-xr-x@  1 Elone  staff   2.3K Nov 12 15:28 context_processors.py
-rwxr-xr-x@  1 Elone  staff   5.3K Nov 12 15:28 forms.py
drwxr-xr-x@ 40 Elone  staff   1.3K Nov 12 15:28 locale
drwxr-xr-x@  4 Elone  staff   128B Nov 12 15:28 migrations
-rwxr-xr-x@  1 Elone  staff   646B Nov 12 15:28 models.py
drwxr-xr-x@  3 Elone  staff    96B Nov 12 15:28 static
drwxr-xr-x@  3 Elone  staff    96B Nov 12 15:28 templates
-rwxr-xr-x@  1 Elone  staff   8.6K Nov 12 15:28 tests.py
-rwxr-xr-x@  1 Elone  staff   233B Nov 12 15:28 translation.py
</code>```

not found settings.py file in this conf folder, i do not find this settings in where, this settings is not project settings, i know project settings in project root folder, but this settings in conf folder, who can tellde me this is what means? thinks

答:
In python, an __init__.py file shares a namespace with the directory it is in. Therefore a variable settings in mezzanine/conf/__init__.py is accessible via the same name as a file mezzanine/conf/settings.pywould be.

In this case mezzanine.conf.settings is defined on the final line of mezzanine/conf/__init__.py:

```<code>settings = Settings()
</code>```

Body:
Using Mezzanine Resource, I find some files are missing in source folder, but project is not except error, i really want know why! i want know this file in where?

look:
./mezzanine-master/mezzanine/blog/views.py #this file import this line
"from mezzanine.conf import settings"

when i goto this ./mezzanine-master/mezzanine/conf folder and list files:

total 96
drwxr-xr-x@ 13 Elone  staff   416B Nov 12 15:28 .
drwxr-xr-x@ 19 Elone  staff   608B Nov 12 15:28 ..
-rwxr-xr-x@  1 Elone  staff    10K Nov 12 15:28 __init__.py
-rwxr-xr-x@  1 Elone  staff   2.2K Nov 12 15:28 admin.py
-rwxr-xr-x@  1 Elone  staff   2.3K Nov 12 15:28 context_processors.py
-rwxr-xr-x@  1 Elone  staff   5.3K Nov 12 15:28 forms.py
drwxr-xr-x@ 40 Elone  staff   1.3K Nov 12 15:28 locale
drwxr-xr-x@  4 Elone  staff   128B Nov 12 15:28 migrations
-rwxr-xr-x@  1 Elone  staff   646B Nov 12 15:28 models.py
drwxr-xr-x@  3 Elone  staff    96B Nov 12 15:28 static
drwxr-xr-x@  3 Elone  staff    96B Nov 12 15:28 templates
-rwxr-xr-x@  1 Elone  staff   8.6K Nov 12 15:28 tests.py
-rwxr-xr-x@  1 Elone  staff   233B Nov 12 15:28 translation.py

not found settings.py file in this conf folder, i do not find this settings in where, this settings is not project settings, i know project settings in project root folder, but this settings in conf folder, who can tellde me this is what means? thinks

Body:
In python, an __init__.py file shares a namespace with the directory it is in. Therefore a variable settings in mezzanine/conf/__init__.py is accessible via the same name as a file mezzanine/conf/settings.pywould be.

In this case mezzanine.conf.settings is defined on the final line of mezzanine/conf/__init__.py:

settings = Settings()


问:
PHP json_encode($_POST) and mySQL issue
I am trying to json_encode($_POST) in PHP, but I have one small problem.

On my $_POST sometimes I get some encoded JSON as example below:

```<code>Array
(
    [module] => {"media":true}
)
</code>```

Where module contains a JSON string. My problem is when I use json_encode($POST); I get a result like this:

```<code>{"module":"{\"petMedia\":true}"}
</code>```

Trying to insert into mySQL JSON column, I get this error

```<code>Invalid JSON text: "Missing a comma or '}' after an object member.
</code>```

It's not possible for me to decode the string before because not always I get encoded JSON.

Thanks.

答:
If I had POST variables coming in where sometimes they have json encoded in it, or not... one way to handle it, would be a cleanup loop.

Lets say this is the POST in:

```<code>$_POST -> 'var1' = 'some string'
       -> 'var2' = '2315'
       -> 'var3' = '{"some":"json"}'
</code>```

Now, I would setup a little cleaner, because you cannot just json_encode($_POST) as you found out. It double encodes the var3.

```<code>$clean = array();
foreach($_POST as $key => $val) {
    json_decode($val);// test
    if (json_last_error() == JSON_ERROR_NONE) {
        $clean[$key] = json_decode($val);// $val is json, so pre-decode it
    } else {
        $clean[$key] = $val;// its not real json, so assign straight
    }
}
print_r($clean);
print_r(json_encode($clean));
</code>```

Results in:

```<code>Array (
    [var1] => some string
    [var2] => 2315
    [var3] => stdClass Object
        (
            [some] => json
        )
)
// this then is a json encoded string, which is good:
{"var1":"some string","var2":2315,"var3":{"some":"json"}}
</code>```

Basically, this then makes a full object which you can now store into the database safely, since all variables and their values are json encodable.

I hope this helps you get started, and you dont actually have normal variables inside json strings, that are not json encoded, and and and and ;)

Title: PHP json_encode($_POST) and mySQL issue

Body:
I am trying to json_encode($_POST) in PHP, but I have one small problem.

On my $_POST sometimes I get some encoded JSON as example below:

Array
(
    [module] => {"media":true}
)

Where module contains a JSON string. My problem is when I use json_encode($POST); I get a result like this:

{"module":"{\"petMedia\":true}"}

Trying to insert into mySQL JSON column, I get this error

Invalid JSON text: "Missing a comma or '}' after an object member.

It's not possible for me to decode the string before because not always I get encoded JSON.

Thanks.

Body:
If I had POST variables coming in where sometimes they have json encoded in it, or not... one way to handle it, would be a cleanup loop.

Lets say this is the POST in:

$_POST -> 'var1' = 'some string'
       -> 'var2' = '2315'
       -> 'var3' = '{"some":"json"}'

Now, I would setup a little cleaner, because you cannot just json_encode($_POST) as you found out. It double encodes the var3.

$clean = array();
foreach($_POST as $key => $val) {
    json_decode($val);// test
    if (json_last_error() == JSON_ERROR_NONE) {
        $clean[$key] = json_decode($val);// $val is json, so pre-decode it
    } else {
        $clean[$key] = $val;// its not real json, so assign straight
    }
}
print_r($clean);
print_r(json_encode($clean));

Results in:

Array (
    [var1] => some string
    [var2] => 2315
    [var3] => stdClass Object
        (
            [some] => json
        )
)
// this then is a json encoded string, which is good:
{"var1":"some string","var2":2315,"var3":{"some":"json"}}

Basically, this then makes a full object which you can now store into the database safely, since all variables and their values are json encodable.

I hope this helps you get started, and you dont actually have normal variables inside json strings, that are not json encoded, and and and and ;)


问:
centering content of iframe for a content body of a specific width
another Question maybe impossible to answer:
on my webside I have an iframe in a div-container:

div:

```<code><div id='frame'>
    <iframe id='content' name='contentfield' ></iframe>
</div>
</code>```

In the css file there is:

css:

```<code>div#frame{
position:absolute;
display:flex;
background-color:green;(just for my testing)
top:100px;
float:left;
width:calc(100vw - 200px);
height:calc(100vh - 100px);
}
iframe#content{
border:none;
width:100%;
height:100%;
}
</code>```

This iframe shows different sides of my webside, e.g. index.php (many index.php's)
so one is loaded by the javascript:

```<code>function start(id){active = id;
    document.getElementById('content').src='content/hallo/';
}
</code>```

so there is: content/hallo/index.php.
The index.php is a normal html document, but body is set to a specific width in px:

```<code><body style='width:1000px'>
    ...
</body>
</code>```

Now: If the browser window is larger then 1200px(100px from body and 200px from another div, see div#frame) the content of the iframe has the width of 1000px but floated left. I want it to be centered so that if the browser window is 1600px wide the content has a margin-left=margin-right of 200px a.s.o.

Edit:
screenshot that shows the unwished:
darkgray is the menu, light gray the iframe and, as you guess right, the pic i a part of me

答:
Solution:You will set the following property</p>

```<code>max-width:auto;
</code>```

Body:
another Question maybe impossible to answer:
on my webside I have an iframe in a div-container:

div:

In the css file there is:

css:

div#frame{
position:absolute;
display:flex;
background-color:green;(just for my testing)
top:100px;
float:left;
width:calc(100vw - 200px);
height:calc(100vh - 100px);
}
iframe#content{
border:none;
width:100%;
height:100%;
}

This iframe shows different sides of my webside, e.g. index.php (many index.php's)
so one is loaded by the javascript:

function start(id){active = id;
    document.getElementById('content').src='content/hallo/';
}

so there is: content/hallo/index.php.
The index.php is a normal html document, but body is set to a specific width in px:

    ...

Now: If the browser window is larger then 1200px(100px from body and 200px from another div, see div#frame) the content of the iframe has the width of 1000px but floated left. I want it to be centered so that if the browser window is 1600px wide the content has a margin-left=margin-right of 200px a.s.o.

Edit:
screenshot that shows the unwished:
darkgray is the menu, light gray the iframe and, as you guess right, the pic i a part of me

Body:
Solution:You will set the following property

max-width:auto;


问:
JavaScript second function parameter magically gets a value
I am reading the JavaScript Guide, section about functions. I got the following code from there:

```<code>function map(f, a) {
    var result = [], i;

    for (i = 0; i != a.length; i++) {
        result[i] = f(a[i]);
    }
    return result;
}

var numbers = [0, 1, 2, 5, 10];
var cube = numbers.map(function(x) {
    return x * x * x;
});

console.log(cube);
</code>```

Result: (5) [0, 1, 8, 125, 1000]

My question is how does the second param a, in map(f, a) even get a value when called in numbers.map? I only see one param being passed and that is the anonymous function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

答:
You are using the map function on the Array prototype. You can call your own mapfunction by calling:

map(yourFunc, numbers);

Body:
I am reading the JavaScript Guide, section about functions. I got the following code from there:

function map(f, a) {
    var result = [], i;

    for (i = 0; i != a.length; i++) {
        result[i] = f(a[i]);
    }
    return result;
}

var numbers = [0, 1, 2, 5, 10];
var cube = numbers.map(function(x) {
    return x * x * x;
});

console.log(cube);

Result: (5) [0, 1, 8, 125, 1000]

My question is how does the second param a, in map(f, a) even get a value when called in numbers.map? I only see one param being passed and that is the anonymous function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions


问:
Spark: run InputFormat as singleton
I'm trying to integrate a key-value database to Spark and have some questions.
I'm a Spark beginner, have read a lot and run some samples but nothing too
complex.

Scenario:

I'm using a small hdfs cluster to store incoming messages in a database.
The cluster has 5 nodes, and the data is split into 5 partitions. Each
partition is stored in a separate database file. Each node can therefore process
its own partition of the data.

The Problem:

The interface to the database software is based on JNI, the database itself is
implemented in C. For technical reasons, the database software can maintain
only one active connection at a time. There can be only one JVM process which
is connected to the Database.

Because of this limitation, reading from and writing to the database must go
through the same JVM process.

(Background info: the database is embedded into the process. It's file based,
and only one process can open it at a time. I could let it run in a separate
process, but that would be slower because of the IPC overhead. My application
will perform many full table scans. Additional writes will be batched and are
not time-critical.)

The Solution:

I have a few ideas in my mind how to solve this, but i don't know if they work
well with Spark.

Maybe it's possible to magically configure Spark to only have one instance of my
proprietary InputFormat per node.

If my InputFormat is used for the first time, it starts a separate thread
which will create the database connection. This thread will then continue
as a daemon and will live as long as the JVM lives. This will only work
if there's just one JVM per node. If Spark starts multiple JVMs on the
same node then each would start its own database thread, which would not
work.

Move my database connection to a separate JVM process per node, and my
InputFormat then uses IPC to connect to this process. As i said, i'd like to avoid this.

Or maybe you have another, better idea?

My favourite solution would be #1, followed closely by #2.

Thanks for any comment and answer!

答: If data from your DB fits into RAM memory of your spark-driver you can load it there as a collection and then parallelize it to an RDD https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html#parallelized-collections</p>

Title: Spark: run InputFormat as singleton


问:
Using alias for template class
I didn't find any answer about this question :
I'm writing a template class DenseMatrix , the necessity of using the specification "Dense" before Matrix is because this class in in a hierarchy that have at the top the base abstract class Matrix from which derives SparseMatrix (from which derive al lot of class representing the different way of storage for sparse matrix, like CRS , MCRS, BlockCSR .. )
Now I wat make available for example in main function the possibility to instantiate an object of the class DenseMatrix using the simple name matrix (note that is not Matrix like the abstract base class) , so I remember that in C was possible used

```<code>typdef struct {

} name ;
</code>```

then

```<code>name obj ; // instance of struct
</code>```

I want obtain the same thing but in a C++ class (C++11 oriented)
which is the best way to doing that directly in the header of the DenseMatrix class declaration ?
P.S. during the defining of the method I always use DenseMatrix:: and not the alias

edit here the example , looking at the end of code

```<code># include "Matrix.H"

template <typename Type>
class DenseMatrix ;

template<typename U>
std::ostream& operator<<(std::ostream& os, const DenseMatrix<U>& m )

    template <typename Type>
    class DenseMatrix
                               :     public Matrix<Type>
    {

           template<typename U>
           friend std::ostream& operator<<(std::ostream& os, const DenseMatrix<U>& m );

    //--
    //
       public:

           constexpr DenseMatrix (std::initializer_list<std::vector<Type>> ) noexcept ;

           constexpr DenseMatrix (const std::string& );

     //       constexpr DenseMatrix (std::size_t , std::size_t);

           virtual  ~DenseMatrix() = default ;

           Type& operator()(const std::size_t , const std::size_t) noexcept override;

           const Type& operator()(const std::size_t , const std::size_t ) const noexcept override;

           void constexpr print () const noexcept override ;

           auto constexpr size1()const noexcept { return Rows ; }

           auto constexpr size2()const noexcept { return Cols ; }

           Type constexpr findValue(const std::size_t , const std::size_t ) const noexcept ;

       protected:

           std::vector<Type> data ;

           std::size_t Rows ;
           std::size_t Cols ;

           mutable Type dummy ;
    } ;
// here ------\/ -------
template <typename T>
using matrix<T> = DenseMatrix<T>
</code>```

thanks @R2RT it's what I was looking for ! SOLVED

答:
If I get you right then you are almost here, but you have one <T> too much:

```<code>template <typename T>
using matrix = DenseMatrix<T>;
</code>```

It's called template aliasing

An alias template is a template which, when specialized, is equivalent to the result of substituting the template arguments of the alias template for the template parameters in the type-id

http://en.cppreference.com/w/cpp/language/type_alias

Title: Using alias for template class

Body:
I didn't find any answer about this question :
I'm writing a template class DenseMatrix , the necessity of using the specification "Dense" before Matrix is because this class in in a hierarchy that have at the top the base abstract class Matrix from which derives SparseMatrix (from which derive al lot of class representing the different way of storage for sparse matrix, like CRS , MCRS, BlockCSR .. )
Now I wat make available for example in main function the possibility to instantiate an object of the class DenseMatrix using the simple name matrix (note that is not Matrix like the abstract base class) , so I remember that in C was possible used

typdef struct {

} name ;

then

name obj ; // instance of struct

I want obtain the same thing but in a C++ class (C++11 oriented)
which is the best way to doing that directly in the header of the DenseMatrix class declaration ?
P.S. during the defining of the method I always use DenseMatrix:: and not the alias

edit here the example , looking at the end of code

# include "Matrix.H"

template <typename Type>
class DenseMatrix ;

template<typename U>
std::ostream& operator<<(std::ostream& os, const DenseMatrix& m )

    template <typename Type>
    class DenseMatrix
                               :     public Matrix<Type>
    {

           template<typename U>
           friend std::ostream& operator<<(std::ostream& os, const DenseMatrix& m );

    //--
    //
       public:

           constexpr DenseMatrix (std::initializer_list<std::vector<Type>> ) noexcept ;

           constexpr DenseMatrix (const std::string& );

     //       constexpr DenseMatrix (std::size_t , std::size_t);

           virtual  ~DenseMatrix() = default ;

           Type& operator()(const std::size_t , const std::size_t) noexcept override;

           const Type& operator()(const std::size_t , const std::size_t ) const noexcept override;

           void constexpr print () const noexcept override ;

           auto constexpr size1()const noexcept { return Rows ; }

           auto constexpr size2()const noexcept { return Cols ; }

           Type constexpr findValue(const std::size_t , const std::size_t ) const noexcept ;

       protected:

           std::vector<Type> data ;

           std::size_t Rows ;
           std::size_t Cols ;

           mutable Type dummy ;
    } ;
// here ------\/ -------
template <typename T>
using matrix<T> = DenseMatrix<T>

thanks @R2RT it's what I was looking for ! SOLVED

Body:
If I get you right then you are almost here, but you have one <T> too much:

template <typename T>
using matrix = DenseMatrix<T>;

It's called template aliasing

An alias template is a template which, when specialized, is equivalent to the result of substituting the template arguments of the alias template for the template parameters in the type-id

http://en.cppreference.com/w/cpp/language/type_alias


问:
SQL STUFF and XML Path - Can't get space between results
SQL Server 2012

Goal: Combine multiple money rows into one string with a space between.

I have tried a variety of edits and modifications and I can't seem to get this correct.

Here is the data I'm looking at:

```<code>Table1.[Misc Amount]
Table2.Taxes
</code>```

My column name has a space which really made the xml path angry I guess.

Statement used:

```<code>DECLARE @Misc nvarchar(30)
SET @Misc = (SELECT [Misc Amount] FROM Table1 WHERE Order=33532)

SELECT @Misc + ' '+ STUFF((SELECT ' ' + SUM(TaxAmount ) AS [text()]
FROM Table2
WHERE Order=33532
GROUP BY Code FOR XML Path('')), 1,0,'')
</code>```

I also tried as string value, [node()], playing with the positions like 1,2, etc.

My resulting data is:

```<code>10.00 0.006.084.50
</code>```

What I want is

```<code>10.00 0.00 6.08 4.50
</code>```

I'd love to exclude the 0.00 but at the moment I'd be happy with just my spaces.... I really hate stuff statements. Any of you kind gurus have a way to help me?

答:
You've got a solution already, that's fine, but I think the following might be more succinct and it is fully set-based and inlinable:

(Borrowed the DDL from Chris Albert's solution, thx for that!)

CREATE TABLE #MiscAmount ([Order] int, [Misc Amount] money)
CREATE TABLE #Taxes ([Order] int, Code int, TaxAmount money)

INSERT INTO #MiscAmount ([Order], [Misc Amount]) VALUES
 (33532, 10.00)
,(1111, 11.00);

INSERT INTO #Taxes ([Order], Code, TaxAmount) VALUES
 (33532, 1, 0.00)
,(33532, 2, 6.08)
,(33532, 2, 1.00) --2 of Code=2 (as you are using `GROUP BY Code`)
,(33532, 3, 4.50)
,(1111, 1, 1.11);

SELECT m.[Misc Amount]
     ,STUFF(
     (
        SELECT ' ' + CAST(SUM(t.TaxAmount) AS VARCHAR(100))
        FROM #Taxes AS t
        WHERE t.[Order]=m.[Order]
        GROUP BY t.Code
        FOR XML PATH('')
      ),1,1,'') AS CombinedTaxAmount
FROM #MiscAmount AS m

GO
DROP TABLE #MiscAmount
DROP TABLE #Taxes
```

<p>The result</p>

```Misc Amount CombinedTaxAmount
10,00       0.00 7.08 4.50
11,00       1.11
```

Body:
SQL Server 2012

Goal: Combine multiple money rows into one string with a space between.

I have tried a variety of edits and modifications and I can't seem to get this correct.

Here is the data I'm looking at:

Table1.[Misc Amount]
Table2.Taxes

My column name has a space which really made the xml path angry I guess.

Statement used:

DECLARE @Misc nvarchar(30)
SET @Misc = (SELECT [Misc Amount] FROM Table1 WHERE Order=33532)

SELECT @Misc + ' '+ STUFF((SELECT ' ' + SUM(TaxAmount ) AS [text()]
FROM Table2
WHERE Order=33532
GROUP BY Code FOR XML Path('')), 1,0,'')

I also tried as string value, [node()], playing with the positions like 1,2, etc.

My resulting data is:

10.00 0.006.084.50

What I want is

10.00 0.00 6.08 4.50

I'd love to exclude the 0.00 but at the moment I'd be happy with just my spaces.... I really hate stuff statements. Any of you kind gurus have a way to help me?

Body:
You've got a solution already, that's fine, but I think the following might be more succinct and it is fully set-based and inlinable:

(Borrowed the DDL from Chris Albert's solution, thx for that!)

CREATE TABLE #MiscAmount ([Order] int, [Misc Amount] money)
CREATE TABLE #Taxes ([Order] int, Code int, TaxAmount money)

INSERT INTO #MiscAmount ([Order], [Misc Amount]) VALUES
 (33532, 10.00)
,(1111, 11.00);

INSERT INTO #Taxes ([Order], Code, TaxAmount) VALUES
 (33532, 1, 0.00)
,(33532, 2, 6.08)
,(33532, 2, 1.00) --2 of Code=2 (as you are using `GROUP BY Code`)
,(33532, 3, 4.50)
,(1111, 1, 1.11);

SELECT m.[Misc Amount]
     ,STUFF(
     (
        SELECT ' ' + CAST(SUM(t.TaxAmount) AS VARCHAR(100))
        FROM #Taxes AS t
        WHERE t.[Order]=m.[Order]
        GROUP BY t.Code
        FOR XML PATH('')
      ),1,1,'') AS CombinedTaxAmount
FROM #MiscAmount AS m

GO
DROP TABLE #MiscAmount
DROP TABLE #Taxes

The result

Misc Amount CombinedTaxAmount
10,00       0.00 7.08 4.50
11,00       1.11


问:
Ruby Build fail error on Ubuntu 17
rbenv install 2.2.8

Downloading ruby-2.2.8.tar.bz2...

-> https://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.8.tar.bz2
Installing ruby-2.2.8...

WARNING: ruby-2.2.8 is nearing its end of life.
It only receives critical security updates, no bug fixes.

BUILD FAILED (Ubuntu 17.10 using ruby-build 20170914-19-gdcfa90c)

Inspect or clean up the working tree at /tmp/ruby-build.20171209140352.8093
Results logged to /tmp/ruby-build.20171209140352.8093.log

Last 10 log lines:
    /tmp/ruby-build.20171209140352.8093/ruby-2.2.8/lib/rdoc/generator/ri.rb:26:in generate'
    /tmp/ruby-build.20171209140352.8093/ruby-2.2.8/lib/rdoc/rdoc.rb:530:inblock in generate'
    /tmp/ruby-build.20171209140352.8093/ruby-2.2.8/lib/rdoc/rdoc.rb:525:in chdir'
    /tmp/ruby-build.20171209140352.8093/ruby-2.2.8/lib/rdoc/rdoc.rb:525:ingenerate'
    /tmp/ruby-build.20171209140352.8093/ruby-2.2.8/lib/rdoc/rdoc.rb:508:in document'
    ./bin/rdoc:20:in'

uncommon.mk:427: recipe for target 'rdoc' failed
make: *** [rdoc] Error 1

答:
Tried disabling the doc building step

RUBY_CONFIGURE_OPTS=--disable-install-doc rbenv install 2.2.8

it worked

Title: Ruby Build fail error on Ubuntu 17


问:
Forcing a dropdown list for an entity property
I'm trying to keep track of employees in my database. I have two tables, Employees and Departments. The Employees table contains a foreign key relationship with Departments through a column named DepartmentID.

Here's my entity:

```<code>[Table(Name = "Employees")]
public class Employee
{
    [HiddenInput(DisplayValue = false)]
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int UserID { get; set; }

    [Column]
    [Required(ErrorMessage = "Please enter a first name")]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [Column]
    [DisplayName("Last Name")]
    [Required(ErrorMessage = "Please enter a last name")]
    public string LastName { get; set; }

    [Column]
    [DisplayName("Department")]
    [Required(ErrorMessage = "Please select a department")]
    public int DepartmentID { get; set; }
}
</code>```

I have a page that contains a form to add an employee. I'm passing the entity to my view page, and calling <%: Html.EditorForModel() %>

The problem is that the view creates a textbox for the DepartmentID.

How can I force the view to display a dropdown for DepartmentID that contains all the Departments in my database as the dropdown's list items? Is there a way to do this by just adding a metadata attribute to the property in my entity?

答:
No, you're not going to be able to do it with just an attribute. You can use Html.DropDownListFor. You'll have to pass your view a list of all the departments as well.

```<code><%= Html.DropDownListFor(
    x => x.DepartmentID,
    Model.Departments }
) %>
</code>```

Body:
I'm trying to keep track of employees in my database. I have two tables, Employees and Departments. The Employees table contains a foreign key relationship with Departments through a column named DepartmentID.

Here's my entity:

[Table(Name = "Employees")]
public class Employee
{
    [HiddenInput(DisplayValue = false)]
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int UserID { get; set; }

    [Column]
    [Required(ErrorMessage = "Please enter a first name")]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [Column]
    [DisplayName("Last Name")]
    [Required(ErrorMessage = "Please enter a last name")]
    public string LastName { get; set; }

    [Column]
    [DisplayName("Department")]
    [Required(ErrorMessage = "Please select a department")]
    public int DepartmentID { get; set; }
}

I have a page that contains a form to add an employee. I'm passing the entity to my view page, and calling <%: Html.EditorForModel() %>

The problem is that the view creates a textbox for the DepartmentID.

How can I force the view to display a dropdown for DepartmentID that contains all the Departments in my database as the dropdown's list items? Is there a way to do this by just adding a metadata attribute to the property in my entity?

Body:
No, you're not going to be able to do it with just an attribute. You can use Html.DropDownListFor. You'll have to pass your view a list of all the departments as well.

<%= Html.DropDownListFor(
    x => x.DepartmentID,
    Model.Departments }
) %>


问:
android dex unable to merge
running project is facing with this error:

```<code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
</code>```

and this is my gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.arnick.bazim"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "0.8"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [onesignal_app_id               : "#onesingal_app_id",

                                onesignal_google_project_number: "REMOTE"]
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:cardview-v7:26.0.2'
    compile 'com.android.support:design:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.android.support:customtabs:26.1.0'
    compile 'com.google.firebase:firebase-auth:11.6.2'
    compile 'com.google.android.gms:play-services-auth:11.6.2'

    compile('io.socket:socket.io-client:1.0.0') {
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    compile 'com.onesignal:OneSignal:3.6.5'
    compile 'com.android.volley:volley:1.0.0'

    testCompile 'junit:junit:4.12'
}

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '26.0.2'
            }
        }
    }
}

android {
    defaultConfig {
        multiDexEnabled true
    }
}
</code>```

is there any special code I'm missing?
I should mention that this is an old project of mine which I have not worked on it for 4 months and now I am working on it again. 4 months ago everything was fine.
Does anyone know what is the problem?thanks

答:
Actually I could compile your configuration at first attempt, but I saw a warning about the com.google.android.gms version used for some module.

For instance, running gradle app:dependencies I could notice this:

```<code>+--- com.onesignal:OneSignal:3.6.5
|   +--- com.google.android.gms:play-services-gcm:[10.2.1,11.3.0) -> 11.2.2
|    |    +--- com.google.android.gms:play-services-base:11.2.2 -> 11.6.2 (*)
|    |    +--- com.google.android.gms:play-services-basement:11.2.2 -> 11.6.2 (*)
|    |    \--- com.google.android.gms:play-services-iid:11.2.2
|    |         +--- com.google.android.gms:play-services-base:11.2.2 -> 11.6.2 (*)
|    |         \--- com.google.android.gms:play-services-basement:11.2.2 -> 11.6.2 (*)
|    +--- com.google.android.gms:play-services-location:[10.2.1,11.3.0) -> 11.2.2
|    |    +--- com.google.android.gms:play-services-base:11.2.2 -> 11.6.2 (*)
|    |    +--- com.google.android.gms:play-services-basement:11.2.2 -> 11.6.2 (*)
|    |    \--- com.google.android.gms:play-services-tasks:11.2.2 -> 11.6.2 (*)
|    +--- com.android.support:support-v4:[26.0.0,26.2.0) -> 26.0.2 (*)
|    \--- com.android.support:customtabs:[26.0.0,26.2.0) -> 26.0.2 (*)
</code>```

So for example com.google.android.gms:play-services-gcm:[10.2.1,11.3.0) -> 11.2.2 refers version 11.2.2

While firebase refers version 11.6.2

```<code>|    +--- com.google.firebase:firebase-common:11.6.2
|    |    +--- com.google.android.gms:play-services-basement:11.6.2 (*)
|    |    +--- com.google.android.gms:play-services-tasks:11.6.2 (*)
|    |    \--- com.google.firebase:firebase-common-license:11.6.2
|    +--- com.google.android.gms:play-services-tasks:11.6.2 (*)
|    \--- com.google.firebase:firebase-auth-license:11.6.2
</code>```

So since you already have a resolution strategy I would change it like this:

```<code>resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '26.0.2'
        }
    }
    if (requested.group == 'com.google.android.gms') {
        details.useVersion '11.6.2'
    }

}
</code>```

My warning disappeared and I hope it can help you in your case.

UPDATE

I confirm that running the command

gradle app:transformDexArchiveWithExternalLibsDexMergerForDebug

As reported in your exception, I first had your same result with your configuration and then a successful build with the change I suggested.

Title: android dex unable to merge

Body:
running project is facing with this error:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

and this is my gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.arnick.bazim"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "0.8"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [onesignal_app_id               : "#onesingal_app_id",

                                onesignal_google_project_number: "REMOTE"]
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:cardview-v7:26.0.2'
    compile 'com.android.support:design:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.android.support:customtabs:26.1.0'
    compile 'com.google.firebase:firebase-auth:11.6.2'
    compile 'com.google.android.gms:play-services-auth:11.6.2'

    compile('io.socket:socket.io-client:1.0.0') {
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    compile 'com.onesignal:OneSignal:3.6.5'
    compile 'com.android.volley:volley:1.0.0'

    testCompile 'junit:junit:4.12'
}

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '26.0.2'
            }
        }
    }
}

android {
    defaultConfig {
        multiDexEnabled true
    }
}

is there any special code I'm missing?
I should mention that this is an old project of mine which I have not worked on it for 4 months and now I am working on it again. 4 months ago everything was fine.
Does anyone know what is the problem?thanks

Body:
Actually I could compile your configuration at first attempt, but I saw a warning about the com.google.android.gms version used for some module.

For instance, running gradle app:dependencies I could notice this:

+--- com.onesignal:OneSignal:3.6.5
|   +--- com.google.android.gms:play-services-gcm:[10.2.1,11.3.0) -> 11.2.2
|    |    +--- com.google.android.gms:play-services-base:11.2.2 -> 11.6.2 (*)
|    |    +--- com.google.android.gms:play-services-basement:11.2.2 -> 11.6.2 (*)
|    |    \--- com.google.android.gms:play-services-iid:11.2.2
|    |         +--- com.google.android.gms:play-services-base:11.2.2 -> 11.6.2 (*)
|    |         \--- com.google.android.gms:play-services-basement:11.2.2 -> 11.6.2 (*)
|    +--- com.google.android.gms:play-services-location:[10.2.1,11.3.0) -> 11.2.2
|    |    +--- com.google.android.gms:play-services-base:11.2.2 -> 11.6.2 (*)
|    |    +--- com.google.android.gms:play-services-basement:11.2.2 -> 11.6.2 (*)
|    |    \--- com.google.android.gms:play-services-tasks:11.2.2 -> 11.6.2 (*)
|    +--- com.android.support:support-v4:[26.0.0,26.2.0) -> 26.0.2 (*)
|    \--- com.android.support:customtabs:[26.0.0,26.2.0) -> 26.0.2 (*)

So for example com.google.android.gms:play-services-gcm:[10.2.1,11.3.0) -> 11.2.2 refers version 11.2.2

While firebase refers version 11.6.2

|    +--- com.google.firebase:firebase-common:11.6.2
|    |    +--- com.google.android.gms:play-services-basement:11.6.2 (*)
|    |    +--- com.google.android.gms:play-services-tasks:11.6.2 (*)
|    |    \--- com.google.firebase:firebase-common-license:11.6.2
|    +--- com.google.android.gms:play-services-tasks:11.6.2 (*)
|    \--- com.google.firebase:firebase-auth-license:11.6.2

So since you already have a resolution strategy I would change it like this:

resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '26.0.2'
        }
    }
    if (requested.group == 'com.google.android.gms') {
        details.useVersion '11.6.2'
    }

}

My warning disappeared and I hope it can help you in your case.

UPDATE

I confirm that running the command

gradle app:transformDexArchiveWithExternalLibsDexMergerForDebug

As reported in your exception, I first had your same result with your configuration and then a successful build with the change I suggested.


问:
Symbol Server - Move Files, move source code
We recently upgraded TFS 2012 to TFS 2017.  Now we have some challenges

Symbol files do download as expected from our new symbol server, but... the symbol files no longer locate the source code files.  All we get now is a MetaData reference.

I am sure I am setting up the symbol server correctly since the symbol cache is loaded with all the correct symbol files.

What appears to be the problem is despite Visual Studio having the symbol file, Visual Studio debugger cannot locate the symbol file's corresponding source code file.

Would upgrading TFS cause this to happen?  Would moving source code files to a new folder impact this?  I am at a loss as to how Symbol files FIND the source code files... how does this work so I can figure out the problem?

答:
OK I found out how MS expects us to clean this up.

If you move your Version Control Server or change the VC Server Hostname you can do one of two things:

a. Add a srcsrv.ini file to your debugging sdk folder that has the new hostname.  The debugger should pick up the new servername in the ini file and override what's in your pdb.

OR

b. You can update each pdb with pdbstr.exe with the new servername

I have yet to get A to work.  There seems to be conflicting documentation as to where to put your srcsrv.ini file and no clear indication of the variable name to use for the TFS hostname value.

B is the break down the door approach, but Powershell serves nicely.  There were 1200+ dlls to update.  Powershell did all but a dozen of them.

I am still trying to figure out those last 12 issues now.


问:
How to save an image to FileField from its path?
I have an image stored in my media/logo/ folder and I'd like to save it to my model's FileField from my view. Here's what I tried but I'm getting an encoding error & the file becomes corrupted after I'm trying to save it.

UnicodeDecodeError: 'charmap' codec can't decode byte ...

views.py:

```<code>def save_records(request):
    new_path = os.path.join(settings.MEDIA_ROOT, 'logo', filename)
    same_file = File(new_path, filename)
    Company.objects.create(logo=same_file)
</code>```

I have some trouble understanding how I can save the file in new_path to the FileField, any idea ?

答:
According to the docs File class expects a file object as the 1st argument, not a path string. You need to do:

```<code>with open(new_path, 'rb') as fo:
    same_file = File(fo, filename)
    Company.objects.create(logo=same_file)
</code>```

Body:
I have an image stored in my media/logo/ folder and I'd like to save it to my model's FileField from my view. Here's what I tried but I'm getting an encoding error & the file becomes corrupted after I'm trying to save it.

UnicodeDecodeError: 'charmap' codec can't decode byte ...

views.py:

def save_records(request):
    new_path = os.path.join(settings.MEDIA_ROOT, 'logo', filename)
    same_file = File(new_path, filename)
    Company.objects.create(logo=same_file)

I have some trouble understanding how I can save the file in new_path to the FileField, any idea ?

Body:
According to the docs File class expects a file object as the 1st argument, not a path string. You need to do:

with open(new_path, 'rb') as fo:
    same_file = File(fo, filename)
    Company.objects.create(logo=same_file)


问:
Detecting async client disconnect in ASP.NET MVC
Given an async controller:

```<code>public class MyController : AsyncController
{
    [NoAsyncTimeout]
    public void MyActionAsync() { ... }

    public void MyActionCompleted() { ... }
}
</code>```

Assume MyActionAsync kicks off a process that takes several minutes.  If the user now goes to the MyAction action, the browser will wait with the connection open.  If the user closes his browser, the connection is closed.  Is it possible to detect when that happens on the server (preferably inside the controller)?  If so, how?  I've tried overriding OnException but that never fires in this scenario.

Note:  I do appreciate the helpful answers below, but the key aspect of this question is that I'm using an AsyncController.  This means that the HTTP requests are still open (they are long-lived like COMET or BOSH) which means it's a live socket connection.  Why can't the server be notified when this live connection is terminated (i.e.  "connection reset by peer", the TCP RST packet)?

答: For obvious reasons the server cannot be notified that the client has closed his browser. Or that he went to the toilet :-) What you could do is have the client continuously poll the server with AJAX requests at regular interval (window.setInterval) and if the server detects that it is no longer polled it means the client is no longer there.

Body:
Given an async controller:

public class MyController : AsyncController
{
    [NoAsyncTimeout]
    public void MyActionAsync() { ... }

    public void MyActionCompleted() { ... }
}

Assume MyActionAsync kicks off a process that takes several minutes.  If the user now goes to the MyAction action, the browser will wait with the connection open.  If the user closes his browser, the connection is closed.  Is it possible to detect when that happens on the server (preferably inside the controller)?  If so, how?  I've tried overriding OnException but that never fires in this scenario.

Note:  I do appreciate the helpful answers below, but the key aspect of this question is that I'm using an AsyncController.  This means that the HTTP requests are still open (they are long-lived like COMET or BOSH) which means it's a live socket connection.  Why can't the server be notified when this live connection is terminated (i.e.  "connection reset by peer", the TCP RST packet)?


问:
Listen preference change and transfer boolean in checkbox to MainActivity
I have 2 file:

control_preferences.xml:`

```<code><PreferenceCategory
    android:title="@string/control_category">

    <CheckBoxPreference
        android:title="Debug Information ON/OFF"
        android:defaultValue="false"
        android:summary="Show debug information when ON"
        android:key="checkboxPref" />

</PreferenceCategory>
</code>```

`

SettingsActivity.java:

```<code>package com.sample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static final String KEY_PREF_DEBUG = "checkboxPref";

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if (key.equals(KEY_PREF_DEBUG)) {
            Toast.makeText(getApplicationContext(), "CLICK",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);
        }
    }}
</code>```

I have 2 questions:

Why when selecting or deselecting Checkbox Toast doesn't display?

How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity.

答:
1) Why when selecting or deselecting Checkbox Toast doesn't display?

Add below lines in on resume of your activity

```<code>SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(prefs);
</code>```

2)How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity?
Use below code to get value

```<code>    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getBoolean("key_value_given_in_preference_xml_file")
</code>```

Body:
I have 2 file:

control_preferences.xml:`

<PreferenceCategory
    android:title="@string/control_category">

    <CheckBoxPreference
        android:title="Debug Information ON/OFF"
        android:defaultValue="false"
        android:summary="Show debug information when ON"
        android:key="checkboxPref" />

</PreferenceCategory>

`

SettingsActivity.java:

package com.sample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static final String KEY_PREF_DEBUG = "checkboxPref";

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if (key.equals(KEY_PREF_DEBUG)) {
            Toast.makeText(getApplicationContext(), "CLICK",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBuildHeaders(List target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);
        }
    }}

I have 2 questions:

Why when selecting or deselecting Checkbox Toast doesn't display?

How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity.

Body:
1) Why when selecting or deselecting Checkbox Toast doesn't display?

Add below lines in on resume of your activity

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(prefs);

2)How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity?
Use below code to get value

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getBoolean("key_value_given_in_preference_xml_file")


问:
How to link OmniAuth identification (working) and Google Api Calls
After a day trying, testing, googling ... I ask for some help
I try to use Omniauth and Google Calendar. OmniAuth is working like a charm but I just can't link it with Google API

I think I read almost everything, I still get this error message :

dailyLimitExceededUnreg: Daily Limit for Unauthenticated Use Exceeded.
  Continued use requires sign up.

It means that my calls are not properly 'connected' to my auth, which seems to be valid. My tokens are in databases but I this point I would like to login / identify / call and have something else that an error message.

client_id = Google::Auth::ClientId.from_file('.....googleusercontent.com.json')

```<code>scopes =  ['userinfo.email,calendar']

token_store = Google::Auth::MyTokenStore.new()

authorizer = Google::Auth::WebUserAuthorizer.new(
    client_id,
    scopes,
    token_store,
    'http://localhost:3000'
)

# credentials = Google::Auth::UserAuthorizer.new( .  # Anotheir test
#     client_id,
#     scopes,
#     token_store,
#     'http://localhost:3000'
# )
#
# authorizer = credentials.get_credentials_from_code(
#     GoogleUser.find(session[:user_id]) # I tested token ... notking worked
# )

calendar = Google::Apis::CalendarV3::CalendarService.new
calendar.authorization = authorizer
calendar_id = 'primary'

@result = calendar.list_events(calendar_id,
                               max_results: 10,
                               single_events: true,
                               order_by: 'startTime',
                               time_min: Time.now.iso8601)
</code>```

and my token storage , I don't understand why but never called

```<code>class MyTokenStore
  class << self
    attr_accessor :default
  end

  def load(_id)
    puts "********** load ************"
    return GoogleUser.find(session[:user_id]).access_token
  end

  def store(_id, _token)
    puts "********** store ************"
    @user.access_token = _token
  end

  def delete(_id)
    puts "********** delete ************"
    @user.access_token = nil
  end
end
</code>```

end
end

答:
For future readers : I took a different technic, after reading an excellent article here : http://gmile.me/simple-google-auth/
I followed it and use signet, it is working like a charm</p>

Body:
After a day trying, testing, googling ... I ask for some help
I try to use Omniauth and Google Calendar. OmniAuth is working like a charm but I just can't link it with Google API

I think I read almost everything, I still get this error message :

dailyLimitExceededUnreg: Daily Limit for Unauthenticated Use Exceeded.
  Continued use requires sign up.

It means that my calls are not properly 'connected' to my auth, which seems to be valid. My tokens are in databases but I this point I would like to login / identify / call and have something else that an error message.

client_id = Google::Auth::ClientId.from_file('.....googleusercontent.com.json')

scopes =  ['userinfo.email,calendar']

token_store = Google::Auth::MyTokenStore.new()

authorizer = Google::Auth::WebUserAuthorizer.new(
    client_id,
    scopes,
    token_store,
    'http://localhost:3000'
)

# credentials = Google::Auth::UserAuthorizer.new( .  # Anotheir test
#     client_id,
#     scopes,
#     token_store,
#     'http://localhost:3000'
# )
#
# authorizer = credentials.get_credentials_from_code(
#     GoogleUser.find(session[:user_id]) # I tested token ... notking worked
# )

calendar = Google::Apis::CalendarV3::CalendarService.new
calendar.authorization = authorizer
calendar_id = 'primary'

@result = calendar.list_events(calendar_id,
                               max_results: 10,
                               single_events: true,
                               order_by: 'startTime',
                               time_min: Time.now.iso8601)

and my token storage , I don't understand why but never called

class MyTokenStore
  class << self
    attr_accessor :default
  end

  def load(_id)
    puts "********** load ************"
    return GoogleUser.find(session[:user_id]).access_token
  end

  def store(_id, _token)
    puts "********** store ************"
    @user.access_token = _token
  end

  def delete(_id)
    puts "********** delete ************"
    @user.access_token = nil
  end
end

end
end


问:
Symfony - orphanRemoval and Stof Softdeleteable
I have a entity, User and User can has many phone number, so I have field: User.numbers and entity Number
UserType:

```<code>->add('numbers', CollectionType::class, array(
    'entry_type' => NumberType::class,
    'by_reference' => false,
    'allow_add' => true,
    'allow_delete' => true,
))
</code>```

Field number also uses @Gedmo\SoftDeleteable. It works Ok - when I'm deleting phone number directly it's Ok, phone number wont be deleted, only marked as deleted.

But If I update User and I have 5 numbers, I delete one and send form with only 4 - entity manager ignores soft delete and deletes it anyway.

Is it possible to work with orphan removal and softdeleteable together?

答:
This is an expected behavior of the soft deletable component. First time you try to delete it, it marks it as soft deleted. If a soft deleted item gets marked to be deleted it gets deleted permanently.

You are submitting a from with missing items as they where filtered by the Doctrine filter (soft deleted) so when the form gets submitted that items were missing and gets marked again to be deleted.

Check:
https://github.com/Atlantic18/DoctrineExtensions/blob/v2.4.x/lib/Gedmo/SoftDeleteable/SoftDeleteableListener.php#L67

Body:
I have a entity, User and User can has many phone number, so I have field: User.numbers and entity Number
UserType:

->add('numbers', CollectionType::class, array(
    'entry_type' => NumberType::class,
    'by_reference' => false,
    'allow_add' => true,
    'allow_delete' => true,
))

Field number also uses @Gedmo\SoftDeleteable. It works Ok - when I'm deleting phone number directly it's Ok, phone number wont be deleted, only marked as deleted.

But If I update User and I have 5 numbers, I delete one and send form with only 4 - entity manager ignores soft delete and deletes it anyway.

Is it possible to work with orphan removal and softdeleteable together?


问:
Click listener when tab is clicked - angular2 and ng bootstrap
I have the following html code snippet. I am using angular2, ng-bootstrap ng tab. My question is how do i invoke a method click when a tab is clicked?
I added (click) but I see that the method fetchNews() is not getting invoked at all when I click on the tab. What am I doing wrong? </p>

```<code>  <ngb-tab title="Active" (click)="fetchNews('active')">
    <ng-template ngbTabContent>
      <table class="table table-sm table-striped">
        <thead>
        <tr>
          <th>Title</th>
          <th>Description</th>
          <th>Attachment</th>
          <th>Start Date</th>
          <th>End Date</th>
          <th>Actions</th>
        </tr>
        </thead>
        <tr *ngFor="let item of news">
          <td>{{item.title}}</td>
          <td>{{item.description | ellipsis:25}}</td>
          <td>{{item.attachmentUrl | ellipsis:25}}</td>
          <td>{{item.startDate | date: 'MM/dd/yyyy hh:mm a'}}</td>
          <td>{{item.endDate | date: 'MM/dd/yyyy hh:mm a'}}</td>
          <td>
            <button type="button" class="btn btn-secondary btn-sm" (click)="showNewsModal('active',item, true)">
              Modify
            </button>
          </td>
        </tr>
      </table>
    </ng-template>
  </ngb-tab>
</code>```

答:
The below should work correctly every time.

fetchNews(evt: any) {
  console.log(evt); // has nextId that you can check to invoke the desired function
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ngb-tabset (tabChange)="fetchNews($event)">
  <ngb-tab title="Active">
    <ng-template ngbTabContent>
      <table class="table table-sm table-striped">
        ...
      </table>
    </ng-template>
  </ngb-tab>
</ngb-tabset></code>```

Body:
I have the following html code snippet. I am using angular2, ng-bootstrap ng tab. My question is how do i invoke a method click when a tab is clicked?
I added (click) but I see that the method fetchNews() is not getting invoked at all when I click on the tab. What am I doing wrong?

  <ngb-tab title="Active" (click)="fetchNews('active')">
    <ng-template ngbTabContent>

          Title
          Description
          Attachment
          Start Date
          End Date
          Actions

          {{item.title}}
          {{item.description | ellipsis:25}}
          {{item.attachmentUrl | ellipsis:25}}
          {{item.startDate | date: 'MM/dd/yyyy hh:mm a'}}
          {{item.endDate | date: 'MM/dd/yyyy hh:mm a'}}

            <button type="button" class="btn btn-secondary btn-sm" (click)="showNewsModal('active',item, true)">
              Modify
            </button>

    </ng-template>
  </ngb-tab>

Body:
The below should work correctly every time.

fetchNews(evt: any) {
  console.log(evt); // has nextId that you can check to invoke the desired function
}

<ngb-tabset (tabChange)="fetchNews($event)">
  <ngb-tab title="Active">
    <ng-template ngbTabContent>
      <table class="table table-sm table-striped">
        ...
      </table>
    </ng-template>
  </ngb-tab>
</ngb-tabset>


问:
sql query - to rent a car (php)
Im new to php and sql and having trouble writing a query.

I've already accomplished a query that show/get unrented cars.
And it looks this:

```<code>SELECT c.*
FROM cars c
WHERE NOT EXISTS (
          SELECT *
          FROM reservations as r
          WHERE r.car_id = c.id AND
          (r.res_from <= '2017-12-08 02:53:59' AND r.res_to >= '2017-12.09 23:58:59') OR
          (r.res_from <= '2017-12-08 23:59:59' AND r.res_to >= '2017-12.09 23:58:59') OR
          (r.res_from >= '2017-12-08 23:59:59' AND r.res_to <= '2017-12.09 23:58:59')
          );`
</code>```

The question is:  how to write a query that rent a car given from_date - to_date and a user/customer need enough points(money) to rent a specified car.

link to my database http://sqlfiddle.com/#!9/170f7f4/5

I tried something like this. Is this the right way to go?

```<code>    SELECT * FROM cars as c, reservations as r, users as u,
    WHERE HAVING c.id = r.car_id AND
                 r.user_id = u.user_id AND
          (res_from <= '2017-12-08 02:53:59' AND r.res_to >= '2017-12-08 02:53:59') OR
          (r.res_from >= '2017-12-08 23:59:59' AND r.res_to <= '2017-12-08 23:59:59' )
</code>```

.... what next?

And want to click on a car (as can be seen in the attached picture) and then chose a rent date.

答:
Use JOINS</p>

```<code>SELECT * FROM cars as c
LEFT JOIN reservations as r ON c.id = r.car_id
LEFT JOIN users as u ON r.user_id = u.user_id
WHERE ...
etc.
</code>```

Title: sql query - to rent a car (php)

Body:
Im new to php and sql and having trouble writing a query.

I've already accomplished a query that show/get unrented cars.
And it looks this:

SELECT c.*
FROM cars c
WHERE NOT EXISTS (
          SELECT *
          FROM reservations as r
          WHERE r.car_id = c.id AND
          (r.res_from <= '2017-12-08 02:53:59' AND r.res_to >= '2017-12.09 23:58:59') OR
          (r.res_from <= '2017-12-08 23:59:59' AND r.res_to >= '2017-12.09 23:58:59') OR
          (r.res_from >= '2017-12-08 23:59:59' AND r.res_to <= '2017-12.09 23:58:59')
          );`

The question is:  how to write a query that rent a car given from_date - to_date and a user/customer need enough points(money) to rent a specified car.

link to my database http://sqlfiddle.com/#!9/170f7f4/5

I tried something like this. Is this the right way to go?

    SELECT * FROM cars as c, reservations as r, users as u,
    WHERE HAVING c.id = r.car_id AND
                 r.user_id = u.user_id AND
          (res_from <= '2017-12-08 02:53:59' AND r.res_to >= '2017-12-08 02:53:59') OR
          (r.res_from >= '2017-12-08 23:59:59' AND r.res_to <= '2017-12-08 23:59:59' )

.... what next?

And want to click on a car (as can be seen in the attached picture) and then chose a rent date.

Body:
Use JOINS

SELECT * FROM cars as c
LEFT JOIN reservations as r ON c.id = r.car_id
LEFT JOIN users as u ON r.user_id = u.user_id
WHERE ...
etc.