问:
Change font color for a sql file on Visual Studio 2015
I'm using the dark theme on Visual Studio 2015, and installed ReSharper 2017 along with it. As you can see the color on a sql extension file is awful with the dark theme and I cannot find where I can modify its color.

Could anyone point me out where to look at?

答:
Go to tools> options> Environment> Fonts and Colors> select Keyword:

you can set bg/fg color and font size here. see pic:


来源: stackexchange

问:
Spring aop doesn't run when project starts
I'v implemented a spring-boot aop demo and it runs well, but when I want to use it to load some resource when the project starts, it doesn't work somehow

Aop:

```<code>package com.neo.mysql;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by li_weia on 2017/7/6.
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(VendorSource)")
    public void beforeSwitchDS(JoinPoint point){

        //获得当前访问的class
        Class<?> className = point.getTarget().getClass();

        //获得访问的方法名
        String methodName = point.getSignature().getName();
        //得到方法的参数的类型
        Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
        String dataSource = DataSourceContextHolder.DEFAULT_DS;
        try {
            // 得到访问的方法对象
            Method method = className.getMethod(methodName, argClass);

            // 判断是否存在@DS注解
            if (method.isAnnotationPresent(VendorSource.class)) {
                VendorSource annotation = method.getAnnotation(VendorSource.class);
                // 取出注解中的数据源名
                dataSource = annotation.value();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 切换数据源
        DataSourceContextHolder.setDB(dataSource);

    }

    @After("@annotation(VendorSource)")
    public void afterSwitchDS(JoinPoint point){

        DataSourceContextHolder.clearDB();

    }
}
</code>```

The VendorSource annotation:

```<code>package com.neo.mysql;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by li_weia on 2017/7/6.
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface VendorSource {
    String value() default "vendor-master";
}
</code>```

It runs well here, I can successfully change datasource by annotation:

```<code>package com.neo.web;

import com.neo.entity.SiteEntity;
import com.neo.mapper.ClassMappingDao;
import com.neo.mysql.VendorSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    private final ClassMappingDao siteMapper;

    @Autowired(required = false)
    public UserController(ClassMappingDao siteMapper) {
        this.siteMapper = siteMapper;
    }

    @RequestMapping("/getSites")
    @VendorSource("vendor-read")
    public List<SiteEntity> getUsers() {
        return siteMapper.getAllSite();
    }
}
</code>```

but it doesn't work here, the aop method is not invoked at all:

```<code>package com.neo.component;

import com.neo.entity.SiteEntity;
import com.neo.mapper.ClassMappingDao;
import com.neo.mysql.VendorSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by li_weia on 2017/7/7.
 */
@Component
public class TestComponent{
    private final ClassMappingDao userMapper;

    @Autowired(required = false)
    public TestComponent(ClassMappingDao userMapper) {
        this.userMapper = userMapper;
        init();
    }

    @VendorSource("vendor-read")
    public void init() {
        List<SiteEntity> sites = userMapper.getAllSite();
        for(SiteEntity site: sites){
            System.out.println(site.getSite());
        }
    }
}
</code>```

答:
You need to fully qualify the annotation, like so:

```<code>@Before("execution(public * *(..)) && @annotation(com.neo.mysql.VendorSource)")
private void whatever() {}
</code>```

Also, as mentioned in my comment above, you need to have spring-boot-starter-aop on classpath. Maybe you already do, but since you didn't say, it's worth mentioning.

Edit:

I didn't notice the real problem before, I wasn't paying attention.

Spring AOP only triggers if you make calls from another class. This is because Spring needs to be able to intercept the call and run the pointcut. Calling the method from constructor is not going to do anything.

You can do a hackish workaround. Create a @PostConstruct void postConstruct() {} method in your class (not constructor), autowire ApplicationContext, and then do MyClassWithInitMethod myClass = context.getBean(MyClassWithInitMethod.class) in the postConstruct method. Then call the method on myClass, and AOP will kick in.

Frankly, I didn't previously check what you are doing in your pointcut, and it's a terrible idea. When multiple threads run, they are going to overwrite the static context, and create a race-condition that you'll then create another question for. Don't do it! Use the factory pattern instead, and inject the DataSourceFactory in the classes that now have the annotation.

ContentLicense: CC BY-SA 3.0

Body:
I'v implemented a spring-boot aop demo and it runs well, but when I want to use it to load some resource when the project starts, it doesn't work somehow

Aop:

package com.neo.mysql;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by li_weia on 2017/7/6.
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(VendorSource)")
    public void beforeSwitchDS(JoinPoint point){

        //获得当前访问的class
        Class<?> className = point.getTarget().getClass();

        //获得访问的方法名
        String methodName = point.getSignature().getName();
        //得到方法的参数的类型
        Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
        String dataSource = DataSourceContextHolder.DEFAULT_DS;
        try {
            // 得到访问的方法对象
            Method method = className.getMethod(methodName, argClass);

            // 判断是否存在@DS注解
            if (method.isAnnotationPresent(VendorSource.class)) {
                VendorSource annotation = method.getAnnotation(VendorSource.class);
                // 取出注解中的数据源名
                dataSource = annotation.value();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 切换数据源
        DataSourceContextHolder.setDB(dataSource);

    }

    @After("@annotation(VendorSource)")
    public void afterSwitchDS(JoinPoint point){

        DataSourceContextHolder.clearDB();

    }
}

The VendorSource annotation:

package com.neo.mysql;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by li_weia on 2017/7/6.
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface VendorSource {
    String value() default "vendor-master";
}

It runs well here, I can successfully change datasource by annotation:

package com.neo.web;

import com.neo.entity.SiteEntity;
import com.neo.mapper.ClassMappingDao;
import com.neo.mysql.VendorSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    private final ClassMappingDao siteMapper;

    @Autowired(required = false)
    public UserController(ClassMappingDao siteMapper) {
        this.siteMapper = siteMapper;
    }

    @RequestMapping("/getSites")
    @VendorSource("vendor-read")
    public List<SiteEntity> getUsers() {
        return siteMapper.getAllSite();
    }
}

but it doesn't work here, the aop method is not invoked at all:

package com.neo.component;

import com.neo.entity.SiteEntity;
import com.neo.mapper.ClassMappingDao;
import com.neo.mysql.VendorSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by li_weia on 2017/7/7.
 */
@Component
public class TestComponent{
    private final ClassMappingDao userMapper;

    @Autowired(required = false)
    public TestComponent(ClassMappingDao userMapper) {
        this.userMapper = userMapper;
        init();
    }

    @VendorSource("vendor-read")
    public void init() {
        List<SiteEntity> sites = userMapper.getAllSite();
        for(SiteEntity site: sites){
            System.out.println(site.getSite());
        }
    }
}

Body:
You need to fully qualify the annotation, like so:

@Before("execution(public * *(..)) && @annotation(com.neo.mysql.VendorSource)")
private void whatever() {}

Also, as mentioned in my comment above, you need to have spring-boot-starter-aop on classpath. Maybe you already do, but since you didn't say, it's worth mentioning.

Edit:

I didn't notice the real problem before, I wasn't paying attention.

Spring AOP only triggers if you make calls from another class. This is because Spring needs to be able to intercept the call and run the pointcut. Calling the method from constructor is not going to do anything.

You can do a hackish workaround. Create a @PostConstruct void postConstruct() {} method in your class (not constructor), autowire ApplicationContext, and then do MyClassWithInitMethod myClass = context.getBean(MyClassWithInitMethod.class) in the postConstruct method. Then call the method on myClass, and AOP will kick in.

Frankly, I didn't previously check what you are doing in your pointcut, and it's a terrible idea. When multiple threads run, they are going to overwrite the static context, and create a race-condition that you'll then create another question for. Don't do it! Use the factory pattern instead, and inject the DataSourceFactory in the classes that now have the annotation.


问:
What is the best way to pause/stop/command a Python script anytime anywhere?
I have a Python script running selenium framework in a command line and running continuously to control Chrome do background data processing and monitoring. My simplified code structure is as following

```<code>while True:
    Do_task1() # a blocking function
    Do_task2() # another blocking fucntion
    ... # calling many blocking functions below, including wait(), time.sleep()
</code>```

I need a way to interrupt the script anytime and anywhere to pause, terminate safely and give commands. What are the best ways to do this?
I've thought and tried of several ways but I am not exactly sure how to approach it:

I tried this:

```<code>if msvcrt.kbhit():
    key = msvcrt.getch().decode("utf-8").lower()
    if key == "j":
      self.setting1 = True
    elif key == "k":
      self.setting2 = True
</code>```

in the while loop, but it has to pass through bunch of blocking calls before reacting to my keypresses. And the command isn't exactly accepting my keyboard input in real time, that is I'll enter a character input, and I think it will be in the background buffer, then once the code execution reaches the code above, it starts to do stuff.
For terminating the script, I just do Ctrl-C in the CMD window, which I don't think it's the best way, and I should properly end the program ending background processes like Chromedriver.

I thought of having a GUI which runs somehow asynchronously and I can have buttons for pausing, and terminating the script. But I am not exactly sure how to approach it, or if this is a good idea to even try. Any suggestion is welcomed.

Use a script monitoring/workflow monitoring framework like AirBnB's Airflow or Luigi. I had only done brief research on this.

A related question but I don't need to return exactly where it's left off

答:
I usually use try and except to do this</p>

```<code>while True:
    try:
        Do_Task1()
        Do_Task2()
    except KeyBoardInterrrupt:
        break
</code>```

Body:
I have a Python script running selenium framework in a command line and running continuously to control Chrome do background data processing and monitoring. My simplified code structure is as following

while True:
    Do_task1() # a blocking function
    Do_task2() # another blocking fucntion
    ... # calling many blocking functions below, including wait(), time.sleep()

I need a way to interrupt the script anytime and anywhere to pause, terminate safely and give commands. What are the best ways to do this?
I've thought and tried of several ways but I am not exactly sure how to approach it:

I tried this:

if msvcrt.kbhit():
    key = msvcrt.getch().decode("utf-8").lower()
    if key == "j":
      self.setting1 = True
    elif key == "k":
      self.setting2 = True

in the while loop, but it has to pass through bunch of blocking calls before reacting to my keypresses. And the command isn't exactly accepting my keyboard input in real time, that is I'll enter a character input, and I think it will be in the background buffer, then once the code execution reaches the code above, it starts to do stuff.
For terminating the script, I just do Ctrl-C in the CMD window, which I don't think it's the best way, and I should properly end the program ending background processes like Chromedriver.

I thought of having a GUI which runs somehow asynchronously and I can have buttons for pausing, and terminating the script. But I am not exactly sure how to approach it, or if this is a good idea to even try. Any suggestion is welcomed.

