问:
I can't open Android Device Monitor
I am using Android Studio. I can't open Android Device Monitor, Tools > Android > Android Device Monitor. I occurred an error. See the log file at:

C:\Users\Peter Phyo\AppData\Local\Android\sdk\tools\lib\monitor-x86\configuration\1433318221838.log.

答:
I had the same problem, i solved it using jPortable, if you're using Windows then take this one, there are two versions 32bits and 64bits : https://portableapps.com/apps/utilities/java_portable
 I changed the location for the extraction from C:\SDK\tools\lib\monitor-x86_64\CommonFiles\Java64 to C:\SDK\tools\lib\monitor-x86_64\jre and it worked.

Title: I can't open Android Device Monitor


来源: stackexchange

问:
Typescript: Overloading cascade-like constructors
I need to translate these Java constructor overloads to Typescript:

```<code>public QueryMixin() {
    this(null, new DefaultQueryMetadata(), true);
}

public QueryMixin(QueryMetadata metadata) {
    this(null, metadata, true);
}

public QueryMixin(QueryMetadata metadata, boolean expandAnyPaths) {
    this(null, metadata, expandAnyPaths);
}

public QueryMixin(T self) {
    this(self, new DefaultQueryMetadata(), true);
}

public QueryMixin(T self, QueryMetadata metadata) {
    this(self, metadata, true);
}

public QueryMixin(T self, QueryMetadata metadata, boolean expandAnyPaths) {
    this.self = self;
    this.metadata = metadata;
    this.expandAnyPaths = expandAnyPaths;
}
</code>```

I've tried create these constructors taking a look over there, but I've not been able to figure out how to get it...

Any ideas?

```<code>constructor();
constructor(metadata: QueryMetadata);
constructor(metadata: QueryMetadata, expandAnyPaths: boolean);
constructor(self: T);
constructor(self: T, metadata: QueryMetadata);
constructor(???) {
    this.self = self;  <<< ???
    this.metadata = selfOrMetadata;  <<< ???
    this.expandAnyPaths = expandAnyPaths;
}
</code>```

答:
It seems what you actually want is to support any combination of present or missing parameters, with simple defaults. With 3 parameters, there are 8 on/off combinations. So while TypeScript supports overloading, writing out 8 overloads for type safety is not ideal.

But using named parameters (instead of positional) will simplify the implementation. More parameters can be added easily without writing exponentially more overloads.

```<code>interface QueryMetadata { }
class DefaultQueryMetadata implements QueryMetadata { }

interface QueryMixinParams<T> {
    self: T;
    metadata: QueryMetadata;
    expandAnyPaths: boolean;
}

class QueryMixin<T> implements QueryMixinParams<T> {
    self: T;
    metadata: QueryMetadata;
    expandAnyPaths: boolean;

    constructor({
        self = null,
        metadata = new DefaultQueryMetadata(),
        expandAnyPaths = true,
        }: Partial<QueryMixinParams<T>> = {}) {
        this.self = self;
        this.metadata = metadata;
        this.expandAnyPaths = expandAnyPaths;
        console.log(this);
    }
}

// Any combination of parameters is supported
new QueryMixin();
new QueryMixin({});
new QueryMixin({ self: {} });
new QueryMixin({ self: {}, metadata: {} });
new QueryMixin({ self: {}, metadata: {}, expandAnyPaths: false });
new QueryMixin({ self: {}, expandAnyPaths: false });
new QueryMixin({ metadata: {} });
new QueryMixin({ metadata: {}, expandAnyPaths: false });
new QueryMixin({ expandAnyPaths: false });
</code>```

Try it in TypeScript Playground

ContentLicense: CC BY-SA 3.0

Body:
I need to translate these Java constructor overloads to Typescript:

public QueryMixin() {
    this(null, new DefaultQueryMetadata(), true);
}

public QueryMixin(QueryMetadata metadata) {
    this(null, metadata, true);
}

public QueryMixin(QueryMetadata metadata, boolean expandAnyPaths) {
    this(null, metadata, expandAnyPaths);
}

public QueryMixin(T self) {
    this(self, new DefaultQueryMetadata(), true);
}

public QueryMixin(T self, QueryMetadata metadata) {
    this(self, metadata, true);
}

public QueryMixin(T self, QueryMetadata metadata, boolean expandAnyPaths) {
    this.self = self;
    this.metadata = metadata;
    this.expandAnyPaths = expandAnyPaths;
}

I've tried create these constructors taking a look over there, but I've not been able to figure out how to get it...

Any ideas?

constructor();
constructor(metadata: QueryMetadata);
constructor(metadata: QueryMetadata, expandAnyPaths: boolean);
constructor(self: T);
constructor(self: T, metadata: QueryMetadata);
constructor(???) {
    this.self = self;  <<< ???
    this.metadata = selfOrMetadata;  <<< ???
    this.expandAnyPaths = expandAnyPaths;
}

Body:
It seems what you actually want is to support any combination of present or missing parameters, with simple defaults. With 3 parameters, there are 8 on/off combinations. So while TypeScript supports overloading, writing out 8 overloads for type safety is not ideal.

But using named parameters (instead of positional) will simplify the implementation. More parameters can be added easily without writing exponentially more overloads.

interface QueryMetadata { }
class DefaultQueryMetadata implements QueryMetadata { }

interface QueryMixinParams<T> {
    self: T;
    metadata: QueryMetadata;
    expandAnyPaths: boolean;
}

class QueryMixin<T> implements QueryMixinParams<T> {
    self: T;
    metadata: QueryMetadata;
    expandAnyPaths: boolean;

    constructor({
        self = null,
        metadata = new DefaultQueryMetadata(),
        expandAnyPaths = true,
        }: Partial<QueryMixinParams<T>> = {}) {
        this.self = self;
        this.metadata = metadata;
        this.expandAnyPaths = expandAnyPaths;
        console.log(this);
    }
}

// Any combination of parameters is supported
new QueryMixin();
new QueryMixin({});
new QueryMixin({ self: {} });
new QueryMixin({ self: {}, metadata: {} });
new QueryMixin({ self: {}, metadata: {}, expandAnyPaths: false });
new QueryMixin({ self: {}, expandAnyPaths: false });
new QueryMixin({ metadata: {} });
new QueryMixin({ metadata: {}, expandAnyPaths: false });
new QueryMixin({ expandAnyPaths: false });

<a href="http://www.typescriptlang.org/play/#src=interface%20QueryMetadata%20%7B%20%7D%0Aclass%20DefaultQueryMetadata%20implements%20QueryMetadata%20%7B%20%7D%0A%0Ainterface%20QueryMixinParams%3CT%3E%20%7B%0A%20%20%20%20self%3A%20T%3B%0A%20%20%20%20metadata%3A%20QueryMetadata%3B%0A%20%20%20%20expandAnyPaths%3A%20boolean%3B%0A%7D%0A%0Aclass%20QueryMixin%3CT%3E%20implements%20QueryMixinParams%3CT%3E%20%7B%0A%20%20%20%20self%3A%20T%3B%0A%20%20%20%20metadata%3A%20QueryMetadata%3B%0A%20%20%20%20expandAnyPaths%3A%20boolean%3B%0A%0A%20%20%20%20constructor(%7B%0A%20%20%20%20%20%20%20%20self%20%3D%20null%2C%0A%20%20%20%20%20%20%20%20metadata%20%3D%20new%20DefaultQueryMetadata()%2C%0A%20%20%20%20%20%20%20%20expandAnyPaths%20%3D%20true%2C%0A%20%20%20%20%20%20%20%20%7D%3A%20Partial%3CQueryMixinParams%3CT%3E%3E%20%3D%20%7B%7D)%20%7B%0A%20%20%20%20%20%20%20%20this.self%20%3D%20self%3B%0A%20%20%20%20%20%20%20%20this.metadata%20%3D%20metadata%3B%0A%20%20%20%20%20%20%20%20this.expandAnyPaths%20%3D%20expandAnyPaths%3B%0A%20%20%20%20%20%20%20%20console.log(this)%3B%0A%20%20%20%20%7D%0A%7D%0A%0A%2F%2F%20Any%20combination%20of%20parameters%20is%20supported%0Anew%20QueryMixin()%3B%0Anew%20QueryMixin(%7B%7D)%3B%0Anew%20QueryMixin(%7B%20self%3A%20%7B%7D%20%7D)%3B%0Anew%20QueryMixin(%7B%20self%3A%20%7B%7D%2C%20metadata%3A%20%7B%7D%20%7D)%3B%0Anew%20QueryMixin(%7B%20self%3A%20%7B%7D%2C%20metadata%3A%20%7B%7D%2C%20expandAnyPaths%3A%20false%20%7D)%3B%0Anew%20QueryMixin(%7B%20self%3A%20%7B%7D%2C%20expandAnyPaths%3A%20false%20%7D)%3B%0Anew%20QueryMixin(%7B%20metadata%3A%20%7B%7D%20%7D)%3B%0Anew%20QueryMixin(%7B%20metadata%3A%20%7B%7D%2C%20expandAnyPaths%3A%20false%20%7D)%3B%0Anew%20QueryMixin(%7B%20expandAnyPaths%3A%20false%20%7D)%3B%0A" rel="nofollow noreferrer">Try it in TypeScript Playground


问:
Case statement in SQL Server with rolling weeks - easier way?
I am creating a case statement (inside a view) that tests 2 variables and outputs a value for another field. The 2 variables it tests are ForecastMultiplier and a function that gets the current week number. Forecast Multiplier means how many months to take in to effect. I then have a table with 12 months of forecast which I use to figure out how much on hand inventory we should have.

Here are some examples:

If Forecast Multiplier = 1 and we are in the first week of the month then I will take all of Month1 Forecast (which is the current month).

If Forecast Multiplier = 1 and we are in the second week of the month then I will take 75% of Month1 Forecast plus 25% of Month2 Forecast.

If Forecast Multiplier = 5 and we are in the first week of the month then I will take Month1 Forecast plus Month2 Forecast plus Month3 Forecast plus Month4 Forecast plus Month5 Forecast

