问:
Azure Cognitive Services: Where are the missing Custom Vision Performance Statistics?
I am querying the Azure Custom Vision V3.0 Training API (see https://westeurope.dev.cognitive.microsoft.com/docs/services/Custom_Vision_Training_3.0/operations/5c771cdcbf6a2b18a0c3b809) so I can generate per-tag ROCs myself via the GetIterationPerformance operation, part of whose output is:

```<code>{u'averagePrecision': 0.92868346,
 u'perTagPerformance': [{u'averagePrecision': 0.4887446,
                         u'id': u'uuid1',
                         u'name': u'tag_name_1',
                         u'precision': 0.0,
                         u'precisionStdDeviation': 0.0,
                         u'recall': 0.0,
                         u'recallStdDeviation': 0.0},
                        {u'averagePrecision': 1.0,
                         u'id': u'uuid2',
                         u'name': u'tag_name_2',
                         u'precision': 0.0,
                         u'precisionStdDeviation': 0.0,
                         u'recall': 0.0,
                         u'recallStdDeviation': 0.0},
                    {u'averagePrecision': 0.9828302,
                     u'id': u'uuid3',
                     u'name': u'tag_name_3',
                     u'precision': 1.0,
                     u'precisionStdDeviation': 0.0,
                     u'recall': 0.5555556,
                     u'recallStdDeviation': 0.0}],
</code>```

u'precision': 0.9859485,
 u'precisionStdDeviation': 0.0,
 u'recall': 0.3752228,
 u'recallStdDeviation': 0.0}

The precision and recall uncertainties, precisionStdDeviation and recallStdDeviation respectively, always seem to be 0.0. Is this user error and if not are there any plans to activate these stats?

答: So currently precisionStdDeviation and recallStdDeviation are not used so it will always be zero, it is not user error. These two metric exists because previously we do a cross validation on user dataset, and for each cross validation fold we have a precision and recall, the stddev measures the variation of precision and recall across folds. Now instead of cross validation, we split a proportion of the user data as validation set and report IterationPerformance based on that, as there's no multiple folds, the stddev will be always be zero. We are on our plan to retire these two fields, sorry for the confusion, it will be very likely to be removed in the next major version.

Body:
I am querying the Azure Custom Vision V3.0 Training API (see https://westeurope.dev.cognitive.microsoft.com/docs/services/Custom_Vision_Training_3.0/operations/5c771cdcbf6a2b18a0c3b809) so I can generate per-tag ROCs myself via the GetIterationPerformance operation, part of whose output is:

{u'averagePrecision': 0.92868346,
 u'perTagPerformance': [{u'averagePrecision': 0.4887446,
                         u'id': u'uuid1',
                         u'name': u'tag_name_1',
                         u'precision': 0.0,
                         u'precisionStdDeviation': 0.0,
                         u'recall': 0.0,
                         u'recallStdDeviation': 0.0},
                        {u'averagePrecision': 1.0,
                         u'id': u'uuid2',
                         u'name': u'tag_name_2',
                         u'precision': 0.0,
                         u'precisionStdDeviation': 0.0,
                         u'recall': 0.0,
                         u'recallStdDeviation': 0.0},
                    {u'averagePrecision': 0.9828302,
                     u'id': u'uuid3',
                     u'name': u'tag_name_3',
                     u'precision': 1.0,
                     u'precisionStdDeviation': 0.0,
                     u'recall': 0.5555556,
                     u'recallStdDeviation': 0.0}],

u'precision': 0.9859485,
 u'precisionStdDeviation': 0.0,
 u'recall': 0.3752228,
 u'recallStdDeviation': 0.0}

The precision and recall uncertainties, precisionStdDeviation and recallStdDeviation respectively, always seem to be 0.0. Is this user error and if not are there any plans to activate these stats?


来源: stackexchange

问:
remove elements from list of strings while traversing
how to remove elements from a list of strings while traversing through it.
I have a list

```<code>list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']
</code>```

i want to remove $ fro the list and if a ) or )% or % comes add that to the previous elemt of the list.

expected output is :

```<code>['', '32,324', '32', '(35)', '32,321']
</code>```

what i have tried is

```<code>for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      list1[j-1] = list1[j-1] + element
      list1.pop(j)
   elif element == '$':
      list1.pop(j)
</code>```

but the output i am getting is

```<code>['', '32,324', '32', '(35)', '$', '32,321']
</code>```

whis is not the expected output. Please help

This question is different from the suggested reference is, here I have to do a concatenation with the previous element if the current element is ),)% or %.

答:
Instead of attempting to remove and merge elements dynamically while iterating on the list, it will be much easier to make a new list based on the conditions here.</p>

```<code>list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']

out = []
for element in list1:
    if element == "$":
        continue #skip if $ present
    elif element in ("%", ")", ")%"):
        out[-1] = out[-1] + element #merge with last element of out so far.
    else:
        out.append(element)

print(out)
#Output:
['', '32,324', '32', '(35)', '32,321']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
how to remove elements from a list of strings while traversing through it.
I have a list

list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']

i want to remove $ fro the list and if a ) or )% or % comes add that to the previous elemt of the list.

expected output is :

['', '32,324', '32', '(35)', '32,321']

what i have tried is

for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      list1[j-1] = list1[j-1] + element
      list1.pop(j)
   elif element == '$':
      list1.pop(j)

but the output i am getting is

['', '32,324', '32', '(35)', '$', '32,321']

whis is not the expected output. Please help

This question is different from the suggested reference is, here I have to do a concatenation with the previous element if the current element is ),)% or %.

Body:
Instead of attempting to remove and merge elements dynamically while iterating on the list, it will be much easier to make a new list based on the conditions here.

list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']

out = []
for element in list1:
    if element == "$":
        continue #skip if $ present
    elif element in ("%", ")", ")%"):
        out[-1] = out[-1] + element #merge with last element of out so far.
    else:
        out.append(element)

print(out)
#Output:
['', '32,324', '32', '(35)', '32,321']


问:
Open source graph database
I need graph database for my project. I want to perform shortest path operation on the graph. I searched google and found neo4j, InfoGrid and sones. I am not sure which one performs the best.

Neo4j is insisting on transaction for read queries also, so I am worried it will cause delays. I want high performance graph database engine. It will be awesome if it can support shortest path also.

答:
I would recommend you to take a look at AgensGraph and its perfomance.  https://bitnine.net/agensgraph/

AgensGraph supports "Shortest path" as well and you can use it easily.

ContentLicense: CC BY-SA 2.5

Title: Open source graph database


问:
Error when requesting discovery dock ( HTTPS required)
I am using Identity server 4. It was working fine in fact still, everything is working.  However when I try to  call

```<code>var client = new HttpClient();
// discover endpoints from metadata
var disco = client.GetDiscoveryDocumentAsync(IDPBaseURL).Result;
it gives me error
http://xxx.x.x.xx:8080/.well-known/openid-configuration: HTTPS required.
</code>```

It's working from Visual studio and local IIS deployment. However i am facing this error only when deploying on the server.

any Idea?

答:
I ran into this same issue and solved it by changing the policy on the discovery document request.</p>

```<code>var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest {
    Address = "http://xxx.xxx.x.xxx:xxxx",
    Policy =
    {
        RequireHttps = false
    }
});
</code>```

Body:
I am using Identity server 4. It was working fine in fact still, everything is working.  However when I try to  call

var client = new HttpClient();
// discover endpoints from metadata
var disco = client.GetDiscoveryDocumentAsync(IDPBaseURL).Result;
it gives me error
http://xxx.x.x.xx:8080/.well-known/openid-configuration: HTTPS required.

It's working from Visual studio and local IIS deployment. However i am facing this error only when deploying on the server.

any Idea?

Body:
I ran into this same issue and solved it by changing the policy on the discovery document request.

var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest {
    Address = "http://xxx.xxx.x.xxx:xxxx",
    Policy =
    {
        RequireHttps = false
    }
});


问:
Combine two lists of different lengths in python
I have 2 lists of different length.
A gift is selected and assigned to a name, then the next gift will be given to the next name, and so on, in the circle, until the gifts are finished.

```<code>gifts = ['pencil', 'pen', 'book', 'notebook', 'pencil_box', 'schoolbag', 'stick']
name = ['John', 'Marcus', 'Marie']
</code>```

Expected Output:

```<code>John: pencil notebook stick
Marcus: pen pencil_box
Marie: book schoolbag
</code>```

Another example:

```<code>gifts  = ['car', 'house', 'phone']
name = ['RichieRich']
</code>```

Expected Output:

```<code>RichieRich: car house phone
</code>```

Some help?

答:
Here you go:</p>

```<code>from itertools import cycle
from collections import defaultdict

gifts = ['pencil', 'pen', 'book', 'notebook', 'pencil_box', 'schoolbag', 'stick']
names = ['John', 'Marcus', 'Marie']

gifts_by_name = defaultdict(list)
for name, gift in zip(cycle(names), gifts):
    gifts_by_name[name].append(gift)

for name in names:
    print '%s: %s' % (name, " ".join(gifts_by_name[name]))
</code>```

Body:
I have 2 lists of different length.
A gift is selected and assigned to a name, then the next gift will be given to the next name, and so on, in the circle, until the gifts are finished.

gifts = ['pencil', 'pen', 'book', 'notebook', 'pencil_box', 'schoolbag', 'stick']
name = ['John', 'Marcus', 'Marie']

Expected Output:

John: pencil notebook stick
Marcus: pen pencil_box
Marie: book schoolbag

Another example:

gifts  = ['car', 'house', 'phone']
name = ['RichieRich']

Expected Output:

RichieRich: car house phone

Some help?

Body:
Here you go:

from itertools import cycle
from collections import defaultdict

gifts = ['pencil', 'pen', 'book', 'notebook', 'pencil_box', 'schoolbag', 'stick']
names = ['John', 'Marcus', 'Marie']

gifts_by_name = defaultdict(list)
for name, gift in zip(cycle(names), gifts):
    gifts_by_name[name].append(gift)

for name in names:
    print '%s: %s' % (name, " ".join(gifts_by_name[name]))


问:
How to right dynamic DAX queries?
I have a few dates for a specific company below is an example:

```<code>CompanyName         Effective Date    Rates

FH1                  2016-07-01        230