Use a script monitoring/workflow monitoring framework like AirBnB's Airflow or Luigi. I had only done brief research on this.

A related question but I don't need to return exactly where it's left off

Body:
I usually use try and except to do this

while True:
    try:
        Do_Task1()
        Do_Task2()
    except KeyBoardInterrrupt:
        break


问:
Strange behavior of cin
I've been practicing a bit of C ++. It is a simple program, however i've playing with the terminal and I noticed a strange behavior when entering the password in 'input'. It appears that the buffer 'triggers' before the 'Give me the password' message. How could I avoid this strange behavior?.

I'm using Eclipse IDE for C/C++ Developers

Version: Neon.3 Release (4.6.3)
Build id: 20170314-1500

Thanks in advance

```<code>#include <iostream>

using namespace std;

/*  DO WHILE EXAMPLE*/
int main() {

    const string password = "car";
    string input;
    do {
        cout << "Give me the password\n";
        cin >> input;

    if (input != password) {
            cout << "Incorrect Password\n";
    }

    } while (input != password);
    cout << "Correct Password";
    return 0;
}
</code>```

This the Correct Behavior

This the Incorrect Behavior

答:
That's really weird. There doesn't seem to be a reason besides the compiler producing bad code for your OS or something. I recommend getting Visual Studio 2017 if that's possible.

Try a wait after you write to cout.

Title: Strange behavior of cin

Body:
I've been practicing a bit of C ++. It is a simple program, however i've playing with the terminal and I noticed a strange behavior when entering the password in 'input'. It appears that the buffer 'triggers' before the 'Give me the password' message. How could I avoid this strange behavior?.

I'm using Eclipse IDE for C/C++ Developers

Version: Neon.3 Release (4.6.3)
Build id: 20170314-1500

Thanks in advance

#include <iostream>

using namespace std;

/*  DO WHILE EXAMPLE*/
int main() {

    const string password = "car";
    string input;
    do {
        cout << "Give me the password\n";
        cin >> input;

    if (input != password) {
            cout << "Incorrect Password\n";
    }

    } while (input != password);
    cout << "Correct Password";
    return 0;
}

This the Correct Behavior

This the Incorrect Behavior


问:
Convert Thread.Join(timeLapse) to equivalent non-thread pattern
I have the following code:

```<code>Thread validationThread = new Thread(DoAsyncValidationMethod);

validationThread.Start(threadParams);

bool isAborted = false;

int timeLeft = 5000;

// wait for thread terminates itself
if (!validationThread.Join(timeLeft))
{
    // timeout, abort thread
    validationThread.Abort();
    isAborted = true;
}
</code>```

In other words, I'm doing some work that is supposed to complete in the time lapse specified (5000 ms). If completed or not, the thread approach taken will guarantee the code returns no later than 5 sec after it started.

Is there a way to accomplish this with the async/await pattern? or since the thread is just used for the trick, is there any other approach to take?

The more elegant and simple, the better.
Thank you for the help.

答:
You can do this nicely with Microsoft's Reactive Framework (NuGet "System.Reactive"). Then you can do this:</p>

```<code>IObservable<bool> query =
    Observable.Amb(
        Observable.Timer(TimeSpan.FromSeconds(5.0)).Select(_ => false),
        Observable.Start(() => DoAsyncValidationMethod()).Select(_ => true));

IDisposable subscription =
    query.Subscribe(flag =>
    {
        /* `true` succeeded, `false` timed out */
    });
</code>```

Body:
I have the following code:

Thread validationThread = new Thread(DoAsyncValidationMethod);

validationThread.Start(threadParams);

bool isAborted = false;

int timeLeft = 5000;

// wait for thread terminates itself
if (!validationThread.Join(timeLeft))
{
    // timeout, abort thread
    validationThread.Abort();
    isAborted = true;
}

In other words, I'm doing some work that is supposed to complete in the time lapse specified (5000 ms). If completed or not, the thread approach taken will guarantee the code returns no later than 5 sec after it started.

Is there a way to accomplish this with the async/await pattern? or since the thread is just used for the trick, is there any other approach to take?

The more elegant and simple, the better.
Thank you for the help.

Body:
You can do this nicely with Microsoft's Reactive Framework (NuGet "System.Reactive"). Then you can do this:

IObservable<bool> query =
    Observable.Amb(
        Observable.Timer(TimeSpan.FromSeconds(5.0)).Select(_ => false),
        Observable.Start(() => DoAsyncValidationMethod()).Select(_ => true));

IDisposable subscription =
    query.Subscribe(flag =>
    {
        /* `true` succeeded, `false` timed out */
    });


问:
What's a good, efficient way to implement run()?
Should it just contain a loop like ```while (true) { ... }```

I find it not so efficient as it consumes the CPU so much. I would like my thread to keep on waiting for something but what's the best way to make it wait without consuming so much CPU?

答: Don't do while(true) {}. If you are waiting for some event, do wait()-notify() mechanism. Otherwise, use sleep(nsecs).

ContentLicense: CC BY-SA 2.5

Body:
Should it just contain a loop like
while (true) { ... }

I find it not so efficient as it consumes the CPU so much. I would like my thread to keep on waiting for something but what's the best way to make it wait without consuming so much CPU?


问:
SQL Server - Values multiplied by join
having a bit of trouble with this one...

The summed, grouped column TotalStoreVisitTime is being multiplied due to the left join further down. I have attempted sub-queries but cannot successfully implement. Someone else I have spoken with has attempted this using cursors etc. but it seems over complicated.

```<code>SELECT t1.StaffName                 AS "Staff Name"
       ,MIN(t1.ManagerName)         AS "Manager"
       ,t1.Name                     AS "Store"
       ,t1.StartDate                AS "Date"
       ,SUM(t1.TotalStoreVisitTime) AS "Total Store Time" -- this value gets multiplied by the LEFT JOIN further down.
       ,SUM(t2.TotalClientTime)     AS "Total Client Time"
FROM   t1
       LEFT JOIN t2
              ON t1.StaffName =
                 t2.StaffName
                 AND t1.Name = t2.Store
                 AND t1.StartDate =
                     t2.StartDate
WHERE  t1.StartDate >= DATEADD(DAY, -7, GETDATE())
GROUP  BY t1.StaffName
          ,t1.Name
          ,t1.StartDate
ORDER  BY t1.StartDate DESC;
</code>```

The output is as follows:

```<code>| Staff Name |  Manager   |   Store    |   Date    | Total Store Time | Total Client Time |
|------------|------------|------------|-----------|------------------|-------------------|
| John Smith | Jane Smith | Test Store | 6/07/2017 |        25.899996 |          4.033332 |
</code>```

The desired output is this (i.e. with Total Store Time just summing the rows from t1 and not being multiplied by the number of rows in t2):

```<code>| Staff Name |  Manager   |   Store    |   Date    | Total Store Time | Total Client Time |
|------------|------------|------------|-----------|------------------|-------------------|
| John Smith | Jane Smith | Test Store | 6/07/2017 |         4.316666 |          4.033332 |
</code>```

答:
You need to aggregate before the join.  I think this might work:

```<code>SELECT t1.StaffName                 AS "Staff Name" ,
       t1.Manager                  AS "Manager",
       t1.Name                     AS "Store" ,
       t1.StartDate                AS "Date" ,
       t1.tot AS "Total Store Time", -- this value gets multiplied by the LEFT JOIN further down.
       SUM(t2.TotalClientTime)     AS "Total Client Time"
FROM (SELECT t1.StaffName, t1.Name, t1.StartDate,
             SUM(t1.TotalStoreVisitTime) as tot,
             MIN(t1.ManagerName) as manager
      FROM t1
      WHERE t1.StartDate >= DATEADD(DAY, -7, GETDATE())
     ) t1 LEFT JOIN
     t2
     ON t1.StaffName = t2.StaffName AND
        t1.Name = t2.Store AND
        t1.StartDate = t2.StartDate
GROUP BY t1.StaffName, t1.Name, t1.StartDate
ORDER BY t1.StartDate DESC;
</code>```

Title: SQL Server - Values multiplied by join

Body:
having a bit of trouble with this one...

The summed, grouped column TotalStoreVisitTime is being multiplied due to the left join further down. I have attempted sub-queries but cannot successfully implement. Someone else I have spoken with has attempted this using cursors etc. but it seems over complicated.

SELECT t1.StaffName                 AS "Staff Name"
       ,MIN(t1.ManagerName)         AS "Manager"
       ,t1.Name                     AS "Store"
       ,t1.StartDate                AS "Date"
       ,SUM(t1.TotalStoreVisitTime) AS "Total Store Time" -- this value gets multiplied by the LEFT JOIN further down.
       ,SUM(t2.TotalClientTime)     AS "Total Client Time"
FROM   t1
       LEFT JOIN t2
              ON t1.StaffName =
                 t2.StaffName
                 AND t1.Name = t2.Store
                 AND t1.StartDate =
                     t2.StartDate
WHERE  t1.StartDate >= DATEADD(DAY, -7, GETDATE())
GROUP  BY t1.StaffName
          ,t1.Name
          ,t1.StartDate
ORDER  BY t1.StartDate DESC;

The output is as follows:

| Staff Name |  Manager   |   Store    |   Date    | Total Store Time | Total Client Time |
|------------|------------|------------|-----------|------------------|-------------------|
| John Smith | Jane Smith | Test Store | 6/07/2017 |        25.899996 |          4.033332 |

The desired output is this (i.e. with Total Store Time just summing the rows from t1 and not being multiplied by the number of rows in t2):

| Staff Name |  Manager   |   Store    |   Date    | Total Store Time | Total Client Time |
|------------|------------|------------|-----------|------------------|-------------------|
| John Smith | Jane Smith | Test Store | 6/07/2017 |         4.316666 |          4.033332 |

Body:
You need to aggregate before the join.  I think this might work:

SELECT t1.StaffName                 AS "Staff Name" ,
       t1.Manager                  AS "Manager",
       t1.Name                     AS "Store" ,
       t1.StartDate                AS "Date" ,
       t1.tot AS "Total Store Time", -- this value gets multiplied by the LEFT JOIN further down.
       SUM(t2.TotalClientTime)     AS "Total Client Time"
FROM (SELECT t1.StaffName, t1.Name, t1.StartDate,
             SUM(t1.TotalStoreVisitTime) as tot,
             MIN(t1.ManagerName) as manager
      FROM t1
      WHERE t1.StartDate >= DATEADD(DAY, -7, GETDATE())
     ) t1 LEFT JOIN
     t2
     ON t1.StaffName = t2.StaffName AND
        t1.Name = t2.Store AND
        t1.StartDate = t2.StartDate