If Forecast Multiplier = 5 and we are in the third week of the month then I will take 50% of Month1 Forecast plus Month2 Forecast plus Month3 Forecast plus Month4 Forecast plus Month5 Forecast plus 25% of Month6 Forecast

and this needs to be done for forecast multipliers of .5, 1.5, etc as well.  So you can see how, using a simple select case will get very cumbersome.

Here is some of the case statement, so you can see:

```<code>CASE
    when mpi.UseForecast = 0 then mpi.MinimumOnHandQuantity
    when mpi.ForecastMultiplier = 1 and dbo.GetWeekNumber() = 1 Then fp.month1
    when mpi.ForecastMultiplier = 1 and dbo.GetWeekNumber() = 2 Then (fp.month1 * .75) + (fp.MONTH2 * .25)
    when mpi.ForecastMultiplier = 1 and dbo.GetWeekNumber() = 3 Then (fp.month1 * .50) + (fp.MONTH2 * .50)
    when mpi.ForecastMultiplier = 1 and dbo.GetWeekNumber() = 4 Then (fp.month1 * .25) + (fp.MONTH2 * .75)
    when mpi.ForecastMultiplier = 1.5 and dbo.GetWeekNumber() = 1 Then fp.month1 + (fp.month2 * .5)
    when mpi.ForecastMultiplier = 1.5 and dbo.GetWeekNumber() = 2 Then (fp.month1 * .75) + (fp.month2 * .5)
    when mpi.ForecastMultiplier = 1.5 and dbo.GetWeekNumber() = 3 Then (fp.month1 * .50) + (fp.month2 * .5)
    when mpi.ForecastMultiplier = 1.5 and dbo.GetWeekNumber() = 4 Then (fp.month1 * .25) + (fp.month2 * .5)
    when mpi.ForecastMultiplier = 2 and dbo.GetWeekNumber() = 1 Then fp.month1 + fp.month2
    when mpi.ForecastMultiplier = 2 and dbo.GetWeekNumber() = 2 Then (fp.month1 * .75) + fp.month2 + (fp.MONTH3 * .25)
    when mpi.ForecastMultiplier = 2 and dbo.GetWeekNumber() = 3 Then (fp.month1 * .50) + fp.month2 + (fp.MONTH3 * .50)
    when mpi.ForecastMultiplier = 2 and dbo.GetWeekNumber() = 4 Then (fp.month1 * .25) + fp.month2 + (fp.MONTH3 * .75)
</code>```

The SQL statement works but there are a few issues with it.  It is cumbersome. It is getting slower the more Months I add to it (it will never go more than 12 months).  Also, it doesn't take the months with 5 weeks in to account.  Finally, if possible we would prefer rolling days, but by this method it is nearly impossible.  Is there a way of doing this through stored procedures and/ or functions? btw, I originally was doing the select statement in a Scaler function but it was very slow, so now I am trying the view.

What I am looking for is a better way to achieve this same result or as I mentioned in the last paragraph, a better result.

Here is the Schema and some data:

MinimumProductInfoes (MPI):

```<code>Code Region UseForecast ForecastMultipler MinimumOnHand
---- ------ ----------- ----------------- -------------
1    R1     0           0                 50
1    R2     1           2                 0
2    R1     1           4.5               0
2    R3     1           3                 0
3    R1     1           12                0
</code>```

ForecastPivot (FP):

```<code>Code  Region  Month1 Month2 Month3 Month4 Month5 Month6 Month7 ... Month12
----  ------  ------ ------ ------ ------ ------ ------ ------     -------
1     R1      200    200    50     75     200    50     50         80
1     R2      500    500    500    500    500    500    500        500
2     R1      1000   0      0      0      0      0      0          0
2     R3      25     1000   1000   1000   1000   1000   1000       1000
</code>```

答:
SQL Fiddle

Schema Setup: (SQLFiddle uses MS SQL 2014, but this will still work in 2008.)

```<code>CREATE TABLE MPI ( Code int, Region varchar(5), UseForecast bit
    , ForecastMultiplier decimal(5,1), MinimumOnHand int ) ;
INSERT INTO MPI ( Code, Region, UseForecast, ForecastMultiplier, MinimumOnHand )
VALUES
      ( 1,'R1',0,0,50 )
    , ( 1,'R2',1,2,0)
    , ( 2,'R1',1,4.5,0)
    , ( 2,'R3',1,3,0)
    , ( 3,'R1',1,12,0)
;

CREATE TABLE FP ( Code int,  Region varchar(5), Month1 int, Month2 int
    , Month3 int, Month4 int, Month5 int, Month6 int, Month7 int
    , Month8 int, Month9 int, Month10 int, Month11 int, Month12 int ) ;
INSERT INTO FP (Code, Region, Month1, Month2, Month3, Month4, Month5
    , Month6, Month7, Month8, Month9, Month10, Month11, Month12 )
VALUES
      ( 1,'R1',200,200,50,75,200,50,50,50,50,50,50,80 )
    , ( 1,'R2',500,500,500,500,500,500,500,50,50,50,50,500 )
    , ( 2,'R1',1000,0,0,0,0,0,0,50,50,50,50,0 )
    , ( 2,'R3',25,1000,1000,1000,1000,1000,1000,50,50,50,50,1000 )
;
</code>```

Build Simple Calendar Table:

NOTE: The calendar table is for general use in your database, so add whatever calculations you need. I often use a modified version of Aaron Bertrand's example: https://github.com/shawnoden/SQL_Stuff/blob/master/sql_CreateDateDimension.sql

```<code>/* #dim is just a temp holding table for intermediate calculations. */
CREATE TABLE #dim (
      theDate           date        PRIMARY KEY
    , theDay            AS DATEPART(day, theDate)           --int
    , theWeek           AS DATEPART(week, theDate)          --int
    , theMonth          AS DATEPART(month, theDate)         --int
    , theYear           AS DATEPART(year, theDate)          --int
    , yyyymmdd          AS CONVERT(char(8), theDate, 112)   /* yyyymmdd */
    , mm_dd_yy          AS CONVERT(char(10), theDate, 101)  /* mm/dd/yyyy */
);

/**************************************************************************/
/* Use the catalog views to generate as many rows as we need. */

INSERT INTO #dim ( theDate )
SELECT d
FROM (
    SELECT d = DATEADD(day, rn - 1, '20170101')
    FROM
    (
        SELECT TOP (DATEDIFF(day, '20160101', '20190101'))
            rn = ROW_NUMBER() OVER (ORDER BY s1.object_id)
        FROM sys.all_objects AS s1
        CROSS JOIN sys.all_objects AS s2
        ORDER BY s1.object_id
    ) AS x
) AS y;

/* Now create the final ref table for the dates. */
CREATE TABLE refDateDimension
(
      DateKey             int         NOT NULL PRIMARY KEY
    , theDate             date        NOT NULL
    , theDay              tinyint     NOT NULL
    , WeekOfMonth         tinyint     NOT NULL
    , theMonth            tinyint     NOT NULL
    , theYear             int         NOT NULL
    , mm_dd_yy            char(10)    NOT NULL   /* mm/dd/yyyy */
);

/* Insert data in the dimension table. */
INSERT refDateDimension WITH (TABLOCKX)
SELECT
      DateKey              = CONVERT(int, yyyymmdd)
    , theDate              = theDate
    , theDay               = CONVERT(tinyint, theDay)
    , WeekOfMonth          = CONVERT(tinyint
                              , DENSE_RANK() OVER
                                (PARTITION BY theYear, theMonth
                                 ORDER BY theWeek)
                           )
    , theMonth             = CONVERT(tinyint, theMonth)
    , theYear              = theYear
    , mm_dd_yy             = mm_dd_yy
FROM #dim
OPTION (MAXDOP 1);

/* CLEANUP */
DROP TABLE #dim ;
</code>```

Now we use the calendar table to quickly find the week number.:

```<code>SELECT s1.Code
  , s1.Region
  , CEILING(s1.ForecastMinOnHand) AS ForecastMinOnHand /* Round up to even number. */
FROM (
  SELECT MPI.Code, MPI.Region
    --, MPI.UseForecast, MPI.ForecastMultiplier, d.WeekOfMonth
    , CASE
          WHEN MPI.UseForecast = 0          THEN MPI.MinimumOnHand
          WHEN MPI.ForecastMultiplier = 1    THEN CASE d.WeekOfMonth
                                                      WHEN 1 THEN FP.Month1
                                                      WHEN 2 THEN (FP.Month1*.75) + (FP.Month2*.25)
                                                      WHEN 3 THEN (FP.Month1*.5) + (FP.Month2*.5)
                                                      ELSE (FP.Month1*.25) + (FP.Month2*.75)
                                                 END
          WHEN MPI.ForecastMultiplier = 2    THEN CASE d.WeekOfMonth
                                                      WHEN 1 THEN FP.Month1 + FP.Month2
                                                      WHEN 2 THEN (FP.Month1*.75) + FP.Month2 + (FP.Month3*.25)
                                                      WHEN 3 THEN (FP.Month1*.5) + FP.Month2 + (FP.Month3*.5)
                                                      ELSE (FP.Month1*.25) + FP.Month2 + (FP.Month3*.75)
                                                 END
          WHEN MPI.ForecastMultiplier = 3    THEN CASE d.WeekOfMonth
                                                      WHEN 1 THEN FP.Month1 + FP.Month2 + FP.Month3
                                                      WHEN 2 THEN (FP.Month1*.75) + FP.Month2 + FP.Month3 + (FP.Month4*.25)
                                                      WHEN 3 THEN (FP.Month1*.5) + FP.Month2 + FP.Month3 + (FP.Month4*.5)
                                                      ELSE (FP.Month1*.25) + FP.Month2 + FP.Month3 + (FP.Month4*.75)
                                                 END
          WHEN MPI.ForecastMultiplier = 4.5  THEN CASE d.WeekOfMonth
                                                      WHEN 1 THEN FP.month1 + fp.month2 + fp.month3 + fp.month4 + (FP.month5*.5)
                                                      WHEN 2 THEN (FP.Month1*.75) + fp.month2 + fp.month3 + fp.month4 + (FP.Month5*.75)
                                                      WHEN 3 THEN (FP.Month1*.5) + fp.month2 + fp.month3 + fp.month4 + FP.Month5
                                                      ELSE (FP.Month1*.25) + fp.month2 + fp.month3 + fp.month4 + FP.Month5 + (FP.Month6*.25)
                                                 END

     END AS ForecastMinOnHand
     --, MPI.*, FP.*
  FROM MPI
  INNER JOIN refDateDimension d ON CAST(getDate() AS date) = d.theDate
  INNER JOIN FP ON MPI.Code = FP.Code
    AND MPI.Region = FP.Region
) s1
</code>```