FH1                  2016-12-01        110
</code>```

I want to calculate the end date as of above dates so I have a logic in mind for the first row the end date will be -1 the next rows effective date. that is 2016-10-30, and for second row the end date will be the current date for now, and the data for second row will change whenver there will be a third row, hence let say if I have a third row for the same company and dated as 2017-12-01, then for second row the end date will change to be 2017-11-30, and for the third row end date will remain as the current date.

We need to find all the dates in between the effective date and the end date so that we can run the powerbi reports for those specific dates and get the desired rates for those dates.

I need to right a dax which perform this operation for each of the companies, And I have 145 different companies that contains different effective dates.

答:
Following DAX will give you the result you are looking for, add a column:</p>

```<code>EndDate =
var tempEnd = CALCULATE(MIN(YourTable[Effective Date]);FILTER(YourTable; YourTable[CompanyName] = EARLIER(YourTable[CompanyName]) && YourTable[Effective Date] > EARLIER(YourTable[Effective  Date])))
return if (ISBLANK(tempEnd); YourTable[Effective Date]; tempEnd - 1)
</code>```

Title: How to right dynamic DAX queries?

Body:
I have a few dates for a specific company below is an example:

CompanyName         Effective Date    Rates

FH1                  2016-07-01        230

FH1                  2016-12-01        110

I want to calculate the end date as of above dates so I have a logic in mind for the first row the end date will be -1 the next rows effective date. that is 2016-10-30, and for second row the end date will be the current date for now, and the data for second row will change whenver there will be a third row, hence let say if I have a third row for the same company and dated as 2017-12-01, then for second row the end date will change to be 2017-11-30, and for the third row end date will remain as the current date.

We need to find all the dates in between the effective date and the end date so that we can run the powerbi reports for those specific dates and get the desired rates for those dates.

I need to right a dax which perform this operation for each of the companies, And I have 145 different companies that contains different effective dates.

Body:
Following DAX will give you the result you are looking for, add a column:

EndDate =
var tempEnd = CALCULATE(MIN(YourTable[Effective Date]);FILTER(YourTable; YourTable[CompanyName] = EARLIER(YourTable[CompanyName]) && YourTable[Effective Date] > EARLIER(YourTable[Effective  Date])))
return if (ISBLANK(tempEnd); YourTable[Effective Date]; tempEnd - 1)


问:
Why does my function only insert 240 entries into SQLite when the array contains over 3000 elements?
I'm trying to insert all elements from an NSArray (tpInfo) and insert them into an SQLite Database. But only the first 15 rows are being populated, which is 240 entries.  tpInfo contains over 3000 elements.  I've been stuck here for a while, and would appreciate a point in the right direction.

I have tried changing my for loop to increment 'i' by 1, that enters more data, but it's inserted into the incorrect columns/rows and throws an NSRangeException.

'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 2304 beyond bounds [0 .. 2303]'

```<code>-(void) insertTP: (NSMutableArray * ) tpInfo {

NSString * databasePath = [self dataPath: @ "eldb.sqlite3"];
sqlite3 * database;
if (sqlite3_open([databasePath UTF8String], & database) != SQLITE_OK) {
  NSLog(@ "Could not open database");
  return;
} else {
  NSLog(@ "Inserting TimeProfile Data");
}

//for each element in the array, save the array index
sqlite3_stmt * statement;
NSString * SQLInsert = @ "INSERT INTO TIME_PROFILES (TIMEZONE_IID,
TIMEZONE_ID, SERIAL, FROM_TIME, TO_TIME ,MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY, SUNDAY, HOLIDAY, SPECIAL_DAY_ONE,
SPECIAL_DAY_TWO, TIMEZONE_ITEM_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?);";
if (sqlite3_prepare_v2(database, [SQLInsert UTF8String], -1, & statement,
nil) == SQLITE_OK) {

  NSLog(@ "pinfo %@", tpInfo);

  for (int i = 0; i < [tpInfo count]; i += 16) {

  sqlite3_bind_text(statement, 1, [tpInfo[i] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 2, [tpInfo[i + 1] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 3, [tpInfo[i + 2] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 4, [tpInfo[i + 3] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 5, [tpInfo[i + 4] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 6, [tpInfo[i + 5] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 7, [tpInfo[i + 6] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 8, [tpInfo[i + 7] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 9, [tpInfo[i + 8] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 10, [tpInfo[i + 9] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 11, [tpInfo[i + 10] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 12, [tpInfo[i + 11] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 13, [tpInfo[i + 12] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 14, [tpInfo[i + 13] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 15, [tpInfo[i + 14] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 16, [tpInfo[i + 15] UTF8String], -1, NULL);

  if (sqlite3_step(statement) != SQLITE_DONE) {
    NSLog(@"Database returned error %d: %s", sqlite3_errcode(database), sqlite3_errmsg(database));
  }
  sqlite3_reset(statement);
}
sqlite3_finalize(statement);
} else {
  NSLog(@ "Can't prepare: %s", sqlite3_errmsg(database));
}
 sqlite3_close(database);
}
</code>```

答:
Based on the way this is coded, your tpInfo array has 16 columns of data in the first 16 elements (0-15) from TIMEZONE_IID to TIMEZONE_ITEM_ID for the first row, then the second 16 elements (16-31) for the second row.  If so, this is a strange way to populate your tpInfo array.  That should be an array of TimeProfile objects that have 16 attributes, and then you would only increment the for loop by += 1.

This way, what happens if [tpInfo count] is not perfectly divisible by 16?  You're going to get index out of bounds error, which may be what is failing.

Your code should probably look more like this (assuming you have a TimeProfile class object):

```<code>if (sqlite3_prepare_v2(database, [SQLInsert UTF8String], -1, & statement,
nil) == SQLITE_OK) {

for (int i = 0; i < [tpInfo count]; i += 1) {
    TimeProfile *profile = tpInfo[I];
     NSLog(@ "pinfo %@", profile);

  sqlite3_bind_text(statement, 1, [profile.TIMEZONE_IID UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 2, [profile.TIMEZONE_ID UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 3, [profile.SERIAL UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 4, [profile.FROM_TIME UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 5, [profile.TO_TIME UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 6, [profile.MONDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 7, [profile.TUESDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 8, [profile.WEDNESDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 9, [profile.THURSDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 10, [profile.FRIDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 11, [profile.SATURDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 12, [profile.SUNDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 13, [profile.HOLIDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 14, [profile.SPECIAL_DAY_ONE UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 15, [profile.SPECIAL_DAY_TWO UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 16, [profile.SPECIAL_DAY_THREE UTF8String], -1, NULL);

  if (sqlite3_step(statement) != SQLITE_DONE) {
    NSLog(@"Database returned error %d: %s", sqlite3_errcode(database), sqlite3_errmsg(database));
  }

  sqlite3_reset(statement);
}
sqlite3_finalize(statement);
} else {
  NSLog(@ "Can't prepare: %s", sqlite3_errmsg(database));
}
 sqlite3_close(database);
}
</code>```

Body:
I'm trying to insert all elements from an NSArray (tpInfo) and insert them into an SQLite Database. But only the first 15 rows are being populated, which is 240 entries.  tpInfo contains over 3000 elements.  I've been stuck here for a while, and would appreciate a point in the right direction.

I have tried changing my for loop to increment 'i' by 1, that enters more data, but it's inserted into the incorrect columns/rows and throws an NSRangeException.

'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 2304 beyond bounds [0 .. 2303]'

-(void) insertTP: (NSMutableArray * ) tpInfo {

NSString * databasePath = [self dataPath: @ "eldb.sqlite3"];
sqlite3 * database;
if (sqlite3_open([databasePath UTF8String], & database) != SQLITE_OK) {
  NSLog(@ "Could not open database");
  return;
} else {
  NSLog(@ "Inserting TimeProfile Data");
}

//for each element in the array, save the array index
sqlite3_stmt * statement;
NSString * SQLInsert = @ "INSERT INTO TIME_PROFILES (TIMEZONE_IID,
TIMEZONE_ID, SERIAL, FROM_TIME, TO_TIME ,MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY, SUNDAY, HOLIDAY, SPECIAL_DAY_ONE,
SPECIAL_DAY_TWO, TIMEZONE_ITEM_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?);";
if (sqlite3_prepare_v2(database, [SQLInsert UTF8String], -1, & statement,
nil) == SQLITE_OK) {

  NSLog(@ "pinfo %@", tpInfo);

  for (int i = 0; i < [tpInfo count]; i += 16) {

  sqlite3_bind_text(statement, 1, [tpInfo[i] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 2, [tpInfo[i + 1] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 3, [tpInfo[i + 2] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 4, [tpInfo[i + 3] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 5, [tpInfo[i + 4] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 6, [tpInfo[i + 5] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 7, [tpInfo[i + 6] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 8, [tpInfo[i + 7] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 9, [tpInfo[i + 8] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 10, [tpInfo[i + 9] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 11, [tpInfo[i + 10] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 12, [tpInfo[i + 11] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 13, [tpInfo[i + 12] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 14, [tpInfo[i + 13] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 15, [tpInfo[i + 14] UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 16, [tpInfo[i + 15] UTF8String], -1, NULL);

  if (sqlite3_step(statement) != SQLITE_DONE) {
    NSLog(@"Database returned error %d: %s", sqlite3_errcode(database), sqlite3_errmsg(database));
  }
  sqlite3_reset(statement);
}
sqlite3_finalize(statement);
} else {
  NSLog(@ "Can't prepare: %s", sqlite3_errmsg(database));
}
 sqlite3_close(database);
}

Body:
Based on the way this is coded, your tpInfo array has 16 columns of data in the first 16 elements (0-15) from TIMEZONE_IID to TIMEZONE_ITEM_ID for the first row, then the second 16 elements (16-31) for the second row.  If so, this is a strange way to populate your tpInfo array.  That should be an array of TimeProfile objects that have 16 attributes, and then you would only increment the for loop by += 1.

This way, what happens if [tpInfo count] is not perfectly divisible by 16?  You're going to get index out of bounds error, which may be what is failing.

Your code should probably look more like this (assuming you have a TimeProfile class object):

if (sqlite3_prepare_v2(database, [SQLInsert UTF8String], -1, & statement,
nil) == SQLITE_OK) {

for (int i = 0; i < [tpInfo count]; i += 1) {
    TimeProfile *profile = tpInfo[I];
     NSLog(@ "pinfo %@", profile);

  sqlite3_bind_text(statement, 1, [profile.TIMEZONE_IID UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 2, [profile.TIMEZONE_ID UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 3, [profile.SERIAL UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 4, [profile.FROM_TIME UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 5, [profile.TO_TIME UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 6, [profile.MONDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 7, [profile.TUESDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 8, [profile.WEDNESDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 9, [profile.THURSDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 10, [profile.FRIDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 11, [profile.SATURDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 12, [profile.SUNDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 13, [profile.HOLIDAY UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 14, [profile.SPECIAL_DAY_ONE UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 15, [profile.SPECIAL_DAY_TWO UTF8String], -1, NULL);
  sqlite3_bind_text(statement, 16, [profile.SPECIAL_DAY_THREE UTF8String], -1, NULL);

  if (sqlite3_step(statement) != SQLITE_DONE) {
    NSLog(@"Database returned error %d: %s", sqlite3_errcode(database), sqlite3_errmsg(database));
  }

  sqlite3_reset(statement);
}
sqlite3_finalize(statement);
} else {
  NSLog(@ "Can't prepare: %s", sqlite3_errmsg(database));
}
 sqlite3_close(database);
}


问:
HTML form with no action (+ CSP rule no inline javascript)
In the past when I've wanted to disable the default action of a form, I've done

```<code><form action="javascript:void(0);">
</code>```

We now employ a CSP (Content Security Policy) to disallow inline JavaScript. How can we disable the default form action without the inline js?

答:
use jquery</p>

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

        $("#form").submit(function (e) {

            //stop submitting the form
            e.preventDefault();
            return true;

        });
    });
</script>
</code>```

Body:
In the past when I've wanted to disable the default action of a form, I've done

<form action="javascript:void(0);">

We now employ a CSP (Content Security Policy) to disallow inline JavaScript. How can we disable the default form action without the inline js?

Body:
use jquery

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

        $("#form").submit(function (e) {

            //stop submitting the form
            e.preventDefault();
            return true;

        });
    });
</script>


问:
PostgreSQL 9 install on Windows: "Unable to write inside TEMP environment path."
I am attempting to install PostgreSQL 9 (postgresql-9.0.3-1-windows.exe) on my WinXP machine and get the following error at the start:

Some googling around yielded some advice that suggested Windows Scripting Host might be disabled. I've checked and WSH is definitely enabled, so it must be something else. Question is, what?

I can see a file called prerun_checks.vbs is created in %TEMP% and when I try to run this manually, I get the following:

Which looks like a permissions error. However, I am an Admin, and I've given myself full control of the temp folder and it's still not working.

Any help appreciated.

答:
I had the same problem in Windows 10 and the culprit was the OS's permission, or rather the lack thereof, on allowing the executable to write on the User dedicated Temp folder.

Solved it by following my gut and changing the User Temp folder to the same with the system's : Win + Pause/Break to have the Computer Properties window appear (you can do that manually by right-click on Computer icon on Desktop -> Properties) -> click on Advanced System Settings on the panel on the left -> click on Environment Variables and
under "System variables" - Variables, find the TEMP and TMP ones and copy their paths. Then, under "User variables for Administrator" - Variables, find the TEMP and TMP ones and paste the paths. It's most always "C:\Windows\TEMP" anyways ;)

There's this site I read : https://www.askvg.com/where-does-windows-store-temporary-files-and-how-to-change-temp-folder-location/

ContentLicense: CC BY-SA 3.0


问:
jQuery offset error on Chrome & IE
I'm getting this error on Chrome & IE "Cannot read property 'tagName' of null" when I try to get the offset position of an img tag width position:absolute.

html:

```<code><img style="position: absolute;" src="1.jpg">
</code>```

js:

```<code>$('img').offset();
</code>```

I search for reported bugs on jquery issues. I try jQuery 1.4.4 and 1.5.2.... but the error appear. Any ideas?

答: I answer my self. I was including jquery.dimensions which is deprecated. :P</p>

Title: jQuery offset error on Chrome & IE

Body:
I'm getting this error on Chrome & IE "Cannot read property 'tagName' of null" when I try to get the offset position of an img tag width position:absolute.

html:

js:

$('img').offset();

I search for reported bugs on jquery issues. I try jQuery 1.4.4 and 1.5.2.... but the error appear. Any ideas?


问:
Changing WGS84 to EPSG:5330 in R
I would like to change my coordinate form WGS84 to EPSG:5330. Hope, anyone can help me thanks</p>

```<code>ID,X,Y
1,106.6874498,-6.2107887
2,106.6883199,-6.2069667
</code>```

答:
Easy-cheesy with the sp library.

```<code>library(sp)
# Create SpatialPoints out of coordinates.
# Assign WGS84 (EPSG 4326) coordinate reference system.
pts <- SpatialPoints(coords = data.frame(x = c(106.6874498, 106.6883199),
                                         y = c(-6.2107887, -6.2069667)),
                     proj4string = CRS("+init=epsg:4326"))

# Transform SpatialPoints to EPSG 5330.
pts_epsg5330 <- spTransform(x = pts, CRSobj = CRS("+init=epsg:5330"))
</code>```

Result:

```<code># Get coordinates of new SpatialPoints.
> coordinates(pts_epsg5330)

           x        y
[1,] 3532231 213991.4
[2,] 3532328 214415.3
</code>```

Title: Changing WGS84 to EPSG:5330 in R

Body:
I would like to change my coordinate form WGS84 to EPSG:5330. Hope, anyone can help me thanks

ID,X,Y
1,106.6874498,-6.2107887
2,106.6883199,-6.2069667

Body:
Easy-cheesy with the sp library.

library(sp)
# Create SpatialPoints out of coordinates.
# Assign WGS84 (EPSG 4326) coordinate reference system.
pts <- SpatialPoints(coords = data.frame(x = c(106.6874498, 106.6883199),
                                         y = c(-6.2107887, -6.2069667)),
                     proj4string = CRS("+init=epsg:4326"))

# Transform SpatialPoints to EPSG 5330.
pts_epsg5330 <- spTransform(x = pts, CRSobj = CRS("+init=epsg:5330"))

Result:

# Get coordinates of new SpatialPoints.
> coordinates(pts_epsg5330)

           x        y
[1,] 3532231 213991.4
[2,] 3532328 214415.3


问:
how I can set rules in firebase without Auth users
hi i'm working with angular and firebase, in a web app, if i open the browser tools on console, i can see the connection keys to my firebase it's very bad.

the rules in firebase is the solution at this problem. but all answers i found are based on auth of users and on my web app is not necesary auth. how i can set rules so that only my web app can read and write without users auth. because if i create another projec and i use the same keys i can map the database and anyone can update the data  thanks
p.d.  my rules actually are read=true and write=true, this allows anyone to read and write.

```<code>{
  "rules": {
    ".read": "true != null",
    ".write": "true != null"
  }
}
</code>```

P.d. my web app is hosted in Firebase Hosting thanks again

答: This is not possible with security rules.  If you don't restrict usage with Firebase Authentication, that means anyone with an internet connection can read and write your database.</p>

Body:
hi i'm working with angular and firebase, in a web app, if i open the browser tools on console, i can see the connection keys to my firebase it's very bad.

the rules in firebase is the solution at this problem. but all answers i found are based on auth of users and on my web app is not necesary auth. how i can set rules so that only my web app can read and write without users auth. because if i create another projec and i use the same keys i can map the database and anyone can update the data  thanks
p.d.  my rules actually are read=true and write=true, this allows anyone to read and write.

{
  "rules": {
    ".read": "true != null",
    ".write": "true != null"
  }
}

P.d. my web app is hosted in Firebase Hosting thanks again


问:
Firefox is adding horizontal spacing between  tags
Ok, so this might be a stupid question, but I'm trying to make a 3-column table, but Firefox is adding a 1-2 pixel space between all the  columns. The table looks fine in Chrome. How can I eliminate this extra spacing? I'm not able to see these spaces when I inspect it with dev tools.

```

I'm developing this for some email marketing, so I'm not able to use any kind of JavaScript and any advanced CSS is basically a no-go, since I need to account for a broad range of email clients. This is also why I'm not using DIVs to do the layout.

The result that I'm looking for is to have all the  columns appear on a single line within the  instead of wrapping to multiple lines.

答:
What you are seeing is whitespace due to you setting td { display: inline-block; }. If you really need that, a way to solve it is to set the parent element's font-size: 0;:

```

Remember to set the font-size you actually need for any text you might have inside the table on the td elements.

Title: Firefox is adding horizontal spacing between <td> tags

Body:
Ok, so this might be a stupid question, but I'm trying to make a 3-column table, but Firefox is adding a 1-2 pixel space between all the  columns. The table looks fine in Chrome. How can I eliminate this extra spacing? I'm not able to see these spaces when I inspect it with dev tools.

I'm developing this for some email marketing, so I'm not able to use any kind of JavaScript and any advanced CSS is basically a no-go, since I need to account for a broad range of email clients. This is also why I'm not using DIVs to do the layout.

The result that I'm looking for is to have all the  columns appear on a single line within the  instead of wrapping to multiple lines.

Body:
What you are seeing is whitespace due to you setting td { display: inline-block; }. If you really need that, a way to solve it is to set the parent element's font-size: 0;:

<table role="presentation" align="center" cellpadding="0" cellspacing="0" width="100%" bgcolor="#F1F1F1" style="background:#F1F1F1; max-width:640px; border-spacing:-1; border-collapse:collapse; text-align:center;">
  <tr style="font-size: 0;">
    <td style="display:inline-block; vertical-align:top; min-width:120px; width:33.33%;">
      <img id="IMG-small" src="https://picsum.photos/640/300?random=1" alt="" width="213" style="display:block;width:100%;height:auto;max-width:480px;margin:0 auto;" border="0">
    </td>
    <td style="display:inline-block; vertical-align:top; min-width:120px; width:33.33%;">
      <img id="IMG-small" src="https://picsum.photos/640/300?random=2" alt="" width="213" style="display:block;width:100%;height:auto;max-width:480px;margin:0 auto;" border="0">
    </td>
    <td style="display:inline-block; vertical-align:top; min-width:120px; width:33.33%;">
      <img id="IMG-small" src="https://picsum.photos/640/300?random=3" alt="" width="213" style="display:block;width:100%;height:auto;max-width:480px;margin:0 auto;" border="0">
    </td>
  </tr>
</table>

Remember to set the font-size you actually need for any text you might have inside the table on the td elements.


问:
Custom PHP Errors for AJAX calls
I'm building a web application, and am wondering how to handle errors with my AJAX calls.  For instance, if the user enters some sort of data that is invalid (bad email address, user already exists) I want to be able to throw an error from PHP.

I've seen here http://php4every1.com/tutorials/jquery-ajax-tutorial/ that you could just use a JSON object and handle the error report from JQuery's Success function, but that doesn't seem like the right way to do it. It would make sense to me that jQuery's error function should be utilized when there is an error. I guess I'm a stickler for that kind of thing.

Here's how I'm doing it right now.

```<code>//In my PHP file called from JQuery
function error($msg) {
    header("HTTP/1.0 555 ".$msg);
    die();
}
//Then that error is handled accordingly from JQuery
</code>```

So I'm creating an error code of 555—which is not defined as anything—and tacking on my own custom error message. Is that the right way to do this? Should I just use JSON? There's gotta be a standard way to send out error messages like this, right?

If you need to see more of my code to get a better idea, the whole project is up on github: https://github.com/josephwegner/fileDrop. The file in question is config/phpFuncts.php.

答:
I hate using HTTP status codes for indicating failures. The HTTP codes should be reserved for actual HTTP-level errors, and errors related to the AJAX request should be sent back via a JSON structure.

e.g.

```<code>$data = array()
if (some big ugly computation fails) {
   $data['errorcode'] = -123;
   $data['error'] = true;
   $data['success'] = false;
   $data['errormessage'] = 'some helpful error message';
} else {
   $data['success'] = true;
   $data['error'] = false;
   $data['response'] = 'whatever you wanted to send back....';
}
echo json_encode($data);
</code>```

Then on the client-side

```<code>if (data.error) {
   alert('Request blew up: ' + data.errormessage);
}
</code>```

Title: Custom PHP Errors for AJAX calls

Body:
I'm building a web application, and am wondering how to handle errors with my AJAX calls.  For instance, if the user enters some sort of data that is invalid (bad email address, user already exists) I want to be able to throw an error from PHP.

I've seen here http://php4every1.com/tutorials/jquery-ajax-tutorial/ that you could just use a JSON object and handle the error report from JQuery's Success function, but that doesn't seem like the right way to do it. It would make sense to me that jQuery's error function should be utilized when there is an error. I guess I'm a stickler for that kind of thing.

Here's how I'm doing it right now.

//In my PHP file called from JQuery
function error($msg) {
    header("HTTP/1.0 555 ".$msg);
    die();
}
//Then that error is handled accordingly from JQuery

So I'm creating an error code of 555—which is not defined as anything—and tacking on my own custom error message. Is that the right way to do this? Should I just use JSON? There's gotta be a standard way to send out error messages like this, right?

If you need to see more of my code to get a better idea, the whole project is up on github: https://github.com/josephwegner/fileDrop. The file in question is config/phpFuncts.php.

Body:
I hate using HTTP status codes for indicating failures. The HTTP codes should be reserved for actual HTTP-level errors, and errors related to the AJAX request should be sent back via a JSON structure.

e.g.

$data = array()
if (some big ugly computation fails) {
   $data['errorcode'] = -123;
   $data['error'] = true;
   $data['success'] = false;
   $data['errormessage'] = 'some helpful error message';
} else {
   $data['success'] = true;
   $data['error'] = false;
   $data['response'] = 'whatever you wanted to send back....';
}
echo json_encode($data);

Then on the client-side

if (data.error) {
   alert('Request blew up: ' + data.errormessage);
}


问:
Directive Two Way Binding with ng-repeat is not binding back to the model
In the below code, I've bound the array data $scope.data.arraydata to the custom section mysection.

And, for each arraydata I am binding the textbox with some keys for that array.

e.g. var1, var2

Also on adding multiple sections, the above is working fine.

But when I try to get the scope data with the below, the arraydata inside $scope.data is not binding back with the values var1 and var2

```<code>angular.element(document.getElementById('form')).scope().data
</code>```

e.g. Expected Output (on adding 2 sections)

```<code>{
   "test":"Single Data",
   "arraydata":[
      [
         {
            "var1":"aaa",
            "var2":"bbb"
         }
      ],
      [
         {
            "var1":"ccc",
            "var2":"ddd"
         }
      ]
   ]
}
</code>```

var app = angular.module('myApp', []);

        app.controller('myCtrl', function ($scope) {

            $scope.data = {

                "test": "Single Data",
                "arraydata": []
            }

            $scope.addSection = function () {

                $scope.data.arraydata.push([]);

            }

            $scope.addSection();
        });

        app.directive('mysection', function () {

            return {
                restrict: 'E',
                scope: {
                    arrdata: "=?"
                },
                template: $("#SectionTemplate").html()
            }

        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<body id="form" ng-app="myApp" ng-controller="myCtrl">

    <div>
        {{data}}
    </div>
    <div>
        {{ arrdata }}
    </div>
    <div>
        <mysection ng-repeat="arrdata in data.arraydata" ng-model="arrdata"></mysection>
    </div>

    <button type="button" ng-click="addSection()">Add Section</button>
</body>

    <script type="text/ng-template" id="SectionTemplate">
        <div style="border: solid 1px red">
            {{ arrdata }}
            <input type="text" ng-model="arrdata.var1" />
            <input type="text" ng-model="arrdata.var2" />
        </div>
    </script></code>```

答:
I think I see two things in the code:

NgModel is not relevant here. Instead, the directive is expecting arrdata input binding attribute.

The push method is pusing an array, and the directive is expecting an object.

Example:

var app = angular.module('myApp', []);

        app.controller('myCtrl', function ($scope) {

            $scope.data = {

                "test": "Single Data",
                "arraydata": []
            }

            $scope.addSection = function () {

                $scope.data.arraydata.push({});

            }

            $scope.addSection();
        });

        app.directive('mysection', function () {

            return {
                restrict: 'E',
                scope: {
                    arrdata: "=?"
                },
                template: $("#SectionTemplate").html()
            }

        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<body id="form" ng-app="myApp" ng-controller="myCtrl">

    <div>
        {{data}}
    </div>
    <div>
        {{ arrdata }}
    </div>
    <div>
        <mysection ng-repeat="arrdata in data.arraydata" arrdata="arrdata"></mysection>
    </div>

    <button type="button" ng-click="addSection()">Add Section</button>
</body>

    <script type="text/ng-template" id="SectionTemplate">
        <div style="border: solid 1px red">
            {{ arrdata }}
            <input type="text" ng-model="arrdata.var1" />
            <input type="text" ng-model="arrdata.var2" />
        </div>
    </script></code>```

Body:
In the below code, I've bound the array data $scope.data.arraydata to the custom section mysection.

And, for each arraydata I am binding the textbox with some keys for that array.

e.g. var1, var2

Also on adding multiple sections, the above is working fine.

But when I try to get the scope data with the below, the arraydata inside $scope.data is not binding back with the values var1 and var2

angular.element(document.getElementById('form')).scope().data

e.g. Expected Output (on adding 2 sections)

{
   "test":"Single Data",
   "arraydata":[
      [
         {
            "var1":"aaa",
            "var2":"bbb"
         }
      ],
      [
         {
            "var1":"ccc",
            "var2":"ddd"
         }
      ]
   ]
}

var app = angular.module('myApp', []);

        app.controller('myCtrl', function ($scope) {

            $scope.data = {

                "test": "Single Data",
                "arraydata": []
            }

            $scope.addSection = function () {

                $scope.data.arraydata.push([]);

            }

            $scope.addSection();
        });

        app.directive('mysection', function () {

            return {
                restrict: 'E',
                scope: {
                    arrdata: "=?"
                },
                template: $("#SectionTemplate").html()
            }

        });

        {{data}}

        {{ arrdata }}

        <mysection ng-repeat="arrdata in data.arraydata" ng-model="arrdata"></mysection>

    <button type="button" ng-click="addSection()">Add Section</button>

Body:
I think I see two things in the code:

NgModel is not relevant here. Instead, the directive is expecting arrdata input binding attribute.

The push method is pusing an array, and the directive is expecting an object.

Example:

var app = angular.module('myApp', []);

        app.controller('myCtrl', function ($scope) {

            $scope.data = {

                "test": "Single Data",
                "arraydata": []
            }

            $scope.addSection = function () {

                $scope.data.arraydata.push({});

            }

            $scope.addSection();
        });

        app.directive('mysection', function () {

            return {
                restrict: 'E',
                scope: {
                    arrdata: "=?"
                },
                template: $("#SectionTemplate").html()
            }

        });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<body id="form" ng-app="myApp" ng-controller="myCtrl">

    <div>
        {{data}}
    </div>
    <div>
        {{ arrdata }}
    </div>
    <div>
        <mysection ng-repeat="arrdata in data.arraydata" arrdata="arrdata"></mysection>
    </div>

    <button type="button" ng-click="addSection()">Add Section</button>
</body>

    <script type="text/ng-template" id="SectionTemplate">
        <div style="border: solid 1px red">
            {{ arrdata }}
            <input type="text" ng-model="arrdata.var1" />
            <input type="text" ng-model="arrdata.var2" />
        </div>
    </script>


问:
What is the best way to read config values for a python program? Is referring to an Enum class defined in another file common?
For example, I might try the following config:

```<code>class Defaults(Enum):
    a = 1
    b = 2
</code>```

Then from my main file, I can refer to it with:

```<code>import myconfig
windowSize = Defaults.a
</code>```

This would allow me to change the enum values whenever I want to vary how my program runs. Is this a common way to use Enums in python configuration?

答:
I think you're asking whether it's common to hold the configuration settings as members of an enumeration. As a more explicit example:

```<code>class Defaults(Enum):
    window_width = 600
    window_height = 480
    font_size = 14
</code>```

Technically, I think that would work, but what benefit is the enumeration providing? Enum is useful for providing choices to pick from. If you really want to do this, I think a plain class, a data class, or just module-level variables would be less confusing. Django's settings.py configuration file seems to be the closest thing to your idea that I've seen in common use.

Your broader question is how to read configuration values for a Python program. Personally, I like the style recommended by The Twelve-Factor App.

The twelve-factor app stores config in environment variables (often shortened to env vars or env). Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard.

The most flexible way I've found is to use the argparse module, and use the environment variables as the defaults. That way, you can override the environment variables on the command line. Be careful about putting passwords on the command line, though, because other users can probably see your command line arguments in the process list.

Here's an example that uses argparse and environment variables:

```<code>def parse_args(argv=None):
    parser = ArgumentParser(description='Watch the raw data folder for new runs.',
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        '--kive_server',
        default=os.environ.get('MICALL_KIVE_SERVER', 'http://localhost:8000'),
        help='server to send runs to')
    parser.add_argument(
        '--kive_user',
        default=os.environ.get('MICALL_KIVE_USER', 'kive'),
        help='user name for Kive server')
    parser.add_argument(
        '--kive_password',
        default=SUPPRESS,
        help='password for Kive server (default not shown)')

    args = parser.parse_args(argv)
    if not hasattr(args, 'kive_password'):
        args.kive_password = os.environ.get('MICALL_KIVE_PASSWORD', 'kive')
    return args
</code>```

Setting those environment variables can be a bit confusing, particularly for system services. If you're using systemd, look at the service unit, and be careful to use EnvironmentFile instead of Environment for any secrets. Environment values can be viewed by any user with systemctl show.

I usually make the default values useful for a developer running on their workstation, so they can start development without changing any configuration.

If you do want to put the configuration settings in a settings.py file, just be careful not to commit that file to source control. I have often committed a settings_template.py file that users can copy.

Body:
For example, I might try the following config:

class Defaults(Enum):
    a = 1
    b = 2

Then from my main file, I can refer to it with:

import myconfig
windowSize = Defaults.a

This would allow me to change the enum values whenever I want to vary how my program runs. Is this a common way to use Enums in python configuration?

Body:
I think you're asking whether it's common to hold the configuration settings as members of an enumeration. As a more explicit example:

class Defaults(Enum):
    window_width = 600
    window_height = 480
    font_size = 14

Technically, I think that would work, but what benefit is the enumeration providing? Enum is useful for providing choices to pick from. If you really want to do this, I think a plain class, a data class, or just module-level variables would be less confusing. Django's settings.py configuration file seems to be the closest thing to your idea that I've seen in common use.

Your broader question is how to read configuration values for a Python program. Personally, I like the style recommended by The Twelve-Factor App.

The twelve-factor app stores config in environment variables (often shortened to env vars or env). Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard.

The most flexible way I've found is to use the argparse module, and use the environment variables as the defaults. That way, you can override the environment variables on the command line. Be careful about putting passwords on the command line, though, because other users can probably see your command line arguments in the process list.

Here's an example that uses argparse and environment variables:

def parse_args(argv=None):
    parser = ArgumentParser(description='Watch the raw data folder for new runs.',
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        '--kive_server',
        default=os.environ.get('MICALL_KIVE_SERVER', 'http://localhost:8000'),
        help='server to send runs to')
    parser.add_argument(
        '--kive_user',
        default=os.environ.get('MICALL_KIVE_USER', 'kive'),
        help='user name for Kive server')
    parser.add_argument(
        '--kive_password',
        default=SUPPRESS,
        help='password for Kive server (default not shown)')

    args = parser.parse_args(argv)
    if not hasattr(args, 'kive_password'):
        args.kive_password = os.environ.get('MICALL_KIVE_PASSWORD', 'kive')
    return args

Setting those environment variables can be a bit confusing, particularly for system services. If you're using systemd, look at the service unit, and be careful to use EnvironmentFile instead of Environment for any secrets. Environment values can be viewed by any user with systemctl show.

I usually make the default values useful for a developer running on their workstation, so they can start development without changing any configuration.

If you do want to put the configuration settings in a settings.py file, just be careful not to commit that file to source control. I have often committed a settings_template.py file that users can copy.


问:
Flutter error: type '_Smi' is not a subtype of type 'double'
I developed a app using flutter 1.0. The app works well on most android and ios phones. But I found there one android phone and one iphone can not open that app, just show the error message "type '_Smi' is not a subtype of type 'double'". Is there someone can tell me what's going on my app.

Error picture when open the flutter app:

答:
It's hard to tell without the relevant piece of code, but in my case, this happened when trying to assign a double value from a Map. The solution was simply to call .toDouble on the value:

// myMap is a Map<String, dynamic>
double myDouble = myMap['mykey'].toDouble();
```

It used to work without the .toDouble(), but the _Smi error started happening one day.

Body:
It's hard to tell without the relevant piece of code, but in my case, this happened when trying to assign a double value from a Map. The solution was simply to call .toDouble on the value:

// myMap is a Map<String, dynamic>
double myDouble = myMap['mykey'].toDouble();

It used to work without the .toDouble(), but the _Smi error started happening one day.


问:
Creating a couchdb view to index if item in an array exists
I have the following sample documents in my couchdb. The original table in production has about 2M records.

```<code>{
  {
      "_id": "someid|goes|here",
      "collected": {
          "tags": ["abc", "def", "ghi"]
      }
  },
  {
      "_id": "someid1|goes|here",
      "collected": {
           "tags": ["abc", "klm","pqr"]
      },
  },
  {
      "_id": "someid2|goes|here",
      "collected": {
           "tags": ["efg", "hij","klm"]
      },
  }
}
</code>```

Based on my previous question here, how to search for values when the selector is an array,
I currently have an index added for the collected.tags field, but the search is still taking a long time. Here is the search query I have.

```<code>{
  "selector": {
    "collected.tags": {
      "$elemMatch": {
        "$regex": "abc"
      }
    }
  }
}
</code>```

There are about 300k records matching the above condition, there search seems to take a long time. So, I want to create a indexed view to retrieve and lookup faster instead of a find/search. I am new to couchdb and am not sure how to setup the map function to create the indexed view.

答:
Figured the map function out myself. Now all the documents are indexed and retrievals are faster</p>

```<code>function (doc) {
  if(doc.collected.tags.indexOf('abc') > -1){
    emit(doc._id, doc);
  }
}
</code>```

Body:
I have the following sample documents in my couchdb. The original table in production has about 2M records.

{
  {
      "_id": "someid|goes|here",
      "collected": {
          "tags": ["abc", "def", "ghi"]
      }
  },
  {
      "_id": "someid1|goes|here",
      "collected": {
           "tags": ["abc", "klm","pqr"]
      },
  },
  {
      "_id": "someid2|goes|here",
      "collected": {
           "tags": ["efg", "hij","klm"]
      },
  }
}

Based on my previous question here, how to search for values when the selector is an array,
I currently have an index added for the collected.tags field, but the search is still taking a long time. Here is the search query I have.

{
  "selector": {
    "collected.tags": {
      "$elemMatch": {
        "$regex": "abc"
      }
    }
  }
}

There are about 300k records matching the above condition, there search seems to take a long time. So, I want to create a indexed view to retrieve and lookup faster instead of a find/search. I am new to couchdb and am not sure how to setup the map function to create the indexed view.

Body:
Figured the map function out myself. Now all the documents are indexed and retrievals are faster

function (doc) {
  if(doc.collected.tags.indexOf('abc') > -1){
    emit(doc._id, doc);
  }
}


问:
focusing ng-select filter input on drop down open
I'm using ng-select and have a custom filter header template defined which contains an input.

I would like the input to receive focus when the dropdown is opened for the select, but I cant figure out how to.

I have an example here -> https://stackblitz.com/edit/angular-playground-f57jog

I did try attaching to the ng-select (open) output and calling focus() on my input element, but this fails for me.

Whats the correct approach here?
Thanks

答:
Just use ViewChildren and susbcribe to changes, then focus. That's.

```<code>@ViewChildren('filterInput') filterInput : QueryList<ElementRef>;

onOpen()
{
  this.filterInput.changes.subscribe(res=>{
      this.filterInput.first.nativeElement.focus()
  })
}
</code>```

And in your .html

```<code><ng-select ...  (open)="onOpen()"></ng-select>
</code>```

See your forked stackblitz

Body:
Just use ViewChildren and susbcribe to changes, then focus. That's.

@ViewChildren('filterInput') filterInput : QueryList<ElementRef>;

onOpen()
{
  this.filterInput.changes.subscribe(res=>{
      this.filterInput.first.nativeElement.focus()
  })
}

And in your .html

<ng-select ...  (open)="onOpen()"></ng-select>

See your forked stackblitz


问:
Docker&Celery - ERROR: Pidfile (celerybeat.pid) already exists
Application consists of:
- Django
- Redis
- Celery
- Docker
- Postgres

Before merging the project into docker, everything was working smooth and fine, but once it has been moved into containers, something wrong started to happen.
At first it starts perfectly fine, but after a while I do receive folowing error:

```<code>celery-beat_1  | ERROR: Pidfile (celerybeat.pid) already exists.
</code>```

I've been struggling with it for a while, but right now I literally give up. I've no idea of what is wrong with it.

Dockerfile:

```<code>FROM python:3.7

ENV PYTHONUNBUFFERED 1
RUN mkdir -p /opt/services/djangoapp/src

COPY /scripts/startup/entrypoint.sh entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

COPY Pipfile Pipfile.lock /opt/services/djangoapp/src/
WORKDIR /opt/services/djangoapp/src
RUN pip install pipenv && pipenv install --system

COPY . /opt/services/djangoapp/src

RUN find . -type f -name "celerybeat.pid" -exec rm -f {} \;

RUN sed -i "s|django.core.urlresolvers|django.urls |g" /usr/local/lib/python3.7/site-packages/vanilla/views.py
RUN cp /usr/local/lib/python3.7/site-packages/celery/backends/async.py /usr/local/lib/python3.7/site-packages/celery/backends/asynchronous.py
RUN rm /usr/local/lib/python3.7/site-packages/celery/backends/async.py
RUN sed -i "s|async|asynchronous|g" /usr/local/lib/python3.7/site-packages/celery/backends/redis.py
RUN sed -i "s|async|asynchronous|g" /usr/local/lib/python3.7/site-packages/celery/backends/rpc.py

RUN cd app && python manage.py collectstatic --no-input

EXPOSE 8000
CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "app", "example.wsgi:application", "--reload"]
</code>```

docker-compose.yml:

```<code>version: '3'

services:

  djangoapp:
    build: .
    volumes:
      - .:/opt/services/djangoapp/src
      - static_volume:/opt/services/djangoapp/static  # <-- bind the static volume
      - media_volume:/opt/services/djangoapp/media  # <-- bind the media volume
      - static_local_volume:/opt/services/djangoapp/src/app/static
      - media_local_volume:/opt/services/djangoapp/src/app/media
      - .:/code
    restart: always
    networks:
      - nginx_network
      - database1_network # comment when testing
      # - test_database1_network # uncomment when testing
      - redis_network
    depends_on:
      - database1 # comment when testing
      # - test_database1 # uncomment when testing
      - migration
      - redis

  # base redis server
  redis:
    image: "redis:alpine"
    restart: always
    ports:
      - "6379:6379"
    networks:
      - redis_network
    volumes:
      - redis_data:/data

  # celery worker
  celery:
    build: .
    command: >
      bash -c "cd app && celery -A example worker --without-gossip --without-mingle --without-heartbeat -Ofair"
    volumes:
      - .:/opt/services/djangoapp/src
      - static_volume:/opt/services/djangoapp/static  # <-- bind the static volume
      - media_volume:/opt/services/djangoapp/media  # <-- bind the media volume
      - static_local_volume:/opt/services/djangoapp/src/app/static
      - media_local_volume:/opt/services/djangoapp/src/app/media
    networks:
      - redis_network
      - database1_network # comment when testing
      # - test_database1_network # uncomment when testing
    restart: always
    depends_on:
      - database1 # comment when testing
      # - test_database1 # uncomment when testing
      - redis
    links:
      - redis

  celery-beat:
    build: .
    command: >
      bash -c "cd app && celery -A example beat"
    volumes:
      - .:/opt/services/djangoapp/src
      - static_volume:/opt/services/djangoapp/static  # <-- bind the static volume
      - media_volume:/opt/services/djangoapp/media  # <-- bind the media volume
      - static_local_volume:/opt/services/djangoapp/src/app/static
      - media_local_volume:/opt/services/djangoapp/src/app/media
    networks:
      - redis_network
      - database1_network # comment when testing
      # - test_database1_network # uncomment when testing
    restart: always
    depends_on:
      - database1 # comment when testing
      # - test_database1 # uncomment when testing
      - redis
    links:
      - redis

  # migrations needed for proper db functioning
  migration:
    build: .
    command: >
      bash -c "cd app && python3 manage.py makemigrations && python3 manage.py migrate"
    depends_on:
      - database1 # comment when testing
      # - test_database1 # uncomment when testing
    networks:
     - database1_network # comment when testing
     # - test_database1_network # uncomment when testing

  # reverse proxy container (nginx)
  nginx:
    image: nginx:1.13
    ports:
      - 80:80
    volumes:
      - ./config/nginx/conf.d:/etc/nginx/conf.d
      - static_volume:/opt/services/djangoapp/static  # <-- bind the static volume
      - media_volume:/opt/services/djangoapp/media  # <-- bind the media volume
      - static_local_volume:/opt/services/djangoapp/src/app/static
      - media_local_volume:/opt/services/djangoapp/src/app/media
    restart: always
    depends_on:
      - djangoapp
    networks:
      - nginx_network

  database1: # comment when testing
    image: postgres:10 # comment when testing
    env_file: # comment when testing
      - config/db/database1_env # comment when testing
    networks: # comment when testing
      - database1_network # comment when testing
    volumes: # comment when testing
      - database1_volume:/var/lib/postgresql/data # comment when testing

  # test_database1: # uncomment when testing
    # image: postgres:10 # uncomment when testing
    # env_file: # uncomment when testing
      # - config/db/test_database1_env # uncomment when testing
    # networks: # uncomment when testing
      # - test_database1_network # uncomment when testing
    # volumes: # uncomment when testing
      # - test_database1_volume:/var/lib/postgresql/data # uncomment when testing

networks:
  nginx_network:
    driver: bridge
  database1_network: # comment when testing
    driver: bridge # comment when testing
  # test_database1_network: # uncomment when testing
    # driver: bridge # uncomment when testing
  redis_network:
    driver: bridge
volumes:
  database1_volume: # comment when testing
  # test_database1_volume: # uncomment when testing
  static_volume:  # <-- declare the static volume
  media_volume:  # <-- declare the media volume
  static_local_volume:
  media_local_volume:
  redis_data:
</code>```

Please, ignore "test_database1_volume" as it exists only for test purposes.

答: Another solution (taken from https://stackoverflow.com/a/17674248/39296) is to use --pidfile= (with no path) to not create a pidfile at all.  Same effect as Siyu's answer above.</p>

Body:
Application consists of:
- Django
- Redis
- Celery
- Docker
- Postgres

Before merging the project into docker, everything was working smooth and fine, but once it has been moved into containers, something wrong started to happen.
At first it starts perfectly fine, but after a while I do receive folowing error:

celery-beat_1  | ERROR: Pidfile (celerybeat.pid) already exists.

I've been struggling with it for a while, but right now I literally give up. I've no idea of what is wrong with it.

Dockerfile:

FROM python:3.7

ENV PYTHONUNBUFFERED 1
RUN mkdir -p /opt/services/djangoapp/src

COPY /scripts/startup/entrypoint.sh entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

COPY Pipfile Pipfile.lock /opt/services/djangoapp/src/
WORKDIR /opt/services/djangoapp/src
RUN pip install pipenv && pipenv install --system

COPY . /opt/services/djangoapp/src

RUN find . -type f -name "celerybeat.pid" -exec rm -f {} \;

RUN sed -i "s|django.core.urlresolvers|django.urls |g" /usr/local/lib/python3.7/site-packages/vanilla/views.py
RUN cp /usr/local/lib/python3.7/site-packages/celery/backends/async.py /usr/local/lib/python3.7/site-packages/celery/backends/asynchronous.py
RUN rm /usr/local/lib/python3.7/site-packages/celery/backends/async.py
RUN sed -i "s|async|asynchronous|g" /usr/local/lib/python3.7/site-packages/celery/backends/redis.py
RUN sed -i "s|async|asynchronous|g" /usr/local/lib/python3.7/site-packages/celery/backends/rpc.py

RUN cd app && python manage.py collectstatic --no-input

EXPOSE 8000
CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "app", "example.wsgi:application", "--reload"]

docker-compose.yml:

version: '3'

services:

  djangoapp:
    build: .
    volumes:
      - .:/opt/services/djangoapp/src
      - static_volume:/opt/services/djangoapp/static  # <-- bind the static volume
      - media_volume:/opt/services/djangoapp/media  # <-- bind the media volume
      - static_local_volume:/opt/services/djangoapp/src/app/static
      - media_local_volume:/opt/services/djangoapp/src/app/media
      - .:/code
    restart: always
    networks:
      - nginx_network
      - database1_network # comment when testing
      # - test_database1_network # uncomment when testing
      - redis_network
    depends_on:
      - database1 # comment when testing
      # - test_database1 # uncomment when testing
      - migration
      - redis

  # base redis server
  redis:
    image: "redis:alpine"
    restart: always
    ports:
      - "6379:6379"
    networks:
      - redis_network
    volumes:
      - redis_data:/data

  # celery worker
  celery:
    build: .
    command: >
      bash -c "cd app && celery -A example worker --without-gossip --without-mingle --without-heartbeat -Ofair"
    volumes:
      - .:/opt/services/djangoapp/src
      - static_volume:/opt/services/djangoapp/static  # <-- bind the static volume
      - media_volume:/opt/services/djangoapp/media  # <-- bind the media volume
      - static_local_volume:/opt/services/djangoapp/src/app/static
      - media_local_volume:/opt/services/djangoapp/src/app/media
    networks:
      - redis_network
      - database1_network # comment when testing
      # - test_database1_network # uncomment when testing
    restart: always
    depends_on:
      - database1 # comment when testing
      # - test_database1 # uncomment when testing
      - redis
    links:
      - redis

  celery-beat:
    build: .
    command: >
      bash -c "cd app && celery -A example beat"
    volumes:
      - .:/opt/services/djangoapp/src
      - static_volume:/opt/services/djangoapp/static  # <-- bind the static volume
      - media_volume:/opt/services/djangoapp/media  # <-- bind the media volume
      - static_local_volume:/opt/services/djangoapp/src/app/static
      - media_local_volume:/opt/services/djangoapp/src/app/media
    networks:
      - redis_network
      - database1_network # comment when testing
      # - test_database1_network # uncomment when testing
    restart: always
    depends_on:
      - database1 # comment when testing
      # - test_database1 # uncomment when testing
      - redis
    links:
      - redis

  # migrations needed for proper db functioning
  migration:
    build: .
    command: >
      bash -c "cd app && python3 manage.py makemigrations && python3 manage.py migrate"
    depends_on:
      - database1 # comment when testing
      # - test_database1 # uncomment when testing
    networks:
     - database1_network # comment when testing
     # - test_database1_network # uncomment when testing

  # reverse proxy container (nginx)
  nginx:
    image: nginx:1.13
    ports:
      - 80:80
    volumes:
      - ./config/nginx/conf.d:/etc/nginx/conf.d
      - static_volume:/opt/services/djangoapp/static  # <-- bind the static volume
      - media_volume:/opt/services/djangoapp/media  # <-- bind the media volume
      - static_local_volume:/opt/services/djangoapp/src/app/static
      - media_local_volume:/opt/services/djangoapp/src/app/media
    restart: always
    depends_on:
      - djangoapp
    networks:
      - nginx_network

  database1: # comment when testing
    image: postgres:10 # comment when testing
    env_file: # comment when testing
      - config/db/database1_env # comment when testing
    networks: # comment when testing
      - database1_network # comment when testing
    volumes: # comment when testing
      - database1_volume:/var/lib/postgresql/data # comment when testing

  # test_database1: # uncomment when testing
    # image: postgres:10 # uncomment when testing
    # env_file: # uncomment when testing
      # - config/db/test_database1_env # uncomment when testing
    # networks: # uncomment when testing
      # - test_database1_network # uncomment when testing
    # volumes: # uncomment when testing
      # - test_database1_volume:/var/lib/postgresql/data # uncomment when testing

networks:
  nginx_network:
    driver: bridge
  database1_network: # comment when testing
    driver: bridge # comment when testing
  # test_database1_network: # uncomment when testing
    # driver: bridge # uncomment when testing
  redis_network:
    driver: bridge
volumes:
  database1_volume: # comment when testing
  # test_database1_volume: # uncomment when testing
  static_volume:  # <-- declare the static volume
  media_volume:  # <-- declare the media volume
  static_local_volume:
  media_local_volume:
  redis_data:

Please, ignore "test_database1_volume" as it exists only for test purposes.


问:
Reading / Writing files in Javascript - IE6
I need a database storage system for Javascript where the state can be maintained on the local disk.

Here comes the spanners in the works :-

It only needs to support Internet Explorer but the minimum version must be IE6

Files need to be written so they can be read in again later (upon closing and re-opening of browser)

There can be no web server (unless it's extremely easy to distribute and does not require a install) since the HTML pages will be distributed on USB.

Does anyone know of any solutions that might help here?

答:
try to read this post: Read/write to file using jQuery

Hope this helps.


问:
Proxyquire equivalent in Python3 unittest
I am testing a script that looks something like this:

```<code>import arcpy

Class A:
    function go(x, y, z):
        arcpy.dothing(y,x,z['attr'])
</code>```

I want to write a unit test in python 3.6.6 that passes in dummy params and verifies that they are correctly transformed and passed to the arcpy.dothing method. I have used proxyquire in node for this but in python I can't figure this out. In particular the @patch doesn't seem to allow for capturing input arguments.

答:
So I figured this out after a lot of experimenting. Here is what I ended up with:</p>

```<code>import unittest
from a import A
from unittest.mock import patch

class Test_ATest(unittest.TestCase):
    @patch('a.arcpy.dothing')
    def test_dothing(self, dothing):
        d = {"attr": "c"}
        obj = A()
        obj._go(1,2,d)

        dothing.assert_called_with(2,1,'c')
</code>```

Body:
I am testing a script that looks something like this:

import arcpy

Class A:
    function go(x, y, z):
        arcpy.dothing(y,x,z['attr'])

I want to write a unit test in python 3.6.6 that passes in dummy params and verifies that they are correctly transformed and passed to the arcpy.dothing method. I have used proxyquire in node for this but in python I can't figure this out. In particular the @patch doesn't seem to allow for capturing input arguments.

Body:
So I figured this out after a lot of experimenting. Here is what I ended up with:

import unittest
from a import A
from unittest.mock import patch

class Test_ATest(unittest.TestCase):
    @patch('a.arcpy.dothing')
    def test_dothing(self, dothing):
        d = {"attr": "c"}
        obj = A()
        obj._go(1,2,d)

        dothing.assert_called_with(2,1,'c')


问:
jQuery autocomplete adding additional data with autocompleted data
I have an input field (text) that I want to perform autocomplete on with multiple names. It acts like the To: field in Gmail, with the user typing in a name and hitting enter and continuing. The problem is that I have a list of names and that's what gets added to the input field and once you submit, as far as I know, only the field string gets sent to the server. The problem is when there are two people with the same name, so: John Smith, Bob, John Smith might be inputted and that string will get sent to the server.

On the backend, all users have a unique id. Is there any way I can have the users' names be the autocomplete source but have their ids sent to the server?

I'm using jQuery 1.5.1 and this plugin: jQuery UI Autocomplete

答:
Use the select event in Jquery UI autocomplete to trigger javascript that will store the IDs you need in a hidden field in the same form.  See the documentation for the select event here:

http://jqueryui.com/demos/autocomplete/#event-select


问:
kafka-connect-hdfs : SequenceFileWriter creates badfiles on connector restarts causing EOFException in the SequenceFileReader
In Kafka connect hdfs, we have the below SequenceFileWriter.java class to write kafka messages in SequenceFileFormat.

```<code>import java.io.IOException;

import io.confluent.connect.avro.AvroData;
import io.confluent.connect.hdfs.RecordWriter;
import io.confluent.connect.hdfs.RecordWriterProvider;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.kafka.connect.sink.SinkRecord;

/**
 * Provider of a Sequence File record writer.
 */
public class SequenceFileWriterProvider implements RecordWriterProvider
{
  public String getExtension() {
    return "";
  }

  @Override
  public RecordWriter<SinkRecord> getRecordWriter(Configuration conf, String fileName, SinkRecord record, AvroData avroData) throws IOException {
    Path path = new Path(fileName);

    final SequenceFile.Writer writer;
    SequenceFile.Writer.Option optPath = SequenceFile.Writer.file(path);
    SequenceFile.Writer.Option optKey = SequenceFile.Writer.keyClass(LongWritable.class);
    SequenceFile.Writer.Option optVal = SequenceFile.Writer.valueClass(Text.class);
    SequenceFile.Writer.Option optCodec = SequenceFile.Writer.compression(SequenceFile.CompressionType.BLOCK, new BZip2Codec());
    writer = SequenceFile.createWriter(conf, optPath, optKey, optVal, optCodec);

    return new RecordWriter<SinkRecord>() {
      @Override
      public void write(SinkRecord record) throws IOException {
        writer.append(
            new LongWritable(System.currentTimeMillis()),
            new Text((byte[]) record.value())
        );
      }

      @Override
      public void close() throws IOException {
        writer.close();
      }
    };
  }
}
</code>```

We run confluent 5.0.0 within docker container managed by kubernetes. We have observed that when we delete the replication controller in k8s running kafka connector and recreate the replication controller, some of the sequence files get corrupted. We have a spark job which reads this data using SequenceFileReader and receive a below EOFException. Also observed that the there are two extra bytes that appear at the end of file. We guess there is a problem with the SequenceFileWriter and need help in validating the Writer. Any help would be appreciated. Thanks.

```<code>java.io.EOFException
    at java.io.DataInputStream.readByte(DataInputStream.java:267)
    at org.apache.hadoop.io.WritableUtils.readVLong(WritableUtils.java:308)
    at org.apache.hadoop.io.WritableUtils.readVInt(WritableUtils.java:329)
    at org.apache.hadoop.io.SequenceFile$Reader.readBuffer(SequenceFile.java:2160)
    at org.apache.hadoop.io.SequenceFile$Reader.seekToCurrentValue(SequenceFile.java:2227)
    at org.apache.hadoop.io.SequenceFile$Reader.getCurrentValue(SequenceFile.java:2263)
    at org.apache.hadoop.io.SequenceFile$Reader.next(SequenceFile.java:2394)
    at badSequenceFile.readSequenceFile(badSequenceFile.java:27)
    at badSequenceFile.main(badSequenceFile.java:345)
</code>```

Note: When we delete the connector temporary files(+tmp) before starting the k8s replication controller, connector starts clean and donot create badfiles.

答:
Modifying the writer.append to handle exception looks to have fixed the issue of not writing bad sequence files with misplaced end of file (EOF) marker.
Additionally also performed type casting of the record value to String datatype from byte.

```<code>return new RecordWriter<SinkRecord>() {
  @Override
  public void write(SinkRecord record) {
      if (record != null) {
          byte[] text = (byte[]) record.value();
              try{
                  writer.append(
                          new LongWritable(System.currentTimeMillis()),
                          new Text(new String (text))
                  );

              } catch (Exception e) {
                  logger.error("Exception encounterd : "+e+" for text : "+text);
              }
          }
      }
  }

</code>```

Body:
In Kafka connect hdfs, we have the below SequenceFileWriter.java class to write kafka messages in SequenceFileFormat.

import java.io.IOException;

import io.confluent.connect.avro.AvroData;
import io.confluent.connect.hdfs.RecordWriter;
import io.confluent.connect.hdfs.RecordWriterProvider;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.kafka.connect.sink.SinkRecord;

/**
 * Provider of a Sequence File record writer.
 */
public class SequenceFileWriterProvider implements RecordWriterProvider
{
  public String getExtension() {
    return "";
  }

  @Override
  public RecordWriter<SinkRecord> getRecordWriter(Configuration conf, String fileName, SinkRecord record, AvroData avroData) throws IOException {
    Path path = new Path(fileName);

    final SequenceFile.Writer writer;
    SequenceFile.Writer.Option optPath = SequenceFile.Writer.file(path);
    SequenceFile.Writer.Option optKey = SequenceFile.Writer.keyClass(LongWritable.class);
    SequenceFile.Writer.Option optVal = SequenceFile.Writer.valueClass(Text.class);
    SequenceFile.Writer.Option optCodec = SequenceFile.Writer.compression(SequenceFile.CompressionType.BLOCK, new BZip2Codec());
    writer = SequenceFile.createWriter(conf, optPath, optKey, optVal, optCodec);

    return new RecordWriter<SinkRecord>() {
      @Override
      public void write(SinkRecord record) throws IOException {
        writer.append(
            new LongWritable(System.currentTimeMillis()),
            new Text((byte[]) record.value())
        );
      }

      @Override
      public void close() throws IOException {
        writer.close();
      }
    };
  }
}

We run confluent 5.0.0 within docker container managed by kubernetes. We have observed that when we delete the replication controller in k8s running kafka connector and recreate the replication controller, some of the sequence files get corrupted. We have a spark job which reads this data using SequenceFileReader and receive a below EOFException. Also observed that the there are two extra bytes that appear at the end of file. We guess there is a problem with the SequenceFileWriter and need help in validating the Writer. Any help would be appreciated. Thanks.

java.io.EOFException
    at java.io.DataInputStream.readByte(DataInputStream.java:267)
    at org.apache.hadoop.io.WritableUtils.readVLong(WritableUtils.java:308)
    at org.apache.hadoop.io.WritableUtils.readVInt(WritableUtils.java:329)
    at org.apache.hadoop.io.SequenceFile$Reader.readBuffer(SequenceFile.java:2160)
    at org.apache.hadoop.io.SequenceFile$Reader.seekToCurrentValue(SequenceFile.java:2227)
    at org.apache.hadoop.io.SequenceFile$Reader.getCurrentValue(SequenceFile.java:2263)
    at org.apache.hadoop.io.SequenceFile$Reader.next(SequenceFile.java:2394)
    at badSequenceFile.readSequenceFile(badSequenceFile.java:27)
    at badSequenceFile.main(badSequenceFile.java:345)

Note: When we delete the connector temporary files(+tmp) before starting the k8s replication controller, connector starts clean and donot create badfiles.

Body:
Modifying the writer.append to handle exception looks to have fixed the issue of not writing bad sequence files with misplaced end of file (EOF) marker.
Additionally also performed type casting of the record value to String datatype from byte.

return new RecordWriter<SinkRecord>() {
  @Override
  public void write(SinkRecord record) {
      if (record != null) {
          byte[] text = (byte[]) record.value();
              try{
                  writer.append(
                          new LongWritable(System.currentTimeMillis()),
                          new Text(new String (text))
                  );

              } catch (Exception e) {
                  logger.error("Exception encounterd : "+e+" for text : "+text);
              }
          }
      }
  }


问:
What is this "tool" and how to disable it?
I'm currently developing a program and I have this that shows up at the top of the window. I don't know what it is or how to remove it. I only have it in this specific program so I guess it's related to something I have done.

答:
This is normal when running a XAML window in Debug. It let's you debug the window.
If you build in release mode, you'll see that this disappears.

If you want to turn it off, uncheck this option in the settings Tools –> Options –> Debugging –> General –> Enable UI Debugging Tools for XAML.


问:
Image and text in HTML a tag where the image resizes to fit the container
I have a 482x482 image I want to use with a  container which is defined as follows:

```<code>    <nav id="nav">
        <ul class="links">
            <li><a href="/exchange/accueil">
                <img src="{% static 'exchange/images/HomeIconWhite.png' %}"></img>
            </a><p>Accueil</p></li>
            <li><a href="/exchange/recherche_avance">Recherche avancée</a></li>
            <li><a href="/exchange/rajouter">Ajouter une info</a></li>
            {% if user.is_authenticated %}
            <li><a href="/exchange/deconnexion">Déconnexion</a></li>
            {% else %}
            <li><a href="/exchange/connexion">Connexion</a></li>
            {% endif %}
        </ul>
    </nav>
</code>```

The CSS defining this container is the following:

```<code>    #nav {
        color: #ffffff;
        display: -moz-flex;
        display: -webkit-flex;
        display: -ms-flex;
        display: flex;
        -moz-transition: -moz-transform 1s ease, opacity 1s ease;
        -webkit-transition: -webkit-transform 1s ease, opacity 1s ease;
        -ms-transition: -ms-transform 1s ease, opacity 1s ease;
        transition: transform 1s ease, opacity 1s ease;
        background: rgba(255, 255, 255, 0.175);
        height: 4rem;
        line-height: 4rem;
        margin: -4rem auto 0 auto;
        overflow: hidden;
        padding: 0 2rem 0 0;
        position: relative;
        width: calc(100% - 4rem);
        max-width: 72rem;
        z-index: 2;
    }

        #nav ul.divided li {
            border-top-color: #ffffff;
        }

        #nav ul.icons li a.icon:hover:before {
            color: #18bfef;
        }

        #nav ul.icons.alt li .icon:before {
            box-shadow: inset 0 0 0 2px #ffffff;
        }

        #nav ul.icons.alt li a.icon:hover:before {
            box-shadow: inset 0 0 0 2px #18bfef;
        }

        #nav input, #nav select, #nav textarea {
            color: #ffffff;
        }

        #nav a {
            color: #ffffff;
            border-bottom-color: rgba(255, 255, 255, 0.5);
        }

            #nav a:hover {
                border-bottom-color: transparent;
                color: #18bfef !important;
            }

        #nav strong, #nav b {
            color: #ffffff;
        }

        #nav h1, #nav h2, #nav h3, #nav h4, #nav h5, #nav h6 {
            color: #ffffff;
        }

        #nav blockquote {
            border-left-color: #ffffff;
        }

        #nav code {
            background: rgba(255, 255, 255, 0.075);
            border-color: #ffffff;
        }

        #nav hr {
            border-bottom-color: #ffffff;
        }

        #nav ul.links {
            display: -moz-flex;
            display: -webkit-flex;
            display: -ms-flex;
            display: flex;
            -moz-flex-grow: 1;
            -webkit-flex-grow: 1;
            -ms-flex-grow: 1;
            flex-grow: 1;
            -moz-flex-shrink: 1;
            -webkit-flex-shrink: 1;
            -ms-flex-shrink: 1;
            flex-shrink: 1;
            font-family: "Source Sans Pro", Helvetica, sans-serif;
            font-weight: 900;
            letter-spacing: 0.075em;
            list-style: none;
            margin-bottom: 0;
            padding-left: 0;
            text-transform: uppercase;
        }

            #nav ul.links li {
                display: block;
                padding-left: 0;
            }

                #nav ul.links li a {
                    -moz-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
                    -webkit-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
                    -ms-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
                    transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
                    display: block;
                    font-size: 0.8rem;
                    outline: none;
                    padding: 0 2rem;
                }

                    #nav ul.links li a:hover {
                        color: inherit !important;
                        background-color: rgba(255, 255, 255, 0.1);
                    }

                #nav ul.links li.active {
                    background-color: #ffffff;
                }

                    #nav ul.links li.active a {
                        color: #1e252d;
                    }

                        #nav ul.links li.active a:hover {
                            color: #18bfef !important;
                        }

        #nav ul.icons {
            -moz-flex-grow: 0;
            -webkit-flex-grow: 0;
            -ms-flex-grow: 0;
            flex-grow: 0;
            -moz-flex-shrink: 0;
            -webkit-flex-shrink: 0;
            -ms-flex-shrink: 0;
            flex-shrink: 0;
            margin-bottom: 0;
        }

        @media screen and (max-width: 980px) {

            #nav {
                display: none;
            }

        }
</code>```

I've tried defining some rules within the css as #nav ul.links img but this didn't achieve my goals.

What I would like is that the image fit the nav container correctly, be centered within it and have some text next to it (also centered)

I'm pretty sure the way of doing this is obvious, but I haven't found any answers online that fit my problem, they all have variations that make them inapplicable to my issue.

Please tell me if you need more details. The link to the image works 100% so the issue doesn't come from this.

EDIT

Here is the Github link.

答:
```<code>#nav ul.links li:first-of-type a{
    display: flex
}
#nav ul.links li:first-of-type a p{
    margin-top: 0;
    margin-left: 5%
}
#logo{
    height: 4em;
    margin-top: 7px;
}
</code>```

Body:
I have a 482x482 image I want to use with a  container which is defined as follows:

Accueil

Recherche avancée

Ajouter une info

            {% if user.is_authenticated %}

Déconnexion

            {% else %}

Connexion

            {% endif %}

The CSS defining this container is the following:

    #nav {
        color: #ffffff;
        display: -moz-flex;
        display: -webkit-flex;
        display: -ms-flex;
        display: flex;
        -moz-transition: -moz-transform 1s ease, opacity 1s ease;
        -webkit-transition: -webkit-transform 1s ease, opacity 1s ease;
        -ms-transition: -ms-transform 1s ease, opacity 1s ease;
        transition: transform 1s ease, opacity 1s ease;
        background: rgba(255, 255, 255, 0.175);
        height: 4rem;
        line-height: 4rem;
        margin: -4rem auto 0 auto;
        overflow: hidden;
        padding: 0 2rem 0 0;
        position: relative;
        width: calc(100% - 4rem);
        max-width: 72rem;
        z-index: 2;
    }

        #nav ul.divided li {
            border-top-color: #ffffff;
        }

        #nav ul.icons li a.icon:hover:before {
            color: #18bfef;
        }

        #nav ul.icons.alt li .icon:before {
            box-shadow: inset 0 0 0 2px #ffffff;
        }

        #nav ul.icons.alt li a.icon:hover:before {
            box-shadow: inset 0 0 0 2px #18bfef;
        }

        #nav input, #nav select, #nav textarea {
            color: #ffffff;
        }

        #nav a {
            color: #ffffff;
            border-bottom-color: rgba(255, 255, 255, 0.5);
        }

            #nav a:hover {
                border-bottom-color: transparent;
                color: #18bfef !important;
            }

        #nav strong, #nav b {
            color: #ffffff;
        }

        #nav h1, #nav h2, #nav h3, #nav h4, #nav h5, #nav h6 {
            color: #ffffff;
        }

        #nav blockquote {
            border-left-color: #ffffff;
        }

        #nav code {
            background: rgba(255, 255, 255, 0.075);
            border-color: #ffffff;
        }

        #nav hr {
            border-bottom-color: #ffffff;
        }

        #nav ul.links {
            display: -moz-flex;
            display: -webkit-flex;
            display: -ms-flex;
            display: flex;
            -moz-flex-grow: 1;
            -webkit-flex-grow: 1;
            -ms-flex-grow: 1;
            flex-grow: 1;
            -moz-flex-shrink: 1;
            -webkit-flex-shrink: 1;
            -ms-flex-shrink: 1;
            flex-shrink: 1;
            font-family: "Source Sans Pro", Helvetica, sans-serif;
            font-weight: 900;
            letter-spacing: 0.075em;
            list-style: none;
            margin-bottom: 0;
            padding-left: 0;
            text-transform: uppercase;
        }

            #nav ul.links li {
                display: block;
                padding-left: 0;
            }

                #nav ul.links li a {
                    -moz-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
                    -webkit-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
                    -ms-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
                    transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
                    display: block;
                    font-size: 0.8rem;
                    outline: none;
                    padding: 0 2rem;
                }

                    #nav ul.links li a:hover {
                        color: inherit !important;
                        background-color: rgba(255, 255, 255, 0.1);
                    }

                #nav ul.links li.active {
                    background-color: #ffffff;
                }

                    #nav ul.links li.active a {
                        color: #1e252d;
                    }

                        #nav ul.links li.active a:hover {
                            color: #18bfef !important;
                        }

        #nav ul.icons {
            -moz-flex-grow: 0;
            -webkit-flex-grow: 0;
            -ms-flex-grow: 0;
            flex-grow: 0;
            -moz-flex-shrink: 0;
            -webkit-flex-shrink: 0;
            -ms-flex-shrink: 0;
            flex-shrink: 0;
            margin-bottom: 0;
        }

        @media screen and (max-width: 980px) {

            #nav {
                display: none;
            }

        }

I've tried defining some rules within the css as #nav ul.links img but this didn't achieve my goals.

What I would like is that the image fit the nav container correctly, be centered within it and have some text next to it (also centered)

I'm pretty sure the way of doing this is obvious, but I haven't found any answers online that fit my problem, they all have variations that make them inapplicable to my issue.

Please tell me if you need more details. The link to the image works 100% so the issue doesn't come from this.

EDIT

Here is the Github link.


问:
How to fillna() all columns of a dataframe from a single row of another dataframe with identical structure
I have a train_df and a test_df, which come from the same original dataframe, but were split up in some proportion to form the training and test datasets, respectively.

Both train and test dataframes have identical structure:

A PeriodIndex with daily buckets

n number of columns that represent observed values in those time buckets e.g. Sales, Price, etc.

I now want to construct a yhat_df, which stores predicted values for each of the columns. In the "naive" case, yhat_df columns values are simply the last observed training dataset value.

So I go about constructing yhat_df as below:

```<code>import pandas as pd
yhat_df = pd.DataFrame().reindex_like(test_df)
yhat_df[train_df.columns[0]].fillna(train_df.tail(1).values[0][0], inplace=True)
yhat_df(train_df.columns[1]].fillna(train_df.tail(1).values[0][1], inplace=True)
</code>```

This appears to work, and since I have only two columns, the extra typing is bearable.

I was wondering if there is simpler way, especially one that does not need me to go column by column.

I tried the following but that just populates the column values correctly where the PeriodIndex values match. It seems fillna() attempts to do a join() of sorts internally on the Index:

```<code>yhat_df.fillna(train_df.tail(1), inplace=True)
</code>```

If I could figure out a way for fillna() to ignore index, maybe this would work?

答:
you can use fillna with a dictionary to fill each column with a different value, so I think:

```<code>yhat_df = yhat_df.fillna(train_df.tail(1).to_dict('records')[0])
</code>```

should work, but if I understand well what you do, then even directly create the dataframe with:

```<code>yhat_df = pd.DataFrame(train_df.tail(1).to_dict('records')[0],
                       index = test_df.index, columns = test_df.columns)
</code>```

Body:
I have a train_df and a test_df, which come from the same original dataframe, but were split up in some proportion to form the training and test datasets, respectively.

Both train and test dataframes have identical structure:

A PeriodIndex with daily buckets

n number of columns that represent observed values in those time buckets e.g. Sales, Price, etc.

I now want to construct a yhat_df, which stores predicted values for each of the columns. In the "naive" case, yhat_df columns values are simply the last observed training dataset value.

So I go about constructing yhat_df as below:

import pandas as pd
yhat_df = pd.DataFrame().reindex_like(test_df)
yhat_df[train_df.columns[0]].fillna(train_df.tail(1).values[0][0], inplace=True)
yhat_df(train_df.columns[1]].fillna(train_df.tail(1).values[0][1], inplace=True)

This appears to work, and since I have only two columns, the extra typing is bearable.

I was wondering if there is simpler way, especially one that does not need me to go column by column.

I tried the following but that just populates the column values correctly where the PeriodIndex values match. It seems fillna() attempts to do a join() of sorts internally on the Index:

yhat_df.fillna(train_df.tail(1), inplace=True)

If I could figure out a way for fillna() to ignore index, maybe this would work?

Body:
you can use fillna with a dictionary to fill each column with a different value, so I think:

yhat_df = yhat_df.fillna(train_df.tail(1).to_dict('records')[0])

should work, but if I understand well what you do, then even directly create the dataframe with:

yhat_df = pd.DataFrame(train_df.tail(1).to_dict('records')[0],
                       index = test_df.index, columns = test_df.columns)