GROUP BY t1.StaffName, t1.Name, t1.StartDate
ORDER BY t1.StartDate DESC;


问:
How can I get all of the average of values of each respective column of nested numpy arrays?
I am having trouble performing a column-wise operation for each column of a dim-2 numpy array. I am trying to adapt my case to this answer, though my setup is different. My actual dataset is quite large and involves multiple resamplings, hence the syntax of the example below. If the code and explanation looks too long, consider skipping ahead to the header Relevant.

Skippable (Only here to reproduce zs below)

Consider an (x_n, y_n) dataset where n = 0, 1, or 2.

```<code>def get_xy(num, size=10):
    ## (x1, y1), (x2, y2), (x3, y3) where xi, yi are both arrays
    if num == 0:
        x = np.linspace(7, size+6, size)
        y = np.linspace(3, size+2, size)
    elif num == 1:
        x = np.linspace(5, size+4, size)
        y = np.linspace(2, size+1, size)
    elif num == 2:
        x = np.linspace(4, size+3, size)
        y = np.linspace(1, size, size)
    return x, y
</code>```

Suppose we can calculate some metric z_n given arrays x_n and y_n.

```<code>def get_single_z(x, y, constant=2):
    deltas = [x[i] - y[i] for i in range(len(x)) if len(x) == len(y)]
    return constant * np.array(deltas)
</code>```

Instead of calculating each z_n individually, we can calculate all z_n's at once.

```<code>def get_all_z(constant=2):
    zs = []
    for num in range(3): ## 0, 1, 2
        xs, ys = get_xy(num)
        zs.append(get_single_z(xs, ys, constant))
    zs = np.array(zs)
    return zs
</code>```

Relevant:

```<code>zs = get_all_z()
print(zs)
>> [[ 8.  8.  8.  8.  8.  8.  8.  8.  8.  8.]
    [ 6.  6.  6.  6.  6.  6.  6.  6.  6.  6.]
    [ 6.  6.  6.  6.  6.  6.  6.  6.  6.  6.]]
</code>```

For my purpose, I'd like to make a new list or array vs for which the value at each index is equal to the average of the values in the corresponding columns of zs. For this case, every element of vs would be identical (since each operation would be the average of [8, 6, 6]). But had the first element of the first sub-array been a 10 instead of an 8, then the first element of vs would be the average of [10, 6, 6].

Unsuccessful Attempt:

```<code>def get_avg_per_col(z):
    ## column ?= axis number
    return [np.mean(z, axis=i) for i in range(len(zs[0]))]

print(get_avg_per_col(zs))
Traceback (most recent call last):...
...line 50, in _count_reduce_items ## of numpy code, not my code
    items *= arr.shape[ax]
IndexError: tuple index out of range
</code>```

Body:
I am having trouble performing a column-wise operation for each column of a dim-2 numpy array. I am trying to adapt my case to this answer, though my setup is different. My actual dataset is quite large and involves multiple resamplings, hence the syntax of the example below. If the code and explanation looks too long, consider skipping ahead to the header Relevant.

Skippable (Only here to reproduce zs below)

Consider an (x_n, y_n) dataset where n = 0, 1, or 2.

def get_xy(num, size=10):
    ## (x1, y1), (x2, y2), (x3, y3) where xi, yi are both arrays
    if num == 0:
        x = np.linspace(7, size+6, size)
        y = np.linspace(3, size+2, size)
    elif num == 1:
        x = np.linspace(5, size+4, size)
        y = np.linspace(2, size+1, size)
    elif num == 2:
        x = np.linspace(4, size+3, size)
        y = np.linspace(1, size, size)
    return x, y

Suppose we can calculate some metric z_n given arrays x_n and y_n.

def get_single_z(x, y, constant=2):
    deltas = [x[i] - y[i] for i in range(len(x)) if len(x) == len(y)]
    return constant * np.array(deltas)

Instead of calculating each z_n individually, we can calculate all z_n's at once.

def get_all_z(constant=2):
    zs = []
    for num in range(3): ## 0, 1, 2
        xs, ys = get_xy(num)
        zs.append(get_single_z(xs, ys, constant))
    zs = np.array(zs)
    return zs

Relevant:

zs = get_all_z()
print(zs)
>> [[ 8.  8.  8.  8.  8.  8.  8.  8.  8.  8.]
    [ 6.  6.  6.  6.  6.  6.  6.  6.  6.  6.]
    [ 6.  6.  6.  6.  6.  6.  6.  6.  6.  6.]]

For my purpose, I'd like to make a new list or array vs for which the value at each index is equal to the average of the values in the corresponding columns of zs. For this case, every element of vs would be identical (since each operation would be the average of [8, 6, 6]). But had the first element of the first sub-array been a 10 instead of an 8, then the first element of vs would be the average of [10, 6, 6].

Unsuccessful Attempt:

def get_avg_per_col(z):
    ## column ?= axis number
    return [np.mean(z, axis=i) for i in range(len(zs[0]))]

print(get_avg_per_col(zs))
Traceback (most recent call last):...
...line 50, in _count_reduce_items ## of numpy code, not my code
    items *= arr.shape[ax]
IndexError: tuple index out of range

Body:
You can use np.mean on the transposed zs to get the column wise mean.

In [49]: import numpy as np

In [53]: zs = np.array([[ 8.,  8.,  8.,  8.,  8.,  8.,  8.,  8.,  8.,  8.],
    ...:  [ 6.,  6.,  6.,  6.,  6.,  6.,  6.,  6.,  6.,  6.],
    ...:  [ 6.,  6.,  6.,  6.,  6.,  6.,  6.,  6.,  6.,  6.]])

In [54]: np.mean(zs.T, axis=1)
Out[54]:
array([ 6.66666667,  6.66666667,  6.66666667,  6.66666667,  6.66666667,
        6.66666667,  6.66666667,  6.66666667,  6.66666667,  6.66666667])


问:
Can an Azure NIC be pointed to records one created in an Azure DNS zone?
Is there a way to point an Azure NIC to the records one created in an Azure DNS zone?

答:
We can't add Azure DNS zone to NIC custom DNS. The custom DNS required IP address, we can add the DNS server IP address to it.

 For example, we can add 8.8.8.8 to it, also we can add local DNS server IP address to it(need VPN). Or create a Azure windows VM and install DNS role on it, and add this VM ip address to it.

If you want to use Azure DNS zone to manage your records, we can map your own domain name to DNS zone, and add name servers to your domain name(add this by domain name registrar manage webpage).

The following image shows an example DNS query about Azure DNS zone:

If you want to add record to DNS zone, and you want to map your 3rd party domain name map to Azure DNS zone, we can follow those steps in that answer.

Note:

Keep in mind Azure DNS is not the domain registrar, we should buy domain name from domain registrar(like godaddy, register.com).

Update:

If you just want to use domain name in your virtual network, there is no need to buy a domain, we can use AAD DS in our virtual network. Or we can deploy a VM and install DC on it, work as on-prem.

By the way, in the same virtual network, we can ping VM's name by default.


问:
How to authenticate user accessing my finatra rest api (Scala) with azure active directory
I have a Scala rest service on Finatra and would like to authenticate users accessing my rest service using Azure Active Directory.

Currently, I can do a curl to get the access token:

```<code>curl -s -X POST https://login.microsoftonline.com/tenant id/oauth2/token -d grant_type=password -d username=$username -d password=$pass  -d resource=$resID -d client_id=$id -d client_secret=$key
</code>```

But it requires the user to pass his password as a parameter which is a security concern.

Is there a way to authenticate the user using Azure AD with taking in the password (I am pretty sure this is not possible) or asking him to sign in?

答:
It is not recommended to use your user and password to login Azure account. You had better create service principal to sign in your Azure account. Please refer to this link: Use portal to create an Azure Active Directory application and service principal that can access resources.

Also, you could use Azure CLI 2.0 to create this.

```<code>az ad sp create-for-rbac --name {appId} --password "{strong password}"
</code>```

Example:

```<code>az ad sp create-for-rbac --name shuiexample --password "Password012!!"
</code>```

You could get result like below:

```<code>{
  "appId": "bca24913-026d-4020-b9f1-add600bf9045",
  "displayName": "shuiexample1234",
  "name": "http://shuiexample1234",
  "password": "*******",
  "tenant": "*******"
}
</code>```

Sign in using the service principal.

```<code>APPID="bca24913-026d-4020-b9f1-add600bf9045"
PASSWORD="******"
TENANTID="*******"

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'client_id=$APPID&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=$PASSWORD&grant_type=client_credentials' 'https://login.microsoftonline.com/$TENANTID/oauth2/token'
</code>```

Body:
I have a Scala rest service on Finatra and would like to authenticate users accessing my rest service using Azure Active Directory.

Currently, I can do a curl to get the access token:

curl -s -X POST https://login.microsoftonline.com/tenant id/oauth2/token -d grant_type=password -d username=$username -d password=$pass  -d resource=$resID -d client_id=$id -d client_secret=$key

But it requires the user to pass his password as a parameter which is a security concern.

Is there a way to authenticate the user using Azure AD with taking in the password (I am pretty sure this is not possible) or asking him to sign in?

Body:
It is not recommended to use your user and password to login Azure account. You had better create service principal to sign in your Azure account. Please refer to this link: Use portal to create an Azure Active Directory application and service principal that can access resources.

Also, you could use Azure CLI 2.0 to create this.

az ad sp create-for-rbac --name {appId} --password "{strong password}"

Example:

az ad sp create-for-rbac --name shuiexample --password "Password012!!"

You could get result like below:

{
  "appId": "bca24913-026d-4020-b9f1-add600bf9045",
  "displayName": "shuiexample1234",
  "name": "http://shuiexample1234",
  "password": "*******",
  "tenant": "*******"
}

Sign in using the service principal.

APPID="bca24913-026d-4020-b9f1-add600bf9045"
PASSWORD="******"
TENANTID="*******"

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'client_id=$APPID&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=$PASSWORD&grant_type=client_credentials' 'https://login.microsoftonline.com/$TENANTID/oauth2/token'


问:
Running a self-contained ASP.NET Core application on Ubuntu
I've published an ASP.NET Core application as a self-contained application targeting Ubuntu. The publish seems to work fine. I've copied the files to a pretty vanilla Ubuntu machine. Now, how do I run my application?

My understanding is that because it is a self-contained .NET Core application I do not need to download and install .NET Core anything. My application should contain everything it needs.

All tutorials seem to say I should call dotnet run. However, the "dotnet" command line doesn't exist (is it supposed to be published into the self-contained folder??) So if I call it, I get "command not found". Of course I could download .NET Core, but doesn't that go against the whole self-contained concept?