Results:

```<code>| Code | Region | ForecastMinOnHand |
|------|--------|-------------------|
|    1 |     R1 |                50 |
|    1 |     R2 |              1000 |
|    2 |     R1 |               750 |
|    2 |     R3 |              2269 |
</code>```

My main purpose of using the calendar table here is that it takes away the GetWeekNumber() function and saves a bunch of processing cycles. It will also let your SQL optimizer run a bit more efficiently. In general, you would add a lot more columns to it to account for the time calculations you need elsewhere. It's a utility table. And extremely handy.

I still think the long CASE statement can be distilled down a bit. If you have the ability to edit the ForecastPivot view, you should be able to get at some of this data a little easier without a pivot.

Body:
I am creating a case statement (inside a view) that tests 2 variables and outputs a value for another field. The 2 variables it tests are ForecastMultiplier and a function that gets the current week number. Forecast Multiplier means how many months to take in to effect. I then have a table with 12 months of forecast which I use to figure out how much on hand inventory we should have.

Here are some examples:

If Forecast Multiplier = 1 and we are in the first week of the month then I will take all of Month1 Forecast (which is the current month).

If Forecast Multiplier = 1 and we are in the second week of the month then I will take 75% of Month1 Forecast plus 25% of Month2 Forecast.

If Forecast Multiplier = 5 and we are in the first week of the month then I will take Month1 Forecast plus Month2 Forecast plus Month3 Forecast plus Month4 Forecast plus Month5 Forecast

If Forecast Multiplier = 5 and we are in the third week of the month then I will take 50% of Month1 Forecast plus Month2 Forecast plus Month3 Forecast plus Month4 Forecast plus Month5 Forecast plus 25% of Month6 Forecast

and this needs to be done for forecast multipliers of .5, 1.5, etc as well.  So you can see how, using a simple select case will get very cumbersome.

Here is some of the case statement, so you can see:

CASE
    when mpi.UseForecast = 0 then mpi.MinimumOnHandQuantity
    when mpi.ForecastMultiplier = 1 and dbo.GetWeekNumber() = 1 Then fp.month1
    when mpi.ForecastMultiplier = 1 and dbo.GetWeekNumber() = 2 Then (fp.month1 * .75) + (fp.MONTH2 * .25)
    when mpi.ForecastMultiplier = 1 and dbo.GetWeekNumber() = 3 Then (fp.month1 * .50) + (fp.MONTH2 * .50)
    when mpi.ForecastMultiplier = 1 and dbo.GetWeekNumber() = 4 Then (fp.month1 * .25) + (fp.MONTH2 * .75)
    when mpi.ForecastMultiplier = 1.5 and dbo.GetWeekNumber() = 1 Then fp.month1 + (fp.month2 * .5)
    when mpi.ForecastMultiplier = 1.5 and dbo.GetWeekNumber() = 2 Then (fp.month1 * .75) + (fp.month2 * .5)
    when mpi.ForecastMultiplier = 1.5 and dbo.GetWeekNumber() = 3 Then (fp.month1 * .50) + (fp.month2 * .5)
    when mpi.ForecastMultiplier = 1.5 and dbo.GetWeekNumber() = 4 Then (fp.month1 * .25) + (fp.month2 * .5)
    when mpi.ForecastMultiplier = 2 and dbo.GetWeekNumber() = 1 Then fp.month1 + fp.month2
    when mpi.ForecastMultiplier = 2 and dbo.GetWeekNumber() = 2 Then (fp.month1 * .75) + fp.month2 + (fp.MONTH3 * .25)
    when mpi.ForecastMultiplier = 2 and dbo.GetWeekNumber() = 3 Then (fp.month1 * .50) + fp.month2 + (fp.MONTH3 * .50)
    when mpi.ForecastMultiplier = 2 and dbo.GetWeekNumber() = 4 Then (fp.month1 * .25) + fp.month2 + (fp.MONTH3 * .75)

The SQL statement works but there are a few issues with it.  It is cumbersome. It is getting slower the more Months I add to it (it will never go more than 12 months).  Also, it doesn't take the months with 5 weeks in to account.  Finally, if possible we would prefer rolling days, but by this method it is nearly impossible.  Is there a way of doing this through stored procedures and/ or functions? btw, I originally was doing the select statement in a Scaler function but it was very slow, so now I am trying the view.

What I am looking for is a better way to achieve this same result or as I mentioned in the last paragraph, a better result.

Here is the Schema and some data:

MinimumProductInfoes (MPI):

Code Region UseForecast ForecastMultipler MinimumOnHand
---- ------ ----------- ----------------- -------------
1    R1     0           0                 50
1    R2     1           2                 0
2    R1     1           4.5               0
2    R3     1           3                 0
3    R1     1           12                0

ForecastPivot (FP):

Code  Region  Month1 Month2 Month3 Month4 Month5 Month6 Month7 ... Month12
----  ------  ------ ------ ------ ------ ------ ------ ------     -------
1     R1      200    200    50     75     200    50     50         80
1     R2      500    500    500    500    500    500    500        500
2     R1      1000   0      0      0      0      0      0          0
2     R3      25     1000   1000   1000   1000   1000   1000       1000

Body:
SQL Fiddle

Schema Setup: (SQLFiddle uses MS SQL 2014, but this will still work in 2008.)

CREATE TABLE MPI ( Code int, Region varchar(5), UseForecast bit
    , ForecastMultiplier decimal(5,1), MinimumOnHand int ) ;
INSERT INTO MPI ( Code, Region, UseForecast, ForecastMultiplier, MinimumOnHand )
VALUES
      ( 1,'R1',0,0,50 )
    , ( 1,'R2',1,2,0)
    , ( 2,'R1',1,4.5,0)
    , ( 2,'R3',1,3,0)
    , ( 3,'R1',1,12,0)
;

CREATE TABLE FP ( Code int,  Region varchar(5), Month1 int, Month2 int
    , Month3 int, Month4 int, Month5 int, Month6 int, Month7 int
    , Month8 int, Month9 int, Month10 int, Month11 int, Month12 int ) ;
INSERT INTO FP (Code, Region, Month1, Month2, Month3, Month4, Month5
    , Month6, Month7, Month8, Month9, Month10, Month11, Month12 )
VALUES
      ( 1,'R1',200,200,50,75,200,50,50,50,50,50,50,80 )
    , ( 1,'R2',500,500,500,500,500,500,500,50,50,50,50,500 )
    , ( 2,'R1',1000,0,0,0,0,0,0,50,50,50,50,0 )
    , ( 2,'R3',25,1000,1000,1000,1000,1000,1000,50,50,50,50,1000 )
;

Build Simple Calendar Table:

NOTE: The calendar table is for general use in your database, so add whatever calculations you need. I often use a modified version of Aaron Bertrand's example: https://github.com/shawnoden/SQL_Stuff/blob/master/sql_CreateDateDimension.sql

/* #dim is just a temp holding table for intermediate calculations. */
CREATE TABLE #dim (
      theDate           date        PRIMARY KEY
    , theDay            AS DATEPART(day, theDate)           --int
    , theWeek           AS DATEPART(week, theDate)          --int
    , theMonth          AS DATEPART(month, theDate)         --int
    , theYear           AS DATEPART(year, theDate)          --int
    , yyyymmdd          AS CONVERT(char(8), theDate, 112)   /* yyyymmdd */
    , mm_dd_yy          AS CONVERT(char(10), theDate, 101)  /* mm/dd/yyyy */
);

/**************************************************************************/
/* Use the catalog views to generate as many rows as we need. */

INSERT INTO #dim ( theDate )
SELECT d
FROM (
    SELECT d = DATEADD(day, rn - 1, '20170101')
    FROM
    (
        SELECT TOP (DATEDIFF(day, '20160101', '20190101'))
            rn = ROW_NUMBER() OVER (ORDER BY s1.object_id)
        FROM sys.all_objects AS s1
        CROSS JOIN sys.all_objects AS s2
        ORDER BY s1.object_id
    ) AS x
) AS y;

/* Now create the final ref table for the dates. */
CREATE TABLE refDateDimension
(
      DateKey             int         NOT NULL PRIMARY KEY
    , theDate             date        NOT NULL
    , theDay              tinyint     NOT NULL
    , WeekOfMonth         tinyint     NOT NULL
    , theMonth            tinyint     NOT NULL
    , theYear             int         NOT NULL
    , mm_dd_yy            char(10)    NOT NULL   /* mm/dd/yyyy */
);

/* Insert data in the dimension table. */
INSERT refDateDimension WITH (TABLOCKX)
SELECT
      DateKey              = CONVERT(int, yyyymmdd)
    , theDate              = theDate
    , theDay               = CONVERT(tinyint, theDay)
    , WeekOfMonth          = CONVERT(tinyint
                              , DENSE_RANK() OVER
                                (PARTITION BY theYear, theMonth
                                 ORDER BY theWeek)
                           )
    , theMonth             = CONVERT(tinyint, theMonth)
    , theYear              = theYear
    , mm_dd_yy             = mm_dd_yy
FROM #dim
OPTION (MAXDOP 1);

/* CLEANUP */
DROP TABLE #dim ;

Now we use the calendar table to quickly find the week number.:

SELECT s1.Code
  , s1.Region
  , CEILING(s1.ForecastMinOnHand) AS ForecastMinOnHand /* Round up to even number. */
FROM (
  SELECT MPI.Code, MPI.Region
    --, MPI.UseForecast, MPI.ForecastMultiplier, d.WeekOfMonth
    , CASE
          WHEN MPI.UseForecast = 0          THEN MPI.MinimumOnHand
          WHEN MPI.ForecastMultiplier = 1    THEN CASE d.WeekOfMonth
                                                      WHEN 1 THEN FP.Month1
                                                      WHEN 2 THEN (FP.Month1*.75) + (FP.Month2*.25)
                                                      WHEN 3 THEN (FP.Month1*.5) + (FP.Month2*.5)
                                                      ELSE (FP.Month1*.25) + (FP.Month2*.75)
                                                 END
          WHEN MPI.ForecastMultiplier = 2    THEN CASE d.WeekOfMonth
                                                      WHEN 1 THEN FP.Month1 + FP.Month2
                                                      WHEN 2 THEN (FP.Month1*.75) + FP.Month2 + (FP.Month3*.25)
                                                      WHEN 3 THEN (FP.Month1*.5) + FP.Month2 + (FP.Month3*.5)
                                                      ELSE (FP.Month1*.25) + FP.Month2 + (FP.Month3*.75)
                                                 END
          WHEN MPI.ForecastMultiplier = 3    THEN CASE d.WeekOfMonth
                                                      WHEN 1 THEN FP.Month1 + FP.Month2 + FP.Month3
                                                      WHEN 2 THEN (FP.Month1*.75) + FP.Month2 + FP.Month3 + (FP.Month4*.25)
                                                      WHEN 3 THEN (FP.Month1*.5) + FP.Month2 + FP.Month3 + (FP.Month4*.5)
                                                      ELSE (FP.Month1*.25) + FP.Month2 + FP.Month3 + (FP.Month4*.75)
                                                 END
          WHEN MPI.ForecastMultiplier = 4.5  THEN CASE d.WeekOfMonth
                                                      WHEN 1 THEN FP.month1 + fp.month2 + fp.month3 + fp.month4 + (FP.month5*.5)
                                                      WHEN 2 THEN (FP.Month1*.75) + fp.month2 + fp.month3 + fp.month4 + (FP.Month5*.75)
                                                      WHEN 3 THEN (FP.Month1*.5) + fp.month2 + fp.month3 + fp.month4 + FP.Month5
                                                      ELSE (FP.Month1*.25) + fp.month2 + fp.month3 + fp.month4 + FP.Month5 + (FP.Month6*.25)
                                                 END

     END AS ForecastMinOnHand
     --, MPI.*, FP.*
  FROM MPI
  INNER JOIN refDateDimension d ON CAST(getDate() AS date) = d.theDate
  INNER JOIN FP ON MPI.Code = FP.Code
    AND MPI.Region = FP.Region
) s1

Results:

| Code | Region | ForecastMinOnHand |
|------|--------|-------------------|
|    1 |     R1 |                50 |
|    1 |     R2 |              1000 |
|    2 |     R1 |               750 |
|    2 |     R3 |              2269 |

My main purpose of using the calendar table here is that it takes away the GetWeekNumber() function and saves a bunch of processing cycles. It will also let your SQL optimizer run a bit more efficiently. In general, you would add a lot more columns to it to account for the time calculations you need elsewhere. It's a utility table. And extremely handy.

I still think the long CASE statement can be distilled down a bit. If you have the ability to edit the ForecastPivot view, you should be able to get at some of this data a little easier without a pivot.


问:
split UIImage by colors and create 2 images
I have looked through replacing colors in an image but cannot get it to work how i need because I am trying to do it with every color but one, as well as transparency.

what I am looking for is a way to take in an image and split out a color (say all the pure black) from that image. Then take that split out portion and make a new image with a transparent background and the split out portion.

(here is just an example of the idea, say i want to take a screenshot of this page. make every other color but pure black be transparent, and save that new image to the library, or put it into a UIImageView)

i have looked in to CGImageCreateWithMaskingColors but cant seem to do what I need with the transparent portion, and I dont really understand the colorMasking input other than you can provide it with a {Rmin,Rmax,Gmin,Gmax,Bmin,Bmax} color mask but when I do, it colors everything. any ideas or input would be great.

答:
Sounds like you're going to have to get access to the underlying bytes and write code to process them directly. You can use CGImageGetDataProvider() to get access to the data of an image, but there's no guarantee that the format will be something you know how to handle. Alternately you can create a new CGContextRef using a specific format you know how to handle, then draw the original image into your new context, then process the underlying data. Here's a quick attempt at doing what you want (uncompiled):

```<code>- (UIImage *)imageWithBlackPixels:(UIImage *)image {
    CGImageRef cgImage = image.CGImage;
    // create a premultiplied ARGB context with 32bpp
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    size_t width = CGImageGetWidth(cgImage);
    size_t height = CGImageGetHeight(cgImage);
    size_t bpc = 8; // bits per component
    size_t bpp = bpc * 4 / 8; // bytes per pixel
    size_t bytesPerRow = bpp * width;
    void *data = malloc(bytesPerRow * height);
    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host;
    CGContextRef ctx = CGBitmapContextCreate(data, width, height, bpc, bytesPerRow, colorspace, bitmapInfo);
    CGColorSpaceRelease(colorspace);
    if (ctx == NULL) {
        // couldn't create the context - double-check the parameters?
        free(data);
        return nil;
    }
    // draw the image into the context
    CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImage);
    // replace all non-black pixels with transparent
    // preserve existing transparency on black pixels
    for (size_t y = 0; y < height; y++) {
        size_t rowStart = bytesPerRow * y;
        for (size_t x = 0; x < width; x++) {
            size_t pixelOffset = rowStart + x*bpp;
            // check the RGB components of the pixel
            if (data[pixelOffset+1] != 0 || data[pixelOffset+2] != 0 || data[pixelOffset+3] != 0) {
                // this pixel contains non-black. zero it out
                memset(&data[pixelOffset], 0, 4);
            }
        }
    }
    // create our new image and release the context data
    CGImageRef newCGImage = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    free(data);
    UIImage *newImage = [UIImage imageWithCGImage:newCGImage scale:image.scale orientation:image.imageOrientation];
    CGImageRelease(newCGImage);
    return newImage;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Sounds like you're going to have to get access to the underlying bytes and write code to process them directly. You can use CGImageGetDataProvider() to get access to the data of an image, but there's no guarantee that the format will be something you know how to handle. Alternately you can create a new CGContextRef using a specific format you know how to handle, then draw the original image into your new context, then process the underlying data. Here's a quick attempt at doing what you want (uncompiled):

- (UIImage *)imageWithBlackPixels:(UIImage *)image {
    CGImageRef cgImage = image.CGImage;
    // create a premultiplied ARGB context with 32bpp
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    size_t width = CGImageGetWidth(cgImage);
    size_t height = CGImageGetHeight(cgImage);
    size_t bpc = 8; // bits per component
    size_t bpp = bpc * 4 / 8; // bytes per pixel
    size_t bytesPerRow = bpp * width;
    void *data = malloc(bytesPerRow * height);
    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host;
    CGContextRef ctx = CGBitmapContextCreate(data, width, height, bpc, bytesPerRow, colorspace, bitmapInfo);
    CGColorSpaceRelease(colorspace);
    if (ctx == NULL) {
        // couldn't create the context - double-check the parameters?
        free(data);
        return nil;
    }
    // draw the image into the context
    CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImage);
    // replace all non-black pixels with transparent
    // preserve existing transparency on black pixels
    for (size_t y = 0; y < height; y++) {
        size_t rowStart = bytesPerRow * y;
        for (size_t x = 0; x < width; x++) {
            size_t pixelOffset = rowStart + x*bpp;
            // check the RGB components of the pixel
            if (data[pixelOffset+1] != 0 || data[pixelOffset+2] != 0 || data[pixelOffset+3] != 0) {
                // this pixel contains non-black. zero it out
                memset(&data[pixelOffset], 0, 4);
            }
        }
    }
    // create our new image and release the context data
    CGImageRef newCGImage = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    free(data);
    UIImage *newImage = [UIImage imageWithCGImage:newCGImage scale:image.scale orientation:image.imageOrientation];
    CGImageRelease(newCGImage);
    return newImage;
}


问:
Tensorflow instalation with anaconda3 python 3.5 got 'Read timed out error"
I'm trying to install tensorflow-gpu
using python3.6 and anaconda 3
I'm following the instalation steps in the following link https://www.tensorflow.org/install/install_windows

1- I have Createed a conda environment named tensorflow by invoking the following command:

C:> conda create -n tensorflow python=3.6

2- then Activated the conda environment by issuing the following command:

C:> activate tensorflow
(tensorflow)C:>

but comming for the final step  to install TensorFlow inside my conda environment. using that command  pip install --ignore-installed --upgrade tensorflow-gpu
I got that error

```<code>(C:\Users\Chaymae\Anaconda3) C:\WINDOWS\system32>activate tensorflow

(tensorflow) C:\WINDOWS\system32>pip install --ignore-installed --upgrade tensorflow-gpu
Collecting tensorflow-gpu
  Downloading tensorflow_gpu-1.4.0-cp36-cp36m-win_amd64.whl (67.6MB)
    25% |████████                        | 16.9MB 5.3kB/s eta 2:38:22Exception:
Traceback (most recent call last):
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 302, in _error_catcher
    yield
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 384, in read
    data = self._fp.read(amt)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 60, in read
    data = self.__fp.read(amt)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\http\client.py", line 449, in read
    n = self.readinto(b)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\http\client.py", line 493, in readinto
    n = self.fp.readinto(b)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\socket.py", line 586, in readinto
    return self._sock.recv_into(b)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\ssl.py", line 1009, in recv_into
    return self.read(nbytes, buffer)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\ssl.py", line 871, in read
    return self._sslobj.read(len, buffer)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\ssl.py", line 631, in read
    v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\commands\install.py", line 335, in run
    wb.build(autobuilding=True)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file
    session=self.session, hashes=hashes)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 821, in unpack_url
    hashes=hashes
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 659, in unpack_http_url
    hashes)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 882, in _download_http_url
    _download_url(resp, link, content_file, hashes)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 603, in _download_url
    hashes.check_against_chunks(downloaded_chunks)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\utils\hashes.py", line 46, in check_against_chunks
    for chunk in chunks:
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 571, in written_chunks
    for chunk in chunks:
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\utils\ui.py", line 139, in iter
    for x in it:
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 560, in resp_read
    decode_content=False):
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 436, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 401, in read
    raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\contextlib.py", line 99, in __exit__
    self.gen.throw(type, value, traceback)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 307, in _error_catcher
    raise ReadTimeoutError(self._pool, None, 'Read timed out.')
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out.
</code>```

Well after that I have tried to install the cpu version I got the same error.
If anyone could help I would be thankful, I really want to start learning tensorflow.

答: It was only the problem of unstable Internet connection, it's installed now and running very well</p>

Body:
I'm trying to install tensorflow-gpu
using python3.6 and anaconda 3
I'm following the instalation steps in the following link https://www.tensorflow.org/install/install_windows

1- I have Createed a conda environment named tensorflow by invoking the following command:

C:> conda create -n tensorflow python=3.6

2- then Activated the conda environment by issuing the following command:

C:> activate tensorflow
(tensorflow)C:>

but comming for the final step  to install TensorFlow inside my conda environment. using that command  pip install --ignore-installed --upgrade tensorflow-gpu
I got that error

(C:\Users\Chaymae\Anaconda3) C:\WINDOWS\system32>activate tensorflow

(tensorflow) C:\WINDOWS\system32>pip install --ignore-installed --upgrade tensorflow-gpu
Collecting tensorflow-gpu
  Downloading tensorflow_gpu-1.4.0-cp36-cp36m-win_amd64.whl (67.6MB)
    25% |████████                        | 16.9MB 5.3kB/s eta 2:38:22Exception:
Traceback (most recent call last):
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 302, in _error_catcher
    yield
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 384, in read
    data = self._fp.read(amt)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 60, in read
    data = self.__fp.read(amt)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\http\client.py", line 449, in read
    n = self.readinto(b)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\http\client.py", line 493, in readinto
    n = self.fp.readinto(b)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\socket.py", line 586, in readinto
    return self._sock.recv_into(b)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\ssl.py", line 1009, in recv_into
    return self.read(nbytes, buffer)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\ssl.py", line 871, in read
    return self._sslobj.read(len, buffer)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\ssl.py", line 631, in read
    v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\commands\install.py", line 335, in run
    wb.build(autobuilding=True)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file
    session=self.session, hashes=hashes)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 821, in unpack_url
    hashes=hashes
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 659, in unpack_http_url
    hashes)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 882, in _download_http_url
    _download_url(resp, link, content_file, hashes)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 603, in _download_url
    hashes.check_against_chunks(downloaded_chunks)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\utils\hashes.py", line 46, in check_against_chunks
    for chunk in chunks:
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 571, in written_chunks
    for chunk in chunks:
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\utils\ui.py", line 139, in iter
    for x in it:
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\download.py", line 560, in resp_read
    decode_content=False):
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 436, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 401, in read
    raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\contextlib.py", line 99, in __exit__
    self.gen.throw(type, value, traceback)
  File "C:\Users\Chaymae\Anaconda3\envs\tensorflow\lib\site-packages\pip\_vendor\urllib3\response.py", line 307, in _error_catcher
    raise ReadTimeoutError(self._pool, None, 'Read timed out.')
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out.

Well after that I have tried to install the cpu version I got the same error.
If anyone could help I would be thankful, I really want to start learning tensorflow.


问:
MYSQL Updating database using maths?
My query:

```<code>UPDATE `settings_products` SET `stock_osrs` = SUM(stock_osrs - 50)
</code>```

I have a stock system in my admin panel which currently displays stock levels set by the admins, but I am creating an API so every payment that has been completed will take away the stock.

Lets say that the ordered amount is "50" like in the query and I want to take this away from the stock_osrs.

How exactly would I go about doing this?

EDIT: I am aware that I could use PHP to do the calculations and then update the table from that, but I feel this will be less reliable as I would have to do "50,000" - 50 = "45,950" and post that number to the database.

In this time there could have been another order which would cause the code to mess up, hence that I need to use SQL to achieve this!

答:
I think you want something like this:

```<code>UPDATE
  settings_products AS lg
  INNER JOIN
    (SELECT
      l.`stock_osrs` AS stock_osrs,
      COUNT(l.id) AS total,
      SUM(l.stock_osrs) AS SUM
    FROM
      stock_osrs l
    GROUP BY l.`stock_osrs`) sub
    ON lg.`stock_osrs` = sub.stock_osrs SET lg.stock_osrs = sub.sum - 50 ;
</code>```

I am assuming that primary key of this table is id. May be you can modify it a little bit but this is the sort of thing you are looking for...

Title: MYSQL Updating database using maths?

Body:
My query:

UPDATE `settings_products` SET `stock_osrs` = SUM(stock_osrs - 50)

I have a stock system in my admin panel which currently displays stock levels set by the admins, but I am creating an API so every payment that has been completed will take away the stock.

Lets say that the ordered amount is "50" like in the query and I want to take this away from the stock_osrs.

How exactly would I go about doing this?

EDIT: I am aware that I could use PHP to do the calculations and then update the table from that, but I feel this will be less reliable as I would have to do "50,000" - 50 = "45,950" and post that number to the database.

In this time there could have been another order which would cause the code to mess up, hence that I need to use SQL to achieve this!

Body:
I think you want something like this:

UPDATE
  settings_products AS lg
  INNER JOIN
    (SELECT
      l.`stock_osrs` AS stock_osrs,
      COUNT(l.id) AS total,
      SUM(l.stock_osrs) AS SUM
    FROM
      stock_osrs l
    GROUP BY l.`stock_osrs`) sub
    ON lg.`stock_osrs` = sub.stock_osrs SET lg.stock_osrs = sub.sum - 50 ;

I am assuming that primary key of this table is id. May be you can modify it a little bit but this is the sort of thing you are looking for...


问:
Using Promises with Await/Async Correctly
I'm having some issues understanding how the Promise functionality works, I have previously used Bluebird but I wanted to try to learn the new await/async standard in order to improve as a programmer. I have used async/await and created promises where I feel appropriate however the functions are still executing out of order.

I'm running this on the latest version of Node with Webpack, I'm not getting any meaningful errors. It runs fine just not as expected. My output when running it is:

```<code>Searching the Web for: Test String
Web search Completed!
Promise { <pending> }
Response Handler Completed!
</code>```

Ideally I'd like it to respond with:

```<code>Searching the Web for: Test String
Response Handler Completed
Web search Completed
</code>```

And then return the output of my response handler.

Can anyone spot my mistake?

```<code>const https = require('https');

// Replace the subscriptionKey string value with your valid subscription key.
const subscriptionKey = '<samplekey>';

const host = 'api.cognitive.microsoft.com';
const path = '/bing/v7.0/search';

const response_handler = async (response) => {
    return new Promise((resolve, reject) => {
      let body = '';
      response.on('data', (d) => {
        body += d;
        resolve(body);
      });
      response.on('end', () => {
        console.log('\nRelevant Headers:\n');
        for (const header in response.headers)
                // header keys are lower-cased by Node.js
          {
          if (header.startsWith('bingapis-') || header.startsWith('x-msedge-')) { console.log(`${header}: ${response.headers[header]}`); }
        }
        body = JSON.stringify(JSON.parse(body), null, '  ');
        //console.log('\nJSON Test Response:\n');
        //console.log(body);
      });
      response.on('error', (e) => {
        console.log(`Error: ${e.message}`);
      });
      console.log('Response Handler Completed!');

    });
};

const bing_web_search = async (search) => {
  return new Promise((resolve, reject) => {
  console.log(`Searching the Web for: ${search}`);
  const request_params = {
    method: 'GET',
    hostname: host,
    path: `${path}?q=${encodeURIComponent(search)}&$responseFilter=${encodeURIComponent('Webpages')}&count=${50}`,
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
    },
  };

  const req = https.request(request_params, response_handler);

  console.log('Web search Completed!');
  console.log(req.body);
  req.end();
  });
};

module.exports = {
  search: async (search) => {
    if (subscriptionKey.length === 32) {
       const result = await bing_web_search(search);
       console.log('Search Completed');
    } else {
      console.log('Invalid Bing Search API subscription key!');
      console.log('Please paste yours into the source code.');
    }
  },
};
</code>```

答:
A bit late but the following should set you on the way, I made changes to the code. If you have any questions please let me know.

```<code>const https = require('https');

// Replace the subscriptionKey string value with your valid subscription key.
const subscriptionKey = '<samplekey>';

const host = 'api.cognitive.microsoft.com';
const path = '/bing/v7.0/search';

const response_handler = (resolve,reject) => (response) => { // no need for async, you return a promise
  //this one does not return anything, it's the handler for the response and will resolve
  // or reject accordingly
  let body = '';
  response.on('data', (d) => {
    body += d;
    //cannot resolve yet, we're not done
    //  you can resolve on end maybe? I don't know nodejs http
    //  if end event is called when request fails then end would not
    //  be the correct way either, better use fetch api
    //resolve(body);
  });
  response.on('end', () => {
    console.log('\nRelevant Headers:\n');
    for (const header in response.headers)
    // header keys are lower-cased by Node.js
    {
      if (header.startsWith('bingapis-') || header.startsWith('x-msedge-')) { console.log(`${header}: ${response.headers[header]}`); }
    }
    body = JSON.stringify(JSON.parse(body), null, '  ');
    resolve(body);//resolving the promise returned by bing_web_search
    //console.log('\nJSON Test Response:\n');
    //console.log(body);
  });
  response.on('error', (e) => {
    console.log(`Error: ${e.message}`);
    //need to reject with the error
    reject(e);
  });
  console.log('Response Handler Completed!');

};
//no need to specify async, you are not awaiting anything
//  you are creating a promise, when using non promise asynchronous
//  functions that work with callbacks or event emitting objects
//  you need resolve and reject functions so you have to return
//  new Promise(
//    (resolve,reject)=>somecallbackNeedingFunction((err,result)=>
//      err ? reject(err) : resolve(result)
//    )
//  )
const bing_web_search = (search) => {
  return new Promise((resolve, reject) => {
    console.log(`Searching the Web for: ${search}`);
    const request_params = {
      method: 'GET',
      hostname: host,
      path: `${path}?q=${encodeURIComponent(search)}&$responseFilter=${encodeURIComponent('Webpages')}&count=${50}`,
      headers: {
        'Ocp-Apim-Subscription-Key': subscriptionKey,
      },
    };

    const req = https.request(
      request_params,
      response_handler(resolve,reject)//passing this resolve and reject
    );
    //no, request not completed, we just started
    console.log('Web search Completed!');
    // console.log(req.body); // nothing to log here
    req.end();
  });
};