Here is a sample of the files I'm copying over:

答:
It's worth noting that with the .NET Standard 2+, there are two required steps:

Edit the .csproj file and add a line with a list of target runtimes:

<PropertyGroup>

```<code><OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>

<!-- Add this with the required runtimes -->
<RuntimeIdentifiers>win10-x64;osx.10.11-x64;ubuntu.16.10-x64</RuntimeIdentifiers>
</code>```

</PropertyGroup>

Restore and build the app: dotnet restore && dotnet build -c release -r RUNTIME

Where RUNTIME is one of the runtimes listed in the .csproj file.

Importantly note that you cannot do this without the .csproj file edit and calling dotnet restore, or the runtime will not be downloaded from NuGet, and the -r ... flag will not work.

ContentLicense: CC BY-SA 4.0

Body:
It's worth noting that with the .NET Standard 2+, there are two required steps:

Edit the .csproj file and add a line with a list of target runtimes:

<PropertyGroup>

<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>

<!-- Add this with the required runtimes -->
<RuntimeIdentifiers>win10-x64;osx.10.11-x64;ubuntu.16.10-x64</RuntimeIdentifiers>

</PropertyGroup>

Restore and build the app: dotnet restore && dotnet build -c release -r RUNTIME

Where RUNTIME is one of the runtimes listed in the .csproj file.

Importantly note that you cannot do this without the .csproj file edit and calling dotnet restore, or the runtime will not be downloaded from NuGet, and the -r ... flag will not work.


问:
How to put navigation bar or something above XLPagerTabStrip
I'm new to iOS programming and got stuck using XLPagerTabStrip(github.com/xmartlabs/XLPagerTabStrip).
I followed its tutorial and successfully added PagerTab on the top of VC.
However, I can't add something like navbar on the top of VC, above the PagerTab. The PagerTab always go to the top even though I set layouts using storyboard. The tutorial doesn't help me, and there are similar questions in github issues and this website, but I can't find answer to my problem. I'd appreciate it if you teach me how to solve it.

My storybord
The output

答:
As refer to your storyboard, you have not added the UINavigationbarController.

Select the ViewController in storyboard.

On Xcode menu, select Editor > Embed In > Navigation Controller

Run and check

This issue not relate to XLPagerTabStrip, it is UINavigationController itself. Refer Apple tutorial for details.