module.exports = {
  search: async (search) => {
    if (subscriptionKey.length === 32) {
      //did not change anything bing_web_search returns a promise
      //  so you can just await it
      const result = await bing_web_search(search);
      console.log('Search Completed');
      //this will resolve with the results
      return result
    } else {
      console.log('Invalid Bing Search API subscription key!');
      console.log('Please paste yours into the source code.');
      //the caller of this function can handle the rejection
      return Promise.reject('Invalid Bing Search API subscription key!');
    }
  },
};
</code>```

[update]

Your comment suggest that you do not call search correctly or handle the promise it returns correctly. You have no control over how long a response takes so in a set of responses the first request may return last. This is why you have Promise.all

```<code>const searchObjects = [s1,s2];
const Fail = function(reason){this.reason=reason;};
Promise.all(
  searchObjects.map(
    searchObject => obj.search(searchObject)
    .then(
      x=>[x,searchObject]//if resolve just pass result
      ,err =>new Fail([err,searchObject])//if reject add a Fail object with some detail
    )
  )
)
.then(
  results => {
    console.log(
      "resolved results:",
      results.filter(([r,_])=>(r&&r.constructor)!==Fail)
    );
    console.log(
      "failed results:",
      results.filter(([r,_])=>(r&&r.constructor)===Fail)
    );
  }
)
</code>```

If you have a lot of searches then maybe you want to throttle the amount of responses withing a certain time period or active connections. Let me know if you need help with that.

Body:
I'm having some issues understanding how the Promise functionality works, I have previously used Bluebird but I wanted to try to learn the new await/async standard in order to improve as a programmer. I have used async/await and created promises where I feel appropriate however the functions are still executing out of order.

I'm running this on the latest version of Node with Webpack, I'm not getting any meaningful errors. It runs fine just not as expected. My output when running it is:

Searching the Web for: Test String
Web search Completed!
Promise { <pending> }
Response Handler Completed!

Ideally I'd like it to respond with:

Searching the Web for: Test String
Response Handler Completed
Web search Completed

And then return the output of my response handler.

Can anyone spot my mistake?

const https = require('https');

// Replace the subscriptionKey string value with your valid subscription key.
const subscriptionKey = '<samplekey>';

const host = 'api.cognitive.microsoft.com';
const path = '/bing/v7.0/search';

const response_handler = async (response) => {
    return new Promise((resolve, reject) => {
      let body = '';
      response.on('data', (d) => {
        body += d;
        resolve(body);
      });
      response.on('end', () => {
        console.log('\nRelevant Headers:\n');
        for (const header in response.headers)
                // header keys are lower-cased by Node.js
          {
          if (header.startsWith('bingapis-') || header.startsWith('x-msedge-')) { console.log(`${header}: ${response.headers[header]}`); }
        }
        body = JSON.stringify(JSON.parse(body), null, '  ');
        //console.log('\nJSON Test Response:\n');
        //console.log(body);
      });
      response.on('error', (e) => {
        console.log(`Error: ${e.message}`);
      });
      console.log('Response Handler Completed!');

    });
};

const bing_web_search = async (search) => {
  return new Promise((resolve, reject) => {
  console.log(`Searching the Web for: ${search}`);
  const request_params = {
    method: 'GET',
    hostname: host,
    path: `${path}?q=${encodeURIComponent(search)}&$responseFilter=${encodeURIComponent('Webpages')}&count=${50}`,
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
    },
  };

  const req = https.request(request_params, response_handler);

  console.log('Web search Completed!');
  console.log(req.body);
  req.end();
  });
};

module.exports = {
  search: async (search) => {
    if (subscriptionKey.length === 32) {
       const result = await bing_web_search(search);
       console.log('Search Completed');
    } else {
      console.log('Invalid Bing Search API subscription key!');
      console.log('Please paste yours into the source code.');
    }
  },
};

Body:
A bit late but the following should set you on the way, I made changes to the code. If you have any questions please let me know.

const https = require('https');

// Replace the subscriptionKey string value with your valid subscription key.
const subscriptionKey = '<samplekey>';

const host = 'api.cognitive.microsoft.com';
const path = '/bing/v7.0/search';

const response_handler = (resolve,reject) => (response) => { // no need for async, you return a promise
  //this one does not return anything, it's the handler for the response and will resolve
  // or reject accordingly
  let body = '';
  response.on('data', (d) => {
    body += d;
    //cannot resolve yet, we're not done
    //  you can resolve on end maybe? I don't know nodejs http
    //  if end event is called when request fails then end would not
    //  be the correct way either, better use fetch api
    //resolve(body);
  });
  response.on('end', () => {
    console.log('\nRelevant Headers:\n');
    for (const header in response.headers)
    // header keys are lower-cased by Node.js
    {
      if (header.startsWith('bingapis-') || header.startsWith('x-msedge-')) { console.log(`${header}: ${response.headers[header]}`); }
    }
    body = JSON.stringify(JSON.parse(body), null, '  ');
    resolve(body);//resolving the promise returned by bing_web_search
    //console.log('\nJSON Test Response:\n');
    //console.log(body);
  });
  response.on('error', (e) => {
    console.log(`Error: ${e.message}`);
    //need to reject with the error
    reject(e);
  });
  console.log('Response Handler Completed!');

};
//no need to specify async, you are not awaiting anything
//  you are creating a promise, when using non promise asynchronous
//  functions that work with callbacks or event emitting objects
//  you need resolve and reject functions so you have to return
//  new Promise(
//    (resolve,reject)=>somecallbackNeedingFunction((err,result)=>
//      err ? reject(err) : resolve(result)
//    )
//  )
const bing_web_search = (search) => {
  return new Promise((resolve, reject) => {
    console.log(`Searching the Web for: ${search}`);
    const request_params = {
      method: 'GET',
      hostname: host,
      path: `${path}?q=${encodeURIComponent(search)}&$responseFilter=${encodeURIComponent('Webpages')}&count=${50}`,
      headers: {
        'Ocp-Apim-Subscription-Key': subscriptionKey,
      },
    };

    const req = https.request(
      request_params,
      response_handler(resolve,reject)//passing this resolve and reject
    );
    //no, request not completed, we just started
    console.log('Web search Completed!');
    // console.log(req.body); // nothing to log here
    req.end();
  });
};

module.exports = {
  search: async (search) => {
    if (subscriptionKey.length === 32) {
      //did not change anything bing_web_search returns a promise
      //  so you can just await it
      const result = await bing_web_search(search);
      console.log('Search Completed');
      //this will resolve with the results
      return result
    } else {
      console.log('Invalid Bing Search API subscription key!');
      console.log('Please paste yours into the source code.');
      //the caller of this function can handle the rejection
      return Promise.reject('Invalid Bing Search API subscription key!');
    }
  },
};

[update]

Your comment suggest that you do not call search correctly or handle the promise it returns correctly. You have no control over how long a response takes so in a set of responses the first request may return last. This is why you have Promise.all

const searchObjects = [s1,s2];
const Fail = function(reason){this.reason=reason;};
Promise.all(
  searchObjects.map(
    searchObject => obj.search(searchObject)
    .then(
      x=>[x,searchObject]//if resolve just pass result
      ,err =>new Fail([err,searchObject])//if reject add a Fail object with some detail
    )
  )
)
.then(
  results => {
    console.log(
      "resolved results:",
      results.filter(([r,_])=>(r&&r.constructor)!==Fail)
    );
    console.log(
      "failed results:",
      results.filter(([r,_])=>(r&&r.constructor)===Fail)
    );
  }
)

If you have a lot of searches then maybe you want to throttle the amount of responses withing a certain time period or active connections. Let me know if you need help with that.


问:
How to select max price using multiple query
i have create tow table,  table and data inserting value are given below :

```<code>create table product (
pid number(10) primary key,
pname varchar2(30)
);

INSERT INTO product values(100,'Apple');
INSERT INTO product values(101,'Banana');
INSERT INTO product values(102,'Pinaple');
INSERT INTO product values(103,'Orange');

create table purchase(
invid  number(10) primary key,
pid number(10),
pprice number(10)
);
alter table purchase add(constraint pid_fk FOREIGN KEY (pid) references  product(pid));

INSERT INTO  purchase values(10,101,30);
INSERT INTO  purchase values(11,103,35);
INSERT INTO  purchase values(12,103,9);
INSERT INTO  purchase values(13,103,22);
INSERT INTO  purchase values(14,101,12);
</code>```

now i have select table purchase show give data

```<code>invid    pid  pprice
10       101   30
11       103   35
12       103    9
13       103   22
14       101   12
</code>```

now i want to be last insert price pid=103
now need show  pprice=22
i have all ready done the task using two query  such as:

select max(invid) from purchase where pid=103;

result is 22  and running next statement

select max(pprice) from purchase where invid=13;

show result =22
 i want to show result 22 using  running one statment,

答:
The aggregate FIRST/LAST function is made exactly for this kind of task. Unfortunately it seems the vast majority of developers don't use it - either because they are not aware of its existence, or because they don't understand how it works, or for who knows what other reason.

https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions056.htm

The function allows for the case when the max(invid) (in your model) is not unique; in which case you must decide WHICH pprice to select. You can select the max, or min, or average pprice (or the sum for that matter), from all those that have pid = 103 and the max value in the invid column. Of course, if the max(invid) is unique (as it is in your problem), then all these functions will return just the pprice associated to that invid; but you must still use one of these aggregate functions, since that uniqueness is not known at parsing time, it is only known at execution time. min is conventionally used in this manner. So:

```<code>select min(pprice) keep (dense_rank last order by invid) as pprice
from   ........
where  pid = 103
;
</code>```

Body:
i have create tow table,  table and data inserting value are given below :

create table product (
pid number(10) primary key,
pname varchar2(30)
);

INSERT INTO product values(100,'Apple');
INSERT INTO product values(101,'Banana');
INSERT INTO product values(102,'Pinaple');
INSERT INTO product values(103,'Orange');

create table purchase(
invid  number(10) primary key,
pid number(10),
pprice number(10)
);
alter table purchase add(constraint pid_fk FOREIGN KEY (pid) references  product(pid));

INSERT INTO  purchase values(10,101,30);
INSERT INTO  purchase values(11,103,35);
INSERT INTO  purchase values(12,103,9);
INSERT INTO  purchase values(13,103,22);
INSERT INTO  purchase values(14,101,12);

now i have select table purchase show give data

invid    pid  pprice
10       101   30
11       103   35
12       103    9
13       103   22
14       101   12

now i want to be last insert price pid=103
now need show  pprice=22
i have all ready done the task using two query  such as:

select max(invid) from purchase where pid=103;

result is 22  and running next statement

select max(pprice) from purchase where invid=13;

show result =22
 i want to show result 22 using  running one statment,

Body:
The aggregate FIRST/LAST function is made exactly for this kind of task. Unfortunately it seems the vast majority of developers don't use it - either because they are not aware of its existence, or because they don't understand how it works, or for who knows what other reason.

https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions056.htm

The function allows for the case when the max(invid) (in your model) is not unique; in which case you must decide WHICH pprice to select. You can select the max, or min, or average pprice (or the sum for that matter), from all those that have pid = 103 and the max value in the invid column. Of course, if the max(invid) is unique (as it is in your problem), then all these functions will return just the pprice associated to that invid; but you must still use one of these aggregate functions, since that uniqueness is not known at parsing time, it is only known at execution time. min is conventionally used in this manner. So:

select min(pprice) keep (dense_rank last order by invid) as pprice
from   ........
where  pid = 103
;


问:
Iterating Through a C# Object
I am looking for the most efficient way of iterating through attributes within an object and checking to see if it has a custom decorator. The challenge is that my object has other objects within it that may have this custom decorator and the SUB-Objects may have objects as well with decorators.

For now the code down below is only reaching into the first layer of sub objects is there a particular way in which I can go within the loop N times efficiently?

```<code>List<PropertyInfo> allProperties = type.GetProperties().ToList();

Dictionary<string, List<string>> groupIndexes = new Dictionary<string, List<string>>();

foreach (var property in type.GetProperties())
{
    var nestedProperties = property.PropertyType.GetProperties();
    foreach (var nestedProperty in nestedProperties)
    {
        var singleNestedPropertyIndex = nestedProperty.GetCustomAttribute<SingleIndexAttribute>();
        var groupNestedIndex = nestedProperty.GetCustomAttribute<GroupIndexAttribute>();
        var ttlIndex = property.GetCustomAttribute<TTLIndexAttribute>();

        if (singleNestedPropertyIndex != null || groupNestedIndex != null || ttlIndex != null)
        {
            allProperties.Add(nestedProperty);
        }
    }
}
</code>```

答:
You could do it non-recursively by keeping a stack of properties yet-to-visit and a hash set of properties already visited. Then, you can do a while loop on the properties yet-to-visit until you've hit them all.

For example (note: code isn't tested):

```<code>HashSet<PropertyInfo> visitedProperties = new HashSet<PropertyInfo>();
Stack<PropertyInfo> remainingProperties = new Stack<PropertyInfo>(type.GetProperties());
List<PropertyInfo> foundProperties = new List<PropertyInfo>();

while (remainingProperties.Count > 0)
{
    var currentProperty = remainingProperties.Pop();

    // Process this property if we haven't visited it yet
    // Add returns true if the element is not yet in the set
    if (visitedProperties.Add(currentProperty))
    {

        // Add sub-properties to the remaining property list if we haven't visited them
        var nestedProperties = currentProperty.PropertyType.GetProperties();
        foreach (var nestedProperty in nestedProperties)
        {
            if (!visitedProperties.Contains(nestedProperty))
            {
                remainingProperties.Push(nestedProperty);
            }
        }

        // Check the current property for attributes
        var singleNestedPropertyIndex = nestedProperty.GetCustomAttribute<SingleIndexAttribute>();
        var groupNestedIndex = nestedProperty.GetCustomAttribute<GroupIndexAttribute>();
        var ttlIndex = property.GetCustomAttribute<TTLIndexAttribute>();

        if (singleNestedPropertyIndex != null || groupNestedIndex != null || ttlIndex != null)
        {
            foundProperties.Add(nestedProperty);
        }
    }
}
</code>```

This will perform in O(N) time, where N is the total number of properties and nested sub-properties in the entire tree.

Title: Iterating Through a C# Object

Body:
I am looking for the most efficient way of iterating through attributes within an object and checking to see if it has a custom decorator. The challenge is that my object has other objects within it that may have this custom decorator and the SUB-Objects may have objects as well with decorators.

For now the code down below is only reaching into the first layer of sub objects is there a particular way in which I can go within the loop N times efficiently?

List<PropertyInfo> allProperties = type.GetProperties().ToList();

Dictionary<string, List<string>> groupIndexes = new Dictionary<string, List<string>>();

foreach (var property in type.GetProperties())
{
    var nestedProperties = property.PropertyType.GetProperties();
    foreach (var nestedProperty in nestedProperties)
    {
        var singleNestedPropertyIndex = nestedProperty.GetCustomAttribute<SingleIndexAttribute>();
        var groupNestedIndex = nestedProperty.GetCustomAttribute<GroupIndexAttribute>();
        var ttlIndex = property.GetCustomAttribute<TTLIndexAttribute>();

        if (singleNestedPropertyIndex != null || groupNestedIndex != null || ttlIndex != null)
        {
            allProperties.Add(nestedProperty);
        }
    }
}

Body:
You could do it non-recursively by keeping a stack of properties yet-to-visit and a hash set of properties already visited. Then, you can do a while loop on the properties yet-to-visit until you've hit them all.

For example (note: code isn't tested):

HashSet<PropertyInfo> visitedProperties = new HashSet<PropertyInfo>();
Stack<PropertyInfo> remainingProperties = new Stack<PropertyInfo>(type.GetProperties());
List<PropertyInfo> foundProperties = new List<PropertyInfo>();

while (remainingProperties.Count > 0)
{
    var currentProperty = remainingProperties.Pop();

    // Process this property if we haven't visited it yet
    // Add returns true if the element is not yet in the set
    if (visitedProperties.Add(currentProperty))
    {

        // Add sub-properties to the remaining property list if we haven't visited them
        var nestedProperties = currentProperty.PropertyType.GetProperties();
        foreach (var nestedProperty in nestedProperties)
        {
            if (!visitedProperties.Contains(nestedProperty))
            {
                remainingProperties.Push(nestedProperty);
            }
        }

        // Check the current property for attributes
        var singleNestedPropertyIndex = nestedProperty.GetCustomAttribute<SingleIndexAttribute>();
        var groupNestedIndex = nestedProperty.GetCustomAttribute<GroupIndexAttribute>();
        var ttlIndex = property.GetCustomAttribute<TTLIndexAttribute>();

        if (singleNestedPropertyIndex != null || groupNestedIndex != null || ttlIndex != null)
        {
            foundProperties.Add(nestedProperty);
        }
    }
}

This will perform in O(N) time, where N is the total number of properties and nested sub-properties in the entire tree.


问:
When does a view outlet have to be set?
I have read through other answers on how to fix "view outlet was not set" exceptions, and understand how to set the file owner and view outlet. However, I can't understand when/why that exception is raised. How come I can get away with this, and it's not an issue?

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let viewNib = UINib(nibName: "MyView", bundle: nil)
    let myView = viewNib.instantiate(withOwner: nil, options: nil).first as! MyView

    self.view = myView
}
</code>```

The MyView class is initialized with a nib, and the nib file itself does not have a file owner set, nor a view outlet, and it's fine. But other times, this doesn't work. I've tried to reproduce a specific case identifying when the exception is and isn't raised, but haven't been able to pin it down.

答:
Alladinian's comment helped. The relevant docs are from the loadView() method:

A view controller has an associated nib file if the nibName property returns a non-nil value, which occurs if the view controller was instantiated from a storyboard, if you explicitly assigned it a nib file using the init(nibName:bundle:) method, or if iOS finds a nib file in the app bundle with a name based on the view controller's class name.

For example, I made a nib with the name 'DuckView', and a view controller with the name 'DuckViewController', and Xcode automatically associated the two and expected the view outlet to be set. If the view outlet is not set, AND loadView() is not overridden, the exception is raised. Conversely, if either the view outlet IS set OR the loadView() method is implemented, it runs fine.

Title: When does a view outlet have to be set?

Body:
I have read through other answers on how to fix "view outlet was not set" exceptions, and understand how to set the file owner and view outlet. However, I can't understand when/why that exception is raised. How come I can get away with this, and it's not an issue?

override func viewDidLoad() {
    super.viewDidLoad()

    let viewNib = UINib(nibName: "MyView", bundle: nil)
    let myView = viewNib.instantiate(withOwner: nil, options: nil).first as! MyView

    self.view = myView
}

The MyView class is initialized with a nib, and the nib file itself does not have a file owner set, nor a view outlet, and it's fine. But other times, this doesn't work. I've tried to reproduce a specific case identifying when the exception is and isn't raised, but haven't been able to pin it down.


问:
Set font size in custom class Xamarin Forms
I would like set in may custom class font size. Do you now how I can do this?

CustomButton class

```<code>  public static readonly BindableProperty PaddingProperty =
        BindableProperty.Create(
            nameof(Padding),
            typeof(Thickness),
            typeof(CustomButton),
            new Thickness(0, 0, 0, 0));

    public static readonly BindableProperty TypeProperty =
        BindableProperty.Create(
            nameof(Type),
            typeof(TypeEnum),
            typeof(CustomButton),
            TypeEnum.Blue
            );

 public Thickness Padding
    {
        get { return (Thickness)GetValue(PaddingProperty); }
        set { SetValue(PaddingProperty, value); }
    }
</code>```

答:
If your "custom button" inherits from Xamarin.Forms.Button you can just set its "FontSize" property.</p>