问:
Delay load of iframe?
I know there are some tools and techniques for delaying the load of javascript, but I have an iframe that I would like to delay loading until after the rest of the page has finished downloading and rendering (the iframe is in a hidden  that will not be revealed until someone clicks on a particular tab on the page.  Is there a way to delay the load of an iframe?  Any suggestions would be much appreciated.  Thanks! </p>

答:
You can also apply display:none to the iframe with CSS, then use jQuery's .show like this:</p>

```<code>$(document).ready(function(){
    $('iframe.class_goes_here').show();
});
</code>```

Title: Delay load of iframe?

Body:
You can also apply display:none to the iframe with CSS, then use jQuery's .show like this:

$(document).ready(function(){
    $('iframe.class_goes_here').show();
});


问:
Amazon Lightsail Subdomain Setup
I'm currently moving all of my hosting from a cheap shared hosting provider over to Amazon LightSail.  Normally, when sending work over to clients for approval, I create a subdomain through my hosting provider's c-panel and upload the required files through FTP.

I am at a loss when it comes to setting up a subdomain through AWS Lightsail though.  I've created a static IP and I've created the A record for the subdomain, but where do I put the directory that the files I want my client review for that subdomain sit and what IP address do I need to point the subdomain at?

答:
AWS LightSail is different from shared hosting providers, where AWS provides Virtual Private Servers(VPS) with its own IP.

Generally VPS is for a single deployment of an application(e.g Single Wordpress Deployment per VPS). So it is recommended to get multiple VPS for your deployments unless your applications are really light weight and gets less traffic.

There is also a limit where you gets 2 VPS servers per AWS account by default. If you need more VPS, either you can send a support request to Amazon and increase the limit or use multiple AWS accounts (If you own the AWS accounts, you can setup consolidated billing)

In DNS setup, since its single application per VPS, you need to create a A record for each subdomain.

Title: Amazon Lightsail Subdomain Setup


问:
Bootstrap 4 - DropDown menu - Element is over navbar
I have problem with DropDown menu. When I'm trying to add padding to DropDown menu (class - drop_link) It pushes whole element over . I don't really know how stop this from happening. I tried turn off some attributes from browser, but It didn't do anything.

Here is my attempt: Link

答:
You can add the following styles to your  element inside your "dropdown" div.

```<code>display: block;
float: left;
</code>```

And, remove "margin-left: 3px;" from your "dropdown" div.

This is only one between many possible solutions.

cheers

Body:
You can add the following styles to your <a> element inside your "dropdown" div.

display: block;
float: left;

And, remove "margin-left: 3px;" from your "dropdown" div.

This is only one between many possible solutions.

cheers


问:
C++ cin Question
Okay, I was writing a simple C++ function to combine cin'd strings. I'm working on Linux at the moment, so I don't have the luxury of a simple "getline(cin, input)" command. Here's the code so far:

```<code>string getLine()
{
    string dummy;
    string retvalue;
    do
    {
        cin << dummy;
        retvalue += dummy;
    } while
    return retvalue;
}
</code>```

What I want to know is this: is the prompt actually asking the user for input, or is it still reading from the buffer that was left over because of a space?

答:
getline() is in the <string> header

I always forget that.

Title: C++ cin Question

Body:
Okay, I was writing a simple C++ function to combine cin'd strings. I'm working on Linux at the moment, so I don't have the luxury of a simple "getline(cin, input)" command. Here's the code so far:

string getLine()
{
    string dummy;
    string retvalue;
    do
    {
        cin << dummy;
        retvalue += dummy;
    } while
    return retvalue;
}

What I want to know is this: is the prompt actually asking the user for input, or is it still reading from the buffer that was left over because of a space?


问:
Convert c# console output to Textbox output
I'm very new in CSharp and I know you found this question very stupid, I need  an idea how to convert the output from console to textbox. thanks</p>

```<code>foreach (DriveInfo d in allDrives)
{
    Console.WriteLine("Drive {0}", d.Name);
    Console.WriteLine("  Drive type: {0}", d.DriveType);
    if (d.IsReady == true)
    {
        Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
        Console.WriteLine("  File system: {0}", d.DriveFormat);
        Console.WriteLine(
           "  Available space to current user:{0, 15} bytes",
           d.AvailableFreeSpace);

        Console.WriteLine(
           "  Total available space:          {0, 15} bytes",
           d.TotalFreeSpace);

        Console.WriteLine(
           "  Total size of drive:            {0, 15} bytes ",
           d.TotalSize);
    }
    Console.ReadKey(true);
}
</code>```

答:
Console.WriteLine is calls a WriteLine on an internal StreamWriter whose stream is the Console.Output.

What you can do is use another object, like a StringBuilder and write your results to the StringBuilder and then set the Text from the string result of StringBuilder.ToString()

```<code>StringBuilder sb = new StringBuilder();
sb.AppendFormat("Drive {0}\n", d.Name);
sb.AppendFormat("  Drive type: {0}\n", d.DriveType);
    if (d.IsReady == true)

    {
        sb.AppendFormat("  Volume label: {0}\n", d.VolumeLabel);
        sb.AppendFormat("  File system: {0}\n", d.DriveFormat);
        sb.AppendFormat(
            "  Available space to current user:{0, 15} bytes\n",
            d.AvailableFreeSpace);

         sb.AppendFormat(
            "  Total available space:          {0, 15} bytes\n",
            d.TotalFreeSpace);

         sb.AppendFormat(
            "  Total size of drive:            {0, 15} bytes \n",
            d.TotalSize);
    }
txtBox1.Text = sb.ToString();
</code>```

Alternately in your loop, you can just add new lines of text to your TextBox

```<code>    txtBox.Text += String.Format(("Drive {0}\n", d.Name);
    txtBox.Text += String.Format(("  Drive type: {0}\n", d.DriveType);
    if (d.IsReady == true)

    {
        txtBox.Text += String.Format(("  Volume label: {0}\n", d.VolumeLabel);
        txtBox.Text += String.Format(("  File system: {0}\n", d.DriveFormat);
        txtBox.Text += String.Format((
            "  Available space to current user:{0, 15} bytes\n",
            d.AvailableFreeSpace);

        txtBox.Text +=String.Format((
            "  Total available space:          {0, 15} bytes\n",
            d.TotalFreeSpace);

        txtBox.Text +=String.Format((
            "  Total size of drive:            {0, 15} bytes \n",
            d.TotalSize);
    }
</code>```

Body:
I'm very new in CSharp and I know you found this question very stupid, I need  an idea how to convert the output from console to textbox. thanks

foreach (DriveInfo d in allDrives)
{
    Console.WriteLine("Drive {0}", d.Name);
    Console.WriteLine("  Drive type: {0}", d.DriveType);
    if (d.IsReady == true)
    {
        Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
        Console.WriteLine("  File system: {0}", d.DriveFormat);
        Console.WriteLine(
           "  Available space to current user:{0, 15} bytes",
           d.AvailableFreeSpace);

        Console.WriteLine(
           "  Total available space:          {0, 15} bytes",
           d.TotalFreeSpace);

        Console.WriteLine(
           "  Total size of drive:            {0, 15} bytes ",
           d.TotalSize);
    }
    Console.ReadKey(true);
}

Body:
Console.WriteLine is calls a WriteLine on an internal StreamWriter whose stream is the Console.Output.

What you can do is use another object, like a StringBuilder and write your results to the StringBuilder and then set the Text from the string result of StringBuilder.ToString()

StringBuilder sb = new StringBuilder();
sb.AppendFormat("Drive {0}\n", d.Name);
sb.AppendFormat("  Drive type: {0}\n", d.DriveType);
    if (d.IsReady == true)

    {
        sb.AppendFormat("  Volume label: {0}\n", d.VolumeLabel);
        sb.AppendFormat("  File system: {0}\n", d.DriveFormat);
        sb.AppendFormat(
            "  Available space to current user:{0, 15} bytes\n",
            d.AvailableFreeSpace);

         sb.AppendFormat(
            "  Total available space:          {0, 15} bytes\n",
            d.TotalFreeSpace);

         sb.AppendFormat(
            "  Total size of drive:            {0, 15} bytes \n",
            d.TotalSize);
    }
txtBox1.Text = sb.ToString();

Alternately in your loop, you can just add new lines of text to your TextBox

    txtBox.Text += String.Format(("Drive {0}\n", d.Name);
    txtBox.Text += String.Format(("  Drive type: {0}\n", d.DriveType);
    if (d.IsReady == true)

    {
        txtBox.Text += String.Format(("  Volume label: {0}\n", d.VolumeLabel);
        txtBox.Text += String.Format(("  File system: {0}\n", d.DriveFormat);
        txtBox.Text += String.Format((
            "  Available space to current user:{0, 15} bytes\n",
            d.AvailableFreeSpace);

        txtBox.Text +=String.Format((
            "  Total available space:          {0, 15} bytes\n",
            d.TotalFreeSpace);

        txtBox.Text +=String.Format((
            "  Total size of drive:            {0, 15} bytes \n",
            d.TotalSize);
    }


问:
Storing contents of a text file in a dictonary
I would like to store a bunch of letters and corresponding values for them in a text file and then have the code go through and store all that in a dictionary

for example
the text file
A = #
B = %

The dictionary will contain

```<code>Dict = {'A':'#', 'B':'%'}
</code>```

how would I go about doing this in python and what should the text file look like?

Please note that each bit of information and its corresponding value will be on a new line

So far i have

```<code>d = {}
with open("data.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[key] = val
print(d)
</code>```

but it does not seem to work

答:
```<code># to read/load data from the file:
d = {}
with open(filename, 'r') as f:
    for line in f:
        a, b = line.split('=')
        d[a.strip()] = b.strip()
</code>```

To write to the file format output string for each line and then use either write or writelines method. Do a search and you will find plenty of information. You will need to iterate over dictionary's items like this:

```<code>for k, v in d.items():
    s = "{} = {}".format(k,v)
    # write s to file...
</code>```

Body:
I would like to store a bunch of letters and corresponding values for them in a text file and then have the code go through and store all that in a dictionary

for example
the text file
A = #
B = %

The dictionary will contain

Dict = {'A':'#', 'B':'%'}

how would I go about doing this in python and what should the text file look like?

Please note that each bit of information and its corresponding value will be on a new line

So far i have

d = {}
with open("data.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[key] = val
print(d)

but it does not seem to work

Body:
# to read/load data from the file:
d = {}
with open(filename, 'r') as f:
    for line in f:
        a, b = line.split('=')
        d[a.strip()] = b.strip()

To write to the file format output string for each line and then use either write or writelines method. Do a search and you will find plenty of information. You will need to iterate over dictionary's items like this:

for k, v in d.items():
    s = "{} = {}".format(k,v)
    # write s to file...


问:
Video rotated after applying AVVideoComposition
After applying an AVVideoComposition to my AVPlayerItem, the filter I apply does work, but the video gets rotated in the AVPlayerLayer.

I know for a fact that the problem is not with the filtered frame because if I show the frame in a UIImageView, the frame is rendered 100% correctly.

The video shows correctly until I apply a videoComposition. Setting the videoGravity on the AVPlayerLayer does not help.

The video gets rotated 90º clockwise and gets stretched in the layer.

Essentially, the video is displayed perfectly in the AVPlayerLayer before the AVPlayerItem is fed through the AVMutableVideoComposition. Once that happens, the video is rotated -90º, and then scaled to fit the same dimensions as the video before filtering. This suggests to me that it does not realize that its transform is already correct, and so it is reapplying the transform on itself.

Why is this happening, and how can I fix it?

Here is some code:

```<code>private func filterVideo(with filter: Filter?) {
    if let player = player, let playerItem = player.currentItem {
        let composition = AVMutableComposition()
        let videoAssetTrack = playerItem.asset.tracks(withMediaType: .video).first
        let videoCompositionTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
        try? videoCompositionTrack?.insertTimeRange(CMTimeRange(start: kCMTimeZero, duration: playerItem.asset.duration), of: videoAssetTrack!, at: kCMTimeZero)
        videoCompositionTrack?.preferredTransform = videoAssetTrack!.preferredTransform

        let videoComposition = AVMutableVideoComposition(asset: composition, applyingCIFiltersWithHandler: { (request) in
            let filteredImage = <...>
            request.finish(with: filteredImage, context: nil)
        })

        playerItem.videoComposition = videoComposition
    }
}
</code>```

答:
Instead of assuming that the image will be filtered, check first if filteredImage is nil. If not, then request.finish(with: filteredImage, context: nil)

However, if it is nil you must request.finish(with: SomeError)

This is as per the docs.

Body:
After applying an AVVideoComposition to my AVPlayerItem, the filter I apply does work, but the video gets rotated in the AVPlayerLayer.

I know for a fact that the problem is not with the filtered frame because if I show the frame in a UIImageView, the frame is rendered 100% correctly.

The video shows correctly until I apply a videoComposition. Setting the videoGravity on the AVPlayerLayer does not help.

The video gets rotated 90º clockwise and gets stretched in the layer.

Essentially, the video is displayed perfectly in the AVPlayerLayer before the AVPlayerItem is fed through the AVMutableVideoComposition. Once that happens, the video is rotated -90º, and then scaled to fit the same dimensions as the video before filtering. This suggests to me that it does not realize that its transform is already correct, and so it is reapplying the transform on itself.

Why is this happening, and how can I fix it?

Here is some code:

private func filterVideo(with filter: Filter?) {
    if let player = player, let playerItem = player.currentItem {
        let composition = AVMutableComposition()
        let videoAssetTrack = playerItem.asset.tracks(withMediaType: .video).first
        let videoCompositionTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
        try? videoCompositionTrack?.insertTimeRange(CMTimeRange(start: kCMTimeZero, duration: playerItem.asset.duration), of: videoAssetTrack!, at: kCMTimeZero)
        videoCompositionTrack?.preferredTransform = videoAssetTrack!.preferredTransform

        let videoComposition = AVMutableVideoComposition(asset: composition, applyingCIFiltersWithHandler: { (request) in
            let filteredImage = <...>
            request.finish(with: filteredImage, context: nil)
        })

        playerItem.videoComposition = videoComposition
    }
}


问:
Nothing Happens after Clicking the Submit Button
With the generated code, one of my entities can not be saved. On the 8080 port, the form remains the same and nothing shows up on the console after I click the submit button. On the 9000 port, however, a log message shows fetching for related entities from the database after I click the button. There isn't an error message on any console, including the browser's console. In the dialog.html file, the first line is as follows:

```<code>    <form name="editForm" role="form" novalidate ng-submit="vm.save()"
 show-validation>
</code>```

so I insert the log in the first line of the Javascript function of the dialog.controller.js:

```<code>function save () {
    console.log("Saving ...");
...
</code>```

How should I resolve it?

The structure of the controller is the followings:

```<code>(function() {
'use strict';

angular
    .module('myApp')
    .controller('MyDialogController', MyDialogController);

SkuSDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'DataUtils', 'entity', 'MyEntity', 'MyRelatedEntity'];

function SkuSDialogController ($timeout, $scope, $stateParams, $uibModalInstance, DataUtils, entity, MyEntity, MyRelatedEntity) {
    var vm = this;

    ...
    vm.clear = clear;
    vm.datePickerOpenStatus = {};
    vm.openCalendar = openCalendar;
    vm.byteSize = DataUtils.byteSize;
    vm.openFile = DataUtils.openFile;
    vm.save = save;
    ...

    $timeout(function (){
        angular.element('.form-group:eq(1)>input').focus();
    });

    function clear () {
        $uibModalInstance.dismiss('cancel');
    }

    function save () {
    console.log("Saving ...");
        vm.isSaving = true;
        if (vm.myEntity.id !== null) {
            MyEntity.update(vm.myEntity, onSaveSuccess, onSaveError);
        } else {
            MyEntity.save(vm.myEntity, onSaveSuccess, onSaveError);
        }
    }

    function onSaveSuccess (result) {
        $scope.$emit('myApp:myEntityUpdate', result);
        $uibModalInstance.close(result);
        vm.isSaving = false;
    }

    function onSaveError () {
        vm.isSaving = false;
    }

    vm.datePickerOpenStatus.activeStartDate = false;
    vm.datePickerOpenStatus.activeEndDate = false;

    function openCalendar (date) {
        vm.datePickerOpenStatus[date] = true;
    }
  }
})();
</code>```

答:
Apply this in your html</p>

```<code><div ng-controller="(put here your controllerName) as vm">
</code>```

Body:
With the generated code, one of my entities can not be saved. On the 8080 port, the form remains the same and nothing shows up on the console after I click the submit button. On the 9000 port, however, a log message shows fetching for related entities from the database after I click the button. There isn't an error message on any console, including the browser's console. In the dialog.html file, the first line is as follows:

    <form name="editForm" role="form" novalidate ng-submit="vm.save()"
 show-validation>

so I insert the log in the first line of the Javascript function of the dialog.controller.js:

function save () {
    console.log("Saving ...");
...

How should I resolve it?

The structure of the controller is the followings:

(function() {
'use strict';

angular
    .module('myApp')
    .controller('MyDialogController', MyDialogController);

SkuSDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'DataUtils', 'entity', 'MyEntity', 'MyRelatedEntity'];

function SkuSDialogController ($timeout, $scope, $stateParams, $uibModalInstance, DataUtils, entity, MyEntity, MyRelatedEntity) {
    var vm = this;

    ...
    vm.clear = clear;
    vm.datePickerOpenStatus = {};
    vm.openCalendar = openCalendar;
    vm.byteSize = DataUtils.byteSize;
    vm.openFile = DataUtils.openFile;
    vm.save = save;
    ...

    $timeout(function (){
        angular.element('.form-group:eq(1)>input').focus();
    });

    function clear () {
        $uibModalInstance.dismiss('cancel');
    }

    function save () {
    console.log("Saving ...");
        vm.isSaving = true;
        if (vm.myEntity.id !== null) {
            MyEntity.update(vm.myEntity, onSaveSuccess, onSaveError);
        } else {
            MyEntity.save(vm.myEntity, onSaveSuccess, onSaveError);
        }
    }

    function onSaveSuccess (result) {
        $scope.$emit('myApp:myEntityUpdate', result);
        $uibModalInstance.close(result);
        vm.isSaving = false;
    }

    function onSaveError () {
        vm.isSaving = false;
    }

    vm.datePickerOpenStatus.activeStartDate = false;
    vm.datePickerOpenStatus.activeEndDate = false;

    function openCalendar (date) {
        vm.datePickerOpenStatus[date] = true;
    }
  }
})();

Body:
Apply this in your html

<div ng-controller="(put here your controllerName) as vm">


问:
MVC 4 SimpleMembership Model first
I have researched for the last couple days on Stack and other coding sites and cant seem to find a fix for my problem.

My goal is to configure simplemembership with my own database.(yes i have done a search and none of them answer my question)

I'm using visual studio 2013 and entity framework 4

I used the internet application template for asp.net mvc 4, that has already built in login.

I do as everyone else on line has done and seems to work for some, but most of the time they are left with no answer at all.

when i run my code and set the break points in the SimpleMembershipInitializer class. When I run it and click on register or login I step through the code and when it gets down to

WebSecurity.InitializeDatabaseConnection("AdventureWorksEntities", "mvcUser", "userID", "userName", autoCreateTables: false);

I get this error: "No user table found that has the name \"mvcUser\"."

what I know:

I know there is a table named "mvcUser"

I can CRUD the table and attribute in the table with in the site

If you want screen shots or more code please let me know.

Here is something similar to what I am looking/talking about but I don't understand what is meant by number 2 and 3 in the selected answer.

Controller

```<code>  [Authorize]
  [InitializeSimpleMembership]
  public class AccountController : Controller
  {

    private AdventureWorksEntities db = new AdventureWorksEntities();
</code>```

This is at the top ^^

```<code>    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.userName, model.UserPassword);
                WebSecurity.Login(model.userName, model.UserPassword);
                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }
</code>```

Model

```<code>public class UsersContext : DbContext
{
    public UsersContext()
        : base("AdventureWorksEntities")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
}
</code>```

Web.config

```<code> <connectionStrings>
 <add name="AdventureWorksEntities" connectionString="metadata=res://*/Models.AdventureworksContext.csdl|res://*/Models.AdventureworksContext.ssdl|res://*/Models.AdventureworksContext.msl;provider=System.Data.SqlClient;provider connection string="data source=LEMN-476W-IT;initial catalog=AdventureWorks;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
 </connectionStrings>
</code>```

Filter\InitializerSimpleMembership.cs

```<code>private class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            Database.SetInitializer<UsersContext>(null);

            try
            {
                using (var context = new UsersContext())
                {
                    if (!context.Database.Exists())
                    {
                        // Create the SimpleMembership database without Entity Framework migration schema
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

                WebSecurity.InitializeDatabaseConnection("AdventureWorksEntities", "mvcUser", "userID", "userName", autoCreateTables: false);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
            }
        }
    }
</code>```

答:
"No user table found that has the name XXXXX" means that you can't use Entity Framework connection string (EntityClient provider) to initialize database connection for SimpleMembershipProvider, it must be initialized with a plain SqlClient provider connection string.

There are 2 solutions to solve this problem:

Single Connection String (EDM Only)

Use EntityConnectionStringBuilder instance to generate SqlClient provider connection string, then point InitializeDatabaseConnection to use generated connection string:

```<code>private class SimpleMembershipInitializer
{
    public SimpleMembershipInitializer()
    {
        // initializer settings here

        var connectionBuilder = new EntityConnectionStringBuilder("AdventureWorksEntities");
        string sqlConnectionString = connectionBuilder.ConnectionString;

        WebSecurity.InitializeDatabaseConnection(sqlConnectionString, "mvcUser", "userID", "userName", autoCreateTables: false);
    }
}
</code>```

Dual Connection String

Add a new element on connectionStrings part in web.config file which includes SqlClient provider, so that it will looks like this (one for SQL Server & another one for EF):

```<code><connectionStrings>
   <add name="AdventureWorksDatabase" connectionString="Data Source=LEMN-476W-IT;Initial Catalog=AdventureWorks;Integrated Security=True" providerName="System.Data.SqlClient" />
   <add name="AdventureWorksEntities" connectionString="metadata=res://*/Models.AdventureworksContext.csdl|res://*/Models.AdventureworksContext.ssdl|res://*/Models.AdventureworksContext.msl;provider=System.Data.SqlClient;provider connection string="data source=LEMN-476W-IT;initial catalog=AdventureWorks;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</code>```

Then, set InitializeDatabaseConnection to use newly created connection string:

```<code>private class SimpleMembershipInitializer
{
    public SimpleMembershipInitializer()
    {
        // initializer settings here

        WebSecurity.InitializeDatabaseConnection("AdventureWorksDatabase", "mvcUser", "userID", "userName", autoCreateTables: false);
    }
}
</code>```

NB: The accepted answer from this post mentions how to convert Code First to Model First with SimpleMembershipProvider, but here you have Model First setup from start.

Related issues:

Can SimpleMembership and Entity Framework share a connection string?

Setup a valid connection string for SimpleMembership

Title: MVC 4 SimpleMembership Model first

Body:
I have researched for the last couple days on Stack and other coding sites and cant seem to find a fix for my problem.

My goal is to configure simplemembership with my own database.(yes i have done a search and none of them answer my question)

I'm using visual studio 2013 and entity framework 4

I used the internet application template for asp.net mvc 4, that has already built in login.

I do as everyone else on line has done and seems to work for some, but most of the time they are left with no answer at all.

when i run my code and set the break points in the SimpleMembershipInitializer class. When I run it and click on register or login I step through the code and when it gets down to

WebSecurity.InitializeDatabaseConnection("AdventureWorksEntities", "mvcUser", "userID", "userName", autoCreateTables: false);

I get this error: "No user table found that has the name \"mvcUser\"."

what I know:

I know there is a table named "mvcUser"

I can CRUD the table and attribute in the table with in the site

If you want screen shots or more code please let me know.

Here is something similar to what I am looking/talking about but I don't understand what is meant by number 2 and 3 in the selected answer.

Controller

  [Authorize]
  [InitializeSimpleMembership]
  public class AccountController : Controller
  {

    private AdventureWorksEntities db = new AdventureWorksEntities();

This is at the top ^^

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.userName, model.UserPassword);
                WebSecurity.Login(model.userName, model.UserPassword);
                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

Model

public class UsersContext : DbContext
{
    public UsersContext()
        : base("AdventureWorksEntities")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
}

Web.config

 <connectionStrings>
 <add name="AdventureWorksEntities" connectionString="metadata=res://*/Models.AdventureworksContext.csdl|res://*/Models.AdventureworksContext.ssdl|res://*/Models.AdventureworksContext.msl;provider=System.Data.SqlClient;provider connection string="data source=LEMN-476W-IT;initial catalog=AdventureWorks;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
 </connectionStrings>

Filter\InitializerSimpleMembership.cs

private class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            Database.SetInitializer<UsersContext>(null);

            try
            {
                using (var context = new UsersContext())
                {
                    if (!context.Database.Exists())
                    {
                        // Create the SimpleMembership database without Entity Framework migration schema
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

                WebSecurity.InitializeDatabaseConnection("AdventureWorksEntities", "mvcUser", "userID", "userName", autoCreateTables: false);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
            }
        }
    }

Body:
"No user table found that has the name XXXXX" means that you can't use Entity Framework connection string (EntityClient provider) to initialize database connection for SimpleMembershipProvider, it must be initialized with a plain SqlClient provider connection string.

There are 2 solutions to solve this problem:

Single Connection String (EDM Only)

Use EntityConnectionStringBuilder instance to generate SqlClient provider connection string, then point InitializeDatabaseConnection to use generated connection string:

private class SimpleMembershipInitializer
{
    public SimpleMembershipInitializer()
    {
        // initializer settings here

        var connectionBuilder = new EntityConnectionStringBuilder("AdventureWorksEntities");
        string sqlConnectionString = connectionBuilder.ConnectionString;

        WebSecurity.InitializeDatabaseConnection(sqlConnectionString, "mvcUser", "userID", "userName", autoCreateTables: false);
    }
}

Dual Connection String

Add a new element on connectionStrings part in web.config file which includes SqlClient provider, so that it will looks like this (one for SQL Server & another one for EF):

<connectionStrings>
   <add name="AdventureWorksDatabase" connectionString="Data Source=LEMN-476W-IT;Initial Catalog=AdventureWorks;Integrated Security=True" providerName="System.Data.SqlClient" />
   <add name="AdventureWorksEntities" connectionString="metadata=res://*/Models.AdventureworksContext.csdl|res://*/Models.AdventureworksContext.ssdl|res://*/Models.AdventureworksContext.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=LEMN-476W-IT;initial catalog=AdventureWorks;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

Then, set InitializeDatabaseConnection to use newly created connection string:

private class SimpleMembershipInitializer
{
    public SimpleMembershipInitializer()
    {
        // initializer settings here

        WebSecurity.InitializeDatabaseConnection("AdventureWorksDatabase", "mvcUser", "userID", "userName", autoCreateTables: false);
    }
}

NB: The accepted answer from this post mentions how to convert Code First to Model First with SimpleMembershipProvider, but here you have Model First setup from start.

Related issues:

Can SimpleMembership and Entity Framework share a connection string?

Setup a valid connection string for SimpleMembership


问:
Adding a LinearLayout to an existing XML
I have searched in a number of posts here for what I want to accomplish but I find no answer that I can adapt to my purpose.  (As a newbie to C# programming, I am assuming that the C# version I am using is somewhat very new and imposes many strictnesses to the syntax. But my question is not about that...)

What I am trying to do is programmatically add to an XML layout.

This is my XML:

```<code>                <LinearLayout
                    android:id="@+id/daterow"
                    android:orientation="horizontal"
                    android:layout_width="480dp"
                    android:layout_height="40dp"
                    android:background="@drawable/customborder"
                    android:padding="0dp">
                <!--                        <LinearLayout
                        android:id="@+id/ll_001"
                        android:orientation="horizontal"
                        android:layout_width="20dp"
                        android:layout_height="40dp"
                        android:background="@drawable/customborder">
                        <TextView
                            android:id="@+id/Slot_001"
                            android:text="00:00"
                            android:textSize="8dp"
                            android:layout_width="20dp"
                            android:layout_height="40dp"
                            android:rotation="270"
                            android:gravity="left|center"
                            android:singleLine="true"
                            android:maxLines="1" />
                    </LinearLayout> -->
</code>```

My code snippet is as follows:

```<code>            LinearLayout parentLayout = (LinearLayout)FindViewById(Resource.Id.daterow);
            LinearLayout Linear1 = new LinearLayout(this);
            Linear1.LayoutParameters = new LayoutParams(LayoutParams.MatchParent,LayoutParams.WrapContent);
            parentLayout.AddView(Linear1);

            TextView tv = new TextView(this);

            tv.Id = i;  // i is variable in a for loop inside of which this code is.
            int qq;   //THIS LINE FOR TESTING ONLY.
            qq = 333;  //THIS LINE FOR TESTING ONLY.
            this.tv.SetText(DateTime.Now.AddMinutes(this.iSlot).ToString("HH:mm"));  //THIS IS WHAT I WANT TO ACCOMPLISH EVENTUALLY
            tv.SetText(qq);  //THIS LINE FOR TESTING ONLY. **GIVES ERROR**
            ll2.AddView(tv);  //THIS LINE FOR TESTING ONLY.
</code>```

Ultimately, I want to programmatically achieve an XML as shown in the section "This is my XML"..

Visual Studio does not highlight any error in the syntax in the above.  But during runtime - I get the following error:

Unhandled Exception:

Android.Content.Res.Resources+NotFoundException: String resource ID #0x14d

Can someone tell me what error I am committing?

In your response could you also please include which "using" I should have to use the functions that you suggest in your solution - as I am a newbie at C#.

答:
Adding a LinearLayout to an existing XML

```<code> LinearLayout parentLayout = (LinearLayout)FindViewById(Resource.Id.daterow);

 //using Android.Widget;
 Android.Widget.LinearLayout Linear1 = new Android.Widget.LinearLayout(this);

 //using Android.Views.ViewGroup;
 Linear1.LayoutParameters = new Android.Views.ViewGroup.LayoutParams(Android.Views.ViewGroup.LayoutParams.MatchParent, Android.Views.ViewGroup.LayoutParams.WrapContent);
 parentLayout.AddView(Linear1);

 Android.Widget.TextView tv = new Android.Widget.TextView(this);
 tv.Text = DateTime.Now.AddMinutes(1.1).ToString("HH:mm");//THIS IS WHAT I WANT TO ACCOMPLISH EVENTUALLY
 Linear1.AddView(tv);  //THIS LINE FOR TESTING ONLY.
</code>```

Android.Content.Res.Resources+NotFoundException: String resource ID #0x21

This happened when you use tv.SetText(qq) method, if you just want to set a text for TextView, you could use tv.Text = qq.ToString().

this.tv.SetText(DateTime.Now.AddMinutes(this.iSlot).ToString("HH:mm"));  //THIS IS WHAT I WANT TO ACCOMPLISH EVENTUALLY

Modify your code like this you could accomplish the effect :

```<code>tv.Text = DateTime.Now.AddMinutes(1.1).ToString("HH:mm");
</code>```

Effect :

Body:
I have searched in a number of posts here for what I want to accomplish but I find no answer that I can adapt to my purpose.  (As a newbie to C# programming, I am assuming that the C# version I am using is somewhat very new and imposes many strictnesses to the syntax. But my question is not about that...)

What I am trying to do is programmatically add to an XML layout.

This is my XML:

                <LinearLayout
                    android:id="@+id/daterow"
                    android:orientation="horizontal"
                    android:layout_width="480dp"
                    android:layout_height="40dp"
                    android:background="@drawable/customborder"
                    android:padding="0dp">

My code snippet is as follows:

            LinearLayout parentLayout = (LinearLayout)FindViewById(Resource.Id.daterow);
            LinearLayout Linear1 = new LinearLayout(this);
            Linear1.LayoutParameters = new LayoutParams(LayoutParams.MatchParent,LayoutParams.WrapContent);
            parentLayout.AddView(Linear1);

            TextView tv = new TextView(this);

            tv.Id = i;  // i is variable in a for loop inside of which this code is.
            int qq;   //THIS LINE FOR TESTING ONLY.
            qq = 333;  //THIS LINE FOR TESTING ONLY.
            this.tv.SetText(DateTime.Now.AddMinutes(this.iSlot).ToString("HH:mm"));  //THIS IS WHAT I WANT TO ACCOMPLISH EVENTUALLY
            tv.SetText(qq);  //THIS LINE FOR TESTING ONLY. **GIVES ERROR**
            ll2.AddView(tv);  //THIS LINE FOR TESTING ONLY.

Ultimately, I want to programmatically achieve an XML as shown in the section "This is my XML"..

Visual Studio does not highlight any error in the syntax in the above.  But during runtime - I get the following error:

Unhandled Exception:

Android.Content.Res.Resources+NotFoundException: String resource ID #0x14d

Can someone tell me what error I am committing?

In your response could you also please include which "using" I should have to use the functions that you suggest in your solution - as I am a newbie at C#.

Body:
Adding a LinearLayout to an existing XML

 LinearLayout parentLayout = (LinearLayout)FindViewById(Resource.Id.daterow);

 //using Android.Widget;
 Android.Widget.LinearLayout Linear1 = new Android.Widget.LinearLayout(this);

 //using Android.Views.ViewGroup;
 Linear1.LayoutParameters = new Android.Views.ViewGroup.LayoutParams(Android.Views.ViewGroup.LayoutParams.MatchParent, Android.Views.ViewGroup.LayoutParams.WrapContent);
 parentLayout.AddView(Linear1);

 Android.Widget.TextView tv = new Android.Widget.TextView(this);
 tv.Text = DateTime.Now.AddMinutes(1.1).ToString("HH:mm");//THIS IS WHAT I WANT TO ACCOMPLISH EVENTUALLY
 Linear1.AddView(tv);  //THIS LINE FOR TESTING ONLY.

Android.Content.Res.Resources+NotFoundException: String resource ID #0x21

This happened when you use tv.SetText(qq) method, if you just want to set a text for TextView, you could use tv.Text = qq.ToString().

this.tv.SetText(DateTime.Now.AddMinutes(this.iSlot).ToString("HH:mm"));  //THIS IS WHAT I WANT TO ACCOMPLISH EVENTUALLY

Modify your code like this you could accomplish the effect :

tv.Text = DateTime.Now.AddMinutes(1.1).ToString("HH:mm");

Effect :


问:
How do I force evaluation of a cfif stored in a string?
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

```<code>"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"
</code>```

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

```<code><cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>
</code>```

I also tried

```<code><cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>
</code>```

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?

答:
Further to Mark's answer here is some psuedo code:

```<code><cfset fileName = createUUID() & ".cfm">
<cfset fileWrite( fileName, [CODE_FROM_DB]>
<cfinclude template="#fileName#">
<cfset fileDelete( fileName )>
</code>```

I have used code like this before with no problems.  Anything in the Virtual File System flies as it is all run in RAM.  For best practice do remember to delete the files created ;)

Body:
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

<cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>

I also tried

<cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?

Body:
Further to Mark's answer here is some psuedo code:

<cfset fileName = createUUID() & ".cfm">
<cfset fileWrite( fileName, [CODE_FROM_DB]>
<cfinclude template="#fileName#">
<cfset fileDelete( fileName )>

I have used code like this before with no problems.  Anything in the Virtual File System flies as it is all run in RAM.  For best practice do remember to delete the files created ;)


问:
Angular 2: Smart component passing in data to Presentation component
I have set up where I have a smart component that ngOnInit uses a service to call out to a Rest API to fetch an object of data.

That data is passed into the presentation (child) component through an @Input() property.

In the presentation component, I need to repack the data into a bit of a different model so that it fits into the 3rd party component I am using for presentation.

I am not 100% how to deal with that fact that in the ngOnInit of the presentatioin component, the passed in @Input property is still undefined. Since the actual data is a Rest API call, the parent (smart) component will only get it in the subscribe's observer, i.e., asynchronously.

How do I hook this up together such that I am not trying to manipulate an undefined object, but wait until it's actually there in the presentation component?

I guess, I can always link the presentation component to the smart parent component through @ViewChild and then introduce a public method on the presentation component like showData(data), but I am wondering what the best practice is here.

答:
In the child component you have to listen for changes to the input. Once the data input has changed and has data. You can then repack it into another property.

In this example the input data gets assigned to repacked. Notice the *ngIf in the template to prevent the use of the third party stuff until the data is ready.

```<code>@Component({
    selector: 'child',
    tempalte: '<div *ngIf="repacked"><!-- third-party stuff --></div>'
})
export class ChildComponent implements OnChanges {
   @Input()
   public data: Object;

   public repacked: Object;

   public ngChanges(changes: SimpleChanges): void {
      if('data' in changes) {
           this.repack(changes['data'].currentValue);
      }
   }

   private repack(data: Object) {
       if(data) {
          this.repacked = data; // <-- do repacking work here
       }
   }
}
</code>```

Body:
In the child component you have to listen for changes to the input. Once the data input has changed and has data. You can then repack it into another property.

In this example the input data gets assigned to repacked. Notice the *ngIf in the template to prevent the use of the third party stuff until the data is ready.

@Component({
    selector: 'child',
    tempalte: '<div *ngIf="repacked"><!-- third-party stuff --></div>'
})
export class ChildComponent implements OnChanges {
   @Input()
   public data: Object;

   public repacked: Object;

   public ngChanges(changes: SimpleChanges): void {
      if('data' in changes) {
           this.repack(changes['data'].currentValue);
      }
   }

   private repack(data: Object) {
       if(data) {
          this.repacked = data; // <-- do repacking work here
       }
   }
}


问:
How to scan variables into a data structure from inside a function in C
```<code>#include <stdio.h>
#define MAX_TITLE_SIZE 20
#define MAX_BOOKS 10

struct Book{
  int _isbn;
  float _price;
  int _year;
  char _title[MAX_TITLE_SIZE];
  int _qty;
};

void displayInventory(const struct Book book[], const int size){

  int i;

  printf("===================================================\n");
  printf("ISBN      Title              Year Price  Quantity\n");
  printf("---------+------------------+----+-------+--------\n");

  //iterate through objects
  if(size == 0){
    printf("The inventory is empty!\n");
    printf("===================================================");
  }
  else{
    for(i = 0; i < size; i++){
      printf("%-10.0d%-18s%5d $%-8.2f%-8d\n", book[i]._isbn, book[i]._title, book[i]._year, book[i]._price, book[i]._qty);
    }
  }
}

void addBook(struct Book book[], int *size){

  if(*size == MAX_BOOKS){
    printf("the inventory is full\n");
  }
  else{

     //increment inventory size
    (*size)++;  //*size will move the pointer to the next in position/hashcode
    //++*size also works

    printf("ISBN:");
    scanf("%d", book[*size]._isbn);
    printf("Title:");
    scanf("%s", book[*size]._title);
    printf("Year:");
    scanf("%d", book[*size]._year);
    printf("Price:");
    scanf("%f", book[*size]._price);
    printf("Quantity:");
    scanf("%d", book[*size]._qty);

    printf("The book is sucessfully added to the inventory.\n");
    printf("\n");
  }
}

int main(void){

  int size = 0;
  struct Book book[MAX_BOOKS];

  book[0]._isbn = 1234;
  printf("Create string: ");
  scanf("%s", book[0]._title);
  book[0]._year = 1992;
  book[0]._price = 192.90;
  book[0]._qty = 2;

  size++;

  addBook(book, &size);

  displayInventory(book, size);
  return 0;
}
</code>```

So I have this bookkeeping system that I'm trying to make and what I want to do is add a new book to the book[] array structure.

When I try and input the ISBN for a book in my addBook() function the whole application ends with non-zero status.

How do I write into a data structure from a function? I'm sorry if it's a stupid question but I've been stuck on this for a while.

What am I doing wrong?

Here's a link to the repl.it: https://repl.it/JRPH/4

答:
You should refer to address of variable when using scanf. Specifically, scanf("%d", book[*size]._isbn); -> scanf("%d", &(book[*size]._isbn)); and so on...

Take a look at this.

Body:
#include <stdio.h>
#define MAX_TITLE_SIZE 20
#define MAX_BOOKS 10

struct Book{
  int _isbn;
  float _price;
  int _year;
  char _title[MAX_TITLE_SIZE];
  int _qty;
};

void displayInventory(const struct Book book[], const int size){

  int i;

  printf("===================================================\n");
  printf("ISBN      Title              Year Price  Quantity\n");
  printf("---------+------------------+----+-------+--------\n");

  //iterate through objects
  if(size == 0){
    printf("The inventory is empty!\n");
    printf("===================================================");
  }
  else{
    for(i = 0; i < size; i++){
      printf("%-10.0d%-18s%5d $%-8.2f%-8d\n", book[i]._isbn, book[i]._title, book[i]._year, book[i]._price, book[i]._qty);
    }
  }
}

void addBook(struct Book book[], int *size){

  if(*size == MAX_BOOKS){
    printf("the inventory is full\n");
  }
  else{

     //increment inventory size
    (*size)++;  //*size will move the pointer to the next in position/hashcode
    //++*size also works

    printf("ISBN:");
    scanf("%d", book[*size]._isbn);
    printf("Title:");
    scanf("%s", book[*size]._title);
    printf("Year:");
    scanf("%d", book[*size]._year);
    printf("Price:");
    scanf("%f", book[*size]._price);
    printf("Quantity:");
    scanf("%d", book[*size]._qty);

    printf("The book is sucessfully added to the inventory.\n");
    printf("\n");
  }
}

int main(void){

  int size = 0;
  struct Book book[MAX_BOOKS];

  book[0]._isbn = 1234;
  printf("Create string: ");
  scanf("%s", book[0]._title);
  book[0]._year = 1992;
  book[0]._price = 192.90;
  book[0]._qty = 2;

  size++;

  addBook(book, &size);

  displayInventory(book, size);
  return 0;
}

So I have this bookkeeping system that I'm trying to make and what I want to do is add a new book to the book[] array structure.

When I try and input the ISBN for a book in my addBook() function the whole application ends with non-zero status.

How do I write into a data structure from a function? I'm sorry if it's a stupid question but I've been stuck on this for a while.

What am I doing wrong?

Here's a link to the repl.it: https://repl.it/JRPH/4


问:
Creating Google Analytics Property not using Firebase
I went to create a new google analytics property for my mobile app, and it seems like Google is now forcing us to use their Firebase analytics for mobile. There is no option to not use Firebase if you select that you are creating the property for a mobile app.

Does anyone know a way around this? I need to create a new property for my app, and my app isn't set up to use Firebase.

Thanks!

答: I found a simple way to achieve this by just creating a new account in your Google Analytic admin page, then you are allowed to create a moblie app tracker id with this account.


问:
Java generic type parameter naming convention scope
The Java documentation says that when there are multiple generic parameters, the convention is to use S,U,V etc. for the 2nd, 3rd, 4th types. Does this convention apply across the scope of one enclosing <> group, or across a class?

For example, if I have a class with two separate methods that use different generic parameters, does the above convention mean I should write the code like this:

```<code>public abstract class MyClass
{
    public abstract <T extends Class1> T method1();
    public abstract <S extends Class2> S method2();
}
</code>```

Or like this:

```<code>public abstract class MyClass
{
    public abstract <T extends Class1> T method1();
    public abstract <T extends Class2> T method2();
}
</code>```

答:
The second is certainly more conventional. The first pattern won't hold up if you have a large utility class with generic methods.

We can see examples of this here in openjdk, and in popular libraries like this guava class. Note they both re-use T as a type variable in most methods. This allows other identifiers like E, K, V, etc to retain some semantic meaning.

Body:
The Java documentation says that when there are multiple generic parameters, the convention is to use S,U,V etc. for the 2nd, 3rd, 4th types. Does this convention apply across the scope of one enclosing <> group, or across a class?

For example, if I have a class with two separate methods that use different generic parameters, does the above convention mean I should write the code like this:

public abstract class MyClass
{
    public abstract <T extends Class1> T method1();
    public abstract <S extends Class2> S method2();
}

Or like this:

public abstract class MyClass
{
    public abstract <T extends Class1> T method1();
    public abstract <T extends Class2> T method2();
}


问:
How can cached value be invalidated in single thread?
I use the Http.Current.Cache to store various values retrieved from my database because my app is to data-intensive.  When running my website on my new laptop with VS2017 install (on another laptop with VS2015 I never see this problem), I'm seeing a very strange issue where cached values seem to be randomly cleared- almost in a way to defies logic.

For instance, I have an if clause whose condition is that the cache item in question is not null.  My code is definitely following the path through this if statement, but a couple of statements later the debugger shows that the cache item is in fact null- causing my app to fail.

```<code>public static SportSeason GetCurrentSportSeason(string sportCode)
{
  SportSeason sportSeason = null;
  string key = "Sheets_SportSeason_" + sportCode;

  int i = 0;
  if (BaseSheet.Settings.EnableCaching && BizObject.Cache[key] != null)
  {
    i = 1;
    sportSeason = (SportSeason)BizObject.Cache[key];
  }
  else
  {
    i = 2;
    sportSeason = GetSportSeasonFromSportSeasonDetails(SiteProvider.Sheets.GetCurrentSportSeason(sportCode));
    BaseSheet.CacheData(key, sportSeason);
  }
  if(sportSeason == null)
  {
    int j = i;
  }
  return sportSeason;
}
</code>```

I can set a breakpoint in the final if and the variable i is set to 1, but the sportSeason object is NULL (as is the cache entry).  How can this be when the only way the code could have entered the first if clause is if the cache item was not null?

Here is a screenshot showing some watch variables with a breakpoint in the final if.

This is tough to track down because it happens randomly throughout my business objects.  Sometimes I have to refresh the page 3 or 4 times before I see this issues.

How can the cache be invalidated so quickly, and by what?  The screenshot shows that there aren't many cached items, so I don't think I'm running out of memory.  And no other processes are running which could be clobbering the cache.

EDIT:  Through more debugging I've determined that only the cache key that is checked on Line 91 is cleared (set to null) when it is checked again at the breakpoint.  All of the other cache records are still there.

EDIT2:  I've isolated the problem down to this, although it still seems to defy logic:

```<code>    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddSeconds(600), TimeSpan.Zero);
    int i = 0;
</code>```

I clear all my cache.  When I step over the Cache.Insert statement, my cache count goes to 1.  However, the cached item according to that key remains null (see watch window).

Also, if I execute one more statement (the int i = 0), the cache count goes back to zero.

Edit3:  It's the AbsoluteExpiration parameter of the Insert() that is killing me.  Somehow a clock is off.

If I set the AbsoluteExpiration to 5 hours into the future (300 minutes), it doesn't work. If I set it to 5 hours and one minute (301 minutes) into the future, everything works.

```<code>    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(301), TimeSpan.Zero);
</code>```

The clock on my laptop is 100% accurate and you can see the Intellisense shows the correct time as well.  Can the cache be based off of some other clock that is 5 hours off?

Edit4: Looks like someone else is off by 5 hours.

答:
You can add a callback function that can tell you why an item was removed:

https://msdn.microsoft.com/en-us/library/7kxdx246.aspx

You specify the callback when adding an item, and it will be fired when the item is removed. Put a breakpoint or logging output in there to print out the CacheItemRemovedReason argument.

If that doesn't help you, you might try the debugging steps laid out in the top answer to ASP.NET HttpContext Cache removes right after insertion. This may catch if the app is terminating.

Body:
I use the Http.Current.Cache to store various values retrieved from my database because my app is to data-intensive.  When running my website on my new laptop with VS2017 install (on another laptop with VS2015 I never see this problem), I'm seeing a very strange issue where cached values seem to be randomly cleared- almost in a way to defies logic.

For instance, I have an if clause whose condition is that the cache item in question is not null.  My code is definitely following the path through this if statement, but a couple of statements later the debugger shows that the cache item is in fact null- causing my app to fail.

public static SportSeason GetCurrentSportSeason(string sportCode)
{
  SportSeason sportSeason = null;
  string key = "Sheets_SportSeason_" + sportCode;

  int i = 0;
  if (BaseSheet.Settings.EnableCaching && BizObject.Cache[key] != null)
  {
    i = 1;
    sportSeason = (SportSeason)BizObject.Cache[key];
  }
  else
  {
    i = 2;
    sportSeason = GetSportSeasonFromSportSeasonDetails(SiteProvider.Sheets.GetCurrentSportSeason(sportCode));
    BaseSheet.CacheData(key, sportSeason);
  }
  if(sportSeason == null)
  {
    int j = i;
  }
  return sportSeason;
}

I can set a breakpoint in the final if and the variable i is set to 1, but the sportSeason object is NULL (as is the cache entry).  How can this be when the only way the code could have entered the first if clause is if the cache item was not null?

Here is a screenshot showing some watch variables with a breakpoint in the final if.

This is tough to track down because it happens randomly throughout my business objects.  Sometimes I have to refresh the page 3 or 4 times before I see this issues.

How can the cache be invalidated so quickly, and by what?  The screenshot shows that there aren't many cached items, so I don't think I'm running out of memory.  And no other processes are running which could be clobbering the cache.

EDIT:  Through more debugging I've determined that only the cache key that is checked on Line 91 is cleared (set to null) when it is checked again at the breakpoint.  All of the other cache records are still there.

EDIT2:  I've isolated the problem down to this, although it still seems to defy logic:

    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddSeconds(600), TimeSpan.Zero);
    int i = 0;

I clear all my cache.  When I step over the Cache.Insert statement, my cache count goes to 1.  However, the cached item according to that key remains null (see watch window).

Also, if I execute one more statement (the int i = 0), the cache count goes back to zero.

Edit3:  It's the AbsoluteExpiration parameter of the Insert() that is killing me.  Somehow a clock is off.

If I set the AbsoluteExpiration to 5 hours into the future (300 minutes), it doesn't work. If I set it to 5 hours and one minute (301 minutes) into the future, everything works.

    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(301), TimeSpan.Zero);

The clock on my laptop is 100% accurate and you can see the Intellisense shows the correct time as well.  Can the cache be based off of some other clock that is 5 hours off?

Edit4: Looks like someone else is off by 5 hours.