```<code>public class CustomButton : Xamarin.Forms.Button //Inheriting from Xamarin.Forms.Button!
    {
        public static readonly BindableProperty PaddingProperty =
        BindableProperty.Create(
            nameof(Padding),
            typeof(Thickness),
            typeof(CustomButton),
            new Thickness(0, 0, 0, 0));

        public static readonly BindableProperty TypeProperty =
            BindableProperty.Create(
                nameof(Type),
                typeof(TypeEnum),
                typeof(CustomButton),
                TypeEnum.Blue
                );

        public Thickness Padding
        {
            get { return (Thickness)GetValue(PaddingProperty); }
            set { SetValue(PaddingProperty, value); }
        }

        public CustomButton()
        {
            FontSize = 123; //FontSize property on Xamarin.Forms.Button
        }
    }
</code>```

Body:
I would like set in may custom class font size. Do you now how I can do this?

CustomButton class

  public static readonly BindableProperty PaddingProperty =
        BindableProperty.Create(
            nameof(Padding),
            typeof(Thickness),
            typeof(CustomButton),
            new Thickness(0, 0, 0, 0));

    public static readonly BindableProperty TypeProperty =
        BindableProperty.Create(
            nameof(Type),
            typeof(TypeEnum),
            typeof(CustomButton),
            TypeEnum.Blue
            );

 public Thickness Padding
    {
        get { return (Thickness)GetValue(PaddingProperty); }
        set { SetValue(PaddingProperty, value); }
    }

Body:
If your "custom button" inherits from Xamarin.Forms.Button you can just set its "FontSize" property.

public class CustomButton : Xamarin.Forms.Button //Inheriting from Xamarin.Forms.Button!
    {
        public static readonly BindableProperty PaddingProperty =
        BindableProperty.Create(
            nameof(Padding),
            typeof(Thickness),
            typeof(CustomButton),
            new Thickness(0, 0, 0, 0));

        public static readonly BindableProperty TypeProperty =
            BindableProperty.Create(
                nameof(Type),
                typeof(TypeEnum),
                typeof(CustomButton),
                TypeEnum.Blue
                );

        public Thickness Padding
        {
            get { return (Thickness)GetValue(PaddingProperty); }
            set { SetValue(PaddingProperty, value); }
        }

        public CustomButton()
        {
            FontSize = 123; //FontSize property on Xamarin.Forms.Button
        }
    }


问:
ASP.NET Webdeploy failing; AddScheduledJob does not exist in project
I have an ASP.NET project with two WebJobs, one of the WebJobs publishes fine but the second fails to publish and I get the following error message:

The target "AddScheduledJob" does not exist in the project.

Both WebJobs where set up in the "Run on Demand" mode.

I am struggling to find any explanation for this error and cannot see what is different between my two WebJobs.  Anyone come across this?

Edited

I eventually found the problem thanks to David Ebbo pointing me in the right direction. I found that I had ended up with two import lines in the .csproj file of one of my WebJobs projects:

```<code>  <Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.0.2\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.0.2\tools\webjobs.targets')" />
</code>```

After deleting the first of these everything worked fine.  I don't know how this happened but can only assume that something went wrong when I updated the NuGet package.

答:
I had a similar problem when I had existing WebJob SDK projects under an ASP.NET site, and I added a new one.  The new one was using a newer version of the Microsoft.Web.WebJobs.Publish package.

I used the "Add Existing Project as Azure WebJob" flow to add it, and then I noticed in the ASP.NET project that there were now two Imports:

```<code>  <Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.0.10\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.0.10\tools\webjobs.targets')" />
  <Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.1.0\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.1.0\tools\webjobs.targets')" />
</code>```

I simply removed the Import with the older version and that took care of it.

Body:
I have an ASP.NET project with two WebJobs, one of the WebJobs publishes fine but the second fails to publish and I get the following error message:

The target "AddScheduledJob" does not exist in the project.

Both WebJobs where set up in the "Run on Demand" mode.

I am struggling to find any explanation for this error and cannot see what is different between my two WebJobs.  Anyone come across this?

Edited

I eventually found the problem thanks to David Ebbo pointing me in the right direction. I found that I had ended up with two import lines in the .csproj file of one of my WebJobs projects:

  <Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.0.2\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.0.2\tools\webjobs.targets')" />

After deleting the first of these everything worked fine.  I don't know how this happened but can only assume that something went wrong when I updated the NuGet package.

Body:
I had a similar problem when I had existing WebJob SDK projects under an ASP.NET site, and I added a new one.  The new one was using a newer version of the Microsoft.Web.WebJobs.Publish package.

I used the "Add Existing Project as Azure WebJob" flow to add it, and then I noticed in the ASP.NET project that there were now two Imports:

  <Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.0.10\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.0.10\tools\webjobs.targets')" />
  <Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.1.0\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.1.0\tools\webjobs.targets')" />

I simply removed the Import with the older version and that took care of it.


问:
node js and mongodb asynchronous issue
i'm new to mongodb and i'm having problems updating a local variable after a query. i'm using node js and i have a local variable i'm trying to update depending on my query result, but it seems that my functions returns before the query. i understand node js is asynchronous but i'm having trouble dealing with that. you can see my code below:

function userExist(userList, username){
    //var usert = new UserSchema()
    var exist = false
    UserSchema.findOne({userName: username}, function (err, usert) {
      if (err) return handleError(err);
      if (usert) {
        // doc may be null if no document matched
        exist = true
      }
    })
    console.log("boolean " + bool)
    return exist
   // return username in userList
    // return query
}```
</div>
</div>
</p>

<p>I'm also having a different but unrelated issue where i'm trying to extract a specific value from a query result. my schema is as follow:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//import dependency
var mongoose = require('mongoose')
var Schema = mongoose.Schema
//create new instance of the mongoose.schema. the schema takes an
//object that shows the shape of your database entries.
var UserSchema = new Schema({
 userName: String,
 userID: String,
 Conversations: [
   {
     conversationID: String,
     messages: [
       {
         message: String,
         messageID: String,
         sender: String,
         time: String
       }
     ]
   }
 ]
})
//export our module to use in server.js
module.exports = mongoose.model('User', UserSchema)</code>```

i'm trying to get the values in conversations array, add a new conversation to it and push it back in the database.

An answer to either question would be really helpful and appreciated.

just for clarification this is where i'm using the userExist function:

//Verify Username
 socket.on(VERIFY_USER, (nickname, callback)=>{
  if(userExist(connectedUsers, nickname)){
      console.log("user exist")
   callback({ userExist:true, user:null })
  }else{
      console.log("user does not exist")
   callback({ userExist:false, user:createUser({name:nickname, socketId:socket.id})})
  }
 })```

答:
As already pointed out the findOne returns a promise.

You can handle the promise executing callbacks on the success or fail of the findOne result

Define two functions to pass as callbacks

```<code>function success(user){
    //no error check
    //doc has been found
    //do something
    } ;
function fail(err){
    console. log(err)
    }
</code>```

Then in the findOne function body

```<code>if (err) return fail(err) ;
//else
return success(user)
</code>```

OR

you can wrap the userExist function body to return a promise

```<code>function userExist(userList, username){
  return new Promise(function(resolve, reject){
    var exist = false
    UserSchema.findOne({userName: username}, function (err, usert) {
      if (err) return reject(err);
      if (usert) {
        // doc may be null if no document matched
        exist = true
        resolve(exist)
      }
    })
})
}
</code>```

And when you call the userExist

```<code> userExist(userList, username).then(function(user){
       //do something with the user
    }).catch(function(reason) {
         console.error(reason);
    });
</code>```

Title: node js and mongodb asynchronous issue

Body:
i'm new to mongodb and i'm having problems updating a local variable after a query. i'm using node js and i have a local variable i'm trying to update depending on my query result, but it seems that my functions returns before the query. i understand node js is asynchronous but i'm having trouble dealing with that. you can see my code below:

function userExist(userList, username){
    //var usert = new UserSchema()
    var exist = false
    UserSchema.findOne({userName: username}, function (err, usert) {
      if (err) return handleError(err);
      if (usert) {
        // doc may be null if no document matched
        exist = true
      }
    })
    console.log("boolean " + bool)
    return exist
   // return username in userList
    // return query
}

I'm also having a different but unrelated issue where i'm trying to extract a specific value from a query result. my schema is as follow:

//import dependency
var mongoose = require('mongoose')
var Schema = mongoose.Schema
//create new instance of the mongoose.schema. the schema takes an
//object that shows the shape of your database entries.
var UserSchema = new Schema({
 userName: String,
 userID: String,
 Conversations: [
   {
     conversationID: String,
     messages: [
       {
         message: String,
         messageID: String,
         sender: String,
         time: String
       }
     ]
   }
 ]
})
//export our module to use in server.js
module.exports = mongoose.model('User', UserSchema)

i'm trying to get the values in conversations array, add a new conversation to it and push it back in the database.

An answer to either question would be really helpful and appreciated.

just for clarification this is where i'm using the userExist function:

//Verify Username
 socket.on(VERIFY_USER, (nickname, callback)=>{
  if(userExist(connectedUsers, nickname)){
      console.log("user exist")
   callback({ userExist:true, user:null })
  }else{
      console.log("user does not exist")
   callback({ userExist:false, user:createUser({name:nickname, socketId:socket.id})})
  }
 })

Body:
As already pointed out the findOne returns a promise.

You can handle the promise executing callbacks on the success or fail of the findOne result

Define two functions to pass as callbacks

function success(user){
    //no error check
    //doc has been found
    //do something
    } ;
function fail(err){
    console. log(err)
    }

Then in the findOne function body

if (err) return fail(err) ;
//else
return success(user)

OR

you can wrap the userExist function body to return a promise

function userExist(userList, username){
  return new Promise(function(resolve, reject){
    var exist = false
    UserSchema.findOne({userName: username}, function (err, usert) {
      if (err) return reject(err);
      if (usert) {
        // doc may be null if no document matched
        exist = true
        resolve(exist)
      }
    })
})
}

And when you call the userExist

 userExist(userList, username).then(function(user){
       //do something with the user
    }).catch(function(reason) {
         console.error(reason);
    });