问:
How to change the datetime format in sqflite database so that it displays only date?
I'm hoping you can help me figure this out! I've been tearing my hair out for days with this, so any help would be much appreciated.

I want to add a "date" column to the sqflite table in my current project. Here's the code for the database_helper.dart:

import 'dart:io';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DatabaseHelper {

  static final _databaseName = "MyDatabase.db";
  static final _databaseVersion = 1;

  static final table = 'my_table';

  static final columnId = '_id';
  static final columnName = 'name';
  static final columnAge = 'age';
  static final columnColour = 'colour';
  static final columnDateTime = 'datetime';

  // make this a singleton class
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  // only have a single app-wide reference to the database
  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    // lazily instantiate the db the first time it is accessed
    _database = await _initDatabase();
    return _database;
  }

  // this opens the database (and creates it if it doesn't exist)
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion,
        onCreate: _onCreate);
  }

  // SQL code to create the database table
  Future _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE $table (
            $columnId INTEGER PRIMARY KEY,
            $columnName TEXT NOT NULL,
            $columnAge INTEGER NOT NULL,
            $columnColour TEXT NOT NULL,
            $columnDateTime TEXT NOT NULL
          )
          ''');
  }

  // Helper methods

  // Inserts a row in the database where each key in the Map is a column name
  // and the value is the column value. The return value is the id of the
  // inserted row.
  Future<int> insert(Map<String, dynamic> row) async {
    Database db = await instance.database;
    return await db.insert(table, row);
  }

  // All of the rows are returned as a list of maps, where each map is
  // a key-value list of columns.
  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await instance.database;
    return await db.query(table);
  }

  // All of the methods (insert, query, update, delete) can also be done using
  // raw SQL commands. This method uses a raw query to give the row count.
  Future<int> queryRowCount() async {
    Database db = await instance.database;
    return Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM $table'));
  }

  // We are assuming here that the id column in the map is set. The other
  // column values will be used to update the row.
  Future<int> update(Map<String, dynamic> row) async {
    Database db = await instance.database;
    int id = row[columnId];
    return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
  }

  // Deletes the row specified by the id. The number of affected rows is
  // returned. This should be 1 as long as the row exists.
  Future<int> delete(int id) async {
    Database db = await instance.database;
    return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
  }
}```
</div>
</div>
</p>

<p>And here's the code for the main.dart:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import 'package:flutter/material.dart';
// change `flutter_database` to whatever your project name is
import 'package:flutter_database/database_helper.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SQFlite Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {

  // reference to our single class that manages the database
  final dbHelper = DatabaseHelper.instance;

  // homepage layout
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('sqflite'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('insert', style: TextStyle(fontSize: 20),),
              onPressed: () {_insert();},
            ),
            RaisedButton(
              child: Text('query', style: TextStyle(fontSize: 20),),
              onPressed: () {_query();},
            ),
          ],
        ),
      ),
    );
  }

  // Button onPressed methods

  void _insert() async {

    // row to insert
    Map<String, dynamic> row = {
      DatabaseHelper.columnName : 'Bob',
      DatabaseHelper.columnAge  : 23,
      DatabaseHelper.columnColour : 'Red',
      DatabaseHelper.columnDateTime : DateTime.now().toIso8601String(),
    };
    final id = await dbHelper.insert(row);
    print('inserted row id: $id');
  }

  void _query() async {
    final allRows = await dbHelper.queryAllRows();
    print('query all rows:');
    allRows.forEach((row) => print(row));
  }

}</code>```

The goal is to simply to put today's date into the record - I don't need to time part of it, just the date. If you run the above code, the datetime gets displayed in the console if you click the 'query' button, but I want it to only store today's date, not the time aswell.

I've had a look at the docs for the intl package, as I've read that is a good way to format date, but I can't figure out how to implement it into my code in this instance.

Any ideas would be greatly appreciated!

Thank you very much,

Jason

答:
Yep, you can utilize intl's DateFormatter for this:

```<code>import 'package:intl/intl.dart';
import 'package:test/test.dart';

void main() {
  final DateFormat dateOnlyFormat = DateFormat('yyyy.MM.dd');
  test(
      'assert that dateOnlyFormat returns only date part of a DateTime '
      'instance', () {
    final DateTime givenDateTime = DateTime(1995, 1, 1, 5, 5, 5, 5, 5);
    expect(dateOnlyFormat.format(givenDateTime), "1995.01.01");
  });

  test('assert that dateOnlyFormat parses the date as expected', () {
    const String givenDateString = "1995.01.01";
    expect(dateOnlyFormat.parse(givenDateString), DateTime(1995, 1, 1));
  });
}
</code>```

Refer to the DateFormat's class documentation if you need to customize the date format in some other way.

Body:
I'm hoping you can help me figure this out! I've been tearing my hair out for days with this, so any help would be much appreciated.

I want to add a "date" column to the sqflite table in my current project. Here's the code for the database_helper.dart:

import 'dart:io';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DatabaseHelper {

  static final _databaseName = "MyDatabase.db";
  static final _databaseVersion = 1;

  static final table = 'my_table';

  static final columnId = '_id';
  static final columnName = 'name';
  static final columnAge = 'age';
  static final columnColour = 'colour';
  static final columnDateTime = 'datetime';

  // make this a singleton class
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  // only have a single app-wide reference to the database
  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    // lazily instantiate the db the first time it is accessed
    _database = await _initDatabase();
    return _database;
  }

  // this opens the database (and creates it if it doesn't exist)
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion,
        onCreate: _onCreate);
  }

  // SQL code to create the database table
  Future _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE $table (
            $columnId INTEGER PRIMARY KEY,
            $columnName TEXT NOT NULL,
            $columnAge INTEGER NOT NULL,
            $columnColour TEXT NOT NULL,
            $columnDateTime TEXT NOT NULL
          )
          ''');
  }

  // Helper methods

  // Inserts a row in the database where each key in the Map is a column name
  // and the value is the column value. The return value is the id of the
  // inserted row.
  Future<int> insert(Map<String, dynamic> row) async {
    Database db = await instance.database;
    return await db.insert(table, row);
  }

  // All of the rows are returned as a list of maps, where each map is
  // a key-value list of columns.
  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await instance.database;
    return await db.query(table);
  }

  // All of the methods (insert, query, update, delete) can also be done using
  // raw SQL commands. This method uses a raw query to give the row count.
  Future<int> queryRowCount() async {
    Database db = await instance.database;
    return Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM $table'));
  }

  // We are assuming here that the id column in the map is set. The other
  // column values will be used to update the row.
  Future<int> update(Map<String, dynamic> row) async {
    Database db = await instance.database;
    int id = row[columnId];
    return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
  }

  // Deletes the row specified by the id. The number of affected rows is
  // returned. This should be 1 as long as the row exists.
  Future<int> delete(int id) async {
    Database db = await instance.database;
    return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
  }
}

And here's the code for the main.dart:

import 'package:flutter/material.dart';
// change `flutter_database` to whatever your project name is
import 'package:flutter_database/database_helper.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SQFlite Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {

  // reference to our single class that manages the database
  final dbHelper = DatabaseHelper.instance;

  // homepage layout
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('sqflite'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('insert', style: TextStyle(fontSize: 20),),
              onPressed: () {_insert();},
            ),
            RaisedButton(
              child: Text('query', style: TextStyle(fontSize: 20),),
              onPressed: () {_query();},
            ),
          ],
        ),
      ),
    );
  }

  // Button onPressed methods

  void _insert() async {

    // row to insert
    Map<String, dynamic> row = {
      DatabaseHelper.columnName : 'Bob',
      DatabaseHelper.columnAge  : 23,
      DatabaseHelper.columnColour : 'Red',
      DatabaseHelper.columnDateTime : DateTime.now().toIso8601String(),
    };
    final id = await dbHelper.insert(row);
    print('inserted row id: $id');
  }

  void _query() async {
    final allRows = await dbHelper.queryAllRows();
    print('query all rows:');
    allRows.forEach((row) => print(row));
  }

}

The goal is to simply to put today's date into the record - I don't need to time part of it, just the date. If you run the above code, the datetime gets displayed in the console if you click the 'query' button, but I want it to only store today's date, not the time aswell.

I've had a look at the docs for the intl package, as I've read that is a good way to format date, but I can't figure out how to implement it into my code in this instance.

Any ideas would be greatly appreciated!

Thank you very much,

Jason

Body:
Yep, you can utilize intl's DateFormatter for this:

import 'package:intl/intl.dart';
import 'package:test/test.dart';

void main() {
  final DateFormat dateOnlyFormat = DateFormat('yyyy.MM.dd');
  test(
      'assert that dateOnlyFormat returns only date part of a DateTime '
      'instance', () {
    final DateTime givenDateTime = DateTime(1995, 1, 1, 5, 5, 5, 5, 5);
    expect(dateOnlyFormat.format(givenDateTime), "1995.01.01");
  });

  test('assert that dateOnlyFormat parses the date as expected', () {
    const String givenDateString = "1995.01.01";
    expect(dateOnlyFormat.parse(givenDateString), DateTime(1995, 1, 1));
  });
}

Refer to the DateFormat's class documentation if you need to customize the date format in some other way.


来源: stackexchange

问:
Parsing field access flags in java
I have an assignment wherein I have to parse the field access flags of a java .class file.
The specification for a .class file can be found here: Class File Format (page 26 & 27 have the access flags and hex vals).

This is fine, I can do this no worries.
My issue is that there is a large number of combinations.

I know the public, private and protected are mutually exclusive, which reduces the combinations somewhat. Final and transient are also mutually exclusive. The rest however are not.

At the moment, I have a large switch statement to do the comparison. I read in the hex value of the access flag and then increment a counter, depending on if it is public, private or protected. This works fine, but it seems quite messy to just have every combination listed in a switch statement. i.e. public static, public final, public static final, etc.

I thought of doing modulo on the access flag and the appropriate hex value for public, private or protected, but public is 0x0001, so that won't work.

Does anyone else have any ideas as to how I could reduce the amount of cases in my switch statement?

答:
If you are trying to avoid a pattern like this one I just stole:

```<code>if (access_flag & ACC_PUBLIC != 0)
{
    public++;
}
if (access_flag & ACC_FINAL != 0)
{
    final++;
}
...
</code>```

It's a great instinct.  I make it a rule never to write code that looks redundant like that.  Not only is it error-prone and more code in your class, but copy & paste code is really boring to write.

So the big trick is to make this access "Generic" and easy to understand from the calling class--pull out all the repeated crap and just leave "meat", push the complexity to the generic routine.

So an easy way to call a method would be something like this that gives an array of bitfields that contain many bit combinations that need counted and a list of fields that you are interested in (so that you don't waste time testing fields you don't care about):

```<code>int[] counts = sumUpBits(arrayOfFlagBitfields, ACC_PUBLIC | ACC_FINAL | ACC_...);
</code>```

That's really clean, but then how do you access the return fields?  I was originally thinking something like this:

```<code>System.out.println("Number of public classes="+counts[findBitPosition(ACC_PUBLIC]));
System.out.println("Number of final classes="+counts[findBitPosition(ACC_FINAL)]);
</code>```

Most of the boilerplate here is gone except the need to change the bitfields to their position.  I think two changes might make it better--encapsulate it in a class and use a hash to track positions so that you don't have to convert bitPosition all the time (if you prefer not to use the hash, findBitPosition is at the end).

Let's try a full-fledged class.  How should this look from the caller's point of view?

```<code>BitSummer bitSums=new BitSummer(arrayOfFlagBitfields, ACC_PUBLIC, ACC_FINAL);
System.out.println("Number of public classes="+bitSums.getCount(ACC_PUBLIC));
System.out.println("Number of final classes="+bitSums.getCount(ACC_FINAL));
</code>```

That's pretty clean and easy--I really love OO! Now you just use the bitSums to store your values until they are needed (It's less boilerplate than storing them in class variables and more clear than using an array or a collection)

So now to code the class.  Note that the constructor uses variable arguments now--less surprise/more conventional and makes more sense for the hash implementation.

By the way, I know this seems like it would be slow and inefficient, but it's probably not bad for most uses--if it is, it can be improved, but this should be much shorter and less redundant than the switch statement (which is really the same as this, just unrolled--however this one uses a hash & autoboxing which will incur an additional penalty).

```<code>public class BitSummer {
    // sums will store the "sum" as <flag, count>
    private final HashMap<Integer, Integer> sums=new HashMap<Integer, Integer>();

    // Constructor does all the work, the rest is just an easy lookup.
    public BitSummer(int[] arrayOfFlagBitfields, int ... positionsToCount) {

        // Loop over each bitfield we want to count
        for(int bitfield : arrayOfFlagBitfields) {

            // and over each flag to check
            for(int flag : positionsToCount) {
                // Test to see if we actually should count this bitfield as having the flag set
                if((bitfield & flag) != 0) {
                    sums.put(flag, sums.get(flag) +1); // Increment value
                }
            }
        }
    }

    // Return the count for a given bit position
    public int getCount(int bit) {
        return sums.get(bit);
    }
}
</code>```

I didn't test this but I think it's fairly close.  I wouldn't use it for processing video packets in realtime or anything, but for most purposes it should be fast enough.

As for maintaining code may look "Long" compared to the original example but if you have more than 5 or 6 fields to check, this will actually be a shorter solution than the chained if statements and significantly less error/prone and more maintainable--also more interesting to write.

If you really feel the need to eliminate the hashtable you could easily replace it with a sparse array with the flag position as the index (for instance the count of a flag 00001000/0x08 would be stored in the fourth array position).  This would require a function like this to calculate the bit position for array access (both storing in the array and retrieving)

```<code>private int findBitPosition(int flag) {
    int ret;
    while( ( flag << 1 ) != 0 )
        ret++;
    return ret;
}
</code>```

That was fun.

ContentLicense: CC BY-SA 3.0

Title: Parsing field access flags in java

Body:
If you are trying to avoid a pattern like this one I just stole:

if (access_flag & ACC_PUBLIC != 0)
{
    public++;
}
if (access_flag & ACC_FINAL != 0)
{
    final++;
}
...

It's a great instinct.  I make it a rule never to write code that looks redundant like that.  Not only is it error-prone and more code in your class, but copy & paste code is really boring to write.

So the big trick is to make this access "Generic" and easy to understand from the calling class--pull out all the repeated crap and just leave "meat", push the complexity to the generic routine.

So an easy way to call a method would be something like this that gives an array of bitfields that contain many bit combinations that need counted and a list of fields that you are interested in (so that you don't waste time testing fields you don't care about):

int[] counts = sumUpBits(arrayOfFlagBitfields, ACC_PUBLIC | ACC_FINAL | ACC_...);

That's really clean, but then how do you access the return fields?  I was originally thinking something like this:

System.out.println("Number of public classes="+counts[findBitPosition(ACC_PUBLIC]));
System.out.println("Number of final classes="+counts[findBitPosition(ACC_FINAL)]);

Most of the boilerplate here is gone except the need to change the bitfields to their position.  I think two changes might make it better--encapsulate it in a class and use a hash to track positions so that you don't have to convert bitPosition all the time (if you prefer not to use the hash, findBitPosition is at the end).

Let's try a full-fledged class.  How should this look from the caller's point of view?

BitSummer bitSums=new BitSummer(arrayOfFlagBitfields, ACC_PUBLIC, ACC_FINAL);
System.out.println("Number of public classes="+bitSums.getCount(ACC_PUBLIC));
System.out.println("Number of final classes="+bitSums.getCount(ACC_FINAL));

That's pretty clean and easy--I really love OO! Now you just use the bitSums to store your values until they are needed (It's less boilerplate than storing them in class variables and more clear than using an array or a collection)

So now to code the class.  Note that the constructor uses variable arguments now--less surprise/more conventional and makes more sense for the hash implementation.

By the way, I know this seems like it would be slow and inefficient, but it's probably not bad for most uses--if it is, it can be improved, but this should be much shorter and less redundant than the switch statement (which is really the same as this, just unrolled--however this one uses a hash & autoboxing which will incur an additional penalty).

public class BitSummer {
    // sums will store the "sum" as <flag, count>
    private final HashMap<Integer, Integer> sums=new HashMap<Integer, Integer>();

    // Constructor does all the work, the rest is just an easy lookup.
    public BitSummer(int[] arrayOfFlagBitfields, int ... positionsToCount) {

        // Loop over each bitfield we want to count
        for(int bitfield : arrayOfFlagBitfields) {

            // and over each flag to check
            for(int flag : positionsToCount) {
                // Test to see if we actually should count this bitfield as having the flag set
                if((bitfield & flag) != 0) {
                    sums.put(flag, sums.get(flag) +1); // Increment value
                }
            }
        }
    }

    // Return the count for a given bit position
    public int getCount(int bit) {
        return sums.get(bit);
    }
}

I didn't test this but I think it's fairly close.  I wouldn't use it for processing video packets in realtime or anything, but for most purposes it should be fast enough.

As for maintaining code may look "Long" compared to the original example but if you have more than 5 or 6 fields to check, this will actually be a shorter solution than the chained if statements and significantly less error/prone and more maintainable--also more interesting to write.

If you really feel the need to eliminate the hashtable you could easily replace it with a sparse array with the flag position as the index (for instance the count of a flag 00001000/0x08 would be stored in the fourth array position).  This would require a function like this to calculate the bit position for array access (both storing in the array and retrieving)

private int findBitPosition(int flag) {
    int ret;
    while( ( flag << 1 ) != 0 )
        ret++;
    return ret;
}

That was fun.


问:
Calculate manual week number of year in Oracle SQL
i have a date column and along that i need to calculate another column in oracle for week number of they year, the weeks should be from sunday to saturday, starting first day of the year.

for example for current year

```<code>Week 1 : 1 Jan 2020 (Wednesday) - 4 Jan 2020(Saturday)

Week 2 : 5 Jan 2020 (Sunday)        - 11 Jan 2020(Saturday)

. . . . .

Week 5 : 26 Jan 2020 (Sunday) - 1 Feb 2020 (Saturday)
</code>```

and so on...

答:
One other option would be

```<code>with t as
(
 select trunc(sysdate,'yyyy')+level-1 as day, to_char(trunc(sysdate,'yyyy')+level-1,'DY','NLS_DATE_LANGUAGE=AMERICAN') as weekday, level - 1 as lvl
   from dual
 connect by level <= 366
), t1 as
(
select case
         when lvl = 0 then
          day
         else
          case
            when weekday = 'SUN' then
             day
          end
       end as day1,
       lvl
  from t
), t2 as
(
select case
         when weekday = 'SAT' then
          day
       end as day2,
       lvl
  from t
)
select concat( 'Week ', wk1) as week, day1, day2
  from
  (
   select row_number() over (order by lvl) wk1, day1
     from t1 where day1 is not null ) t1
  left join
  (
   select row_number() over (order by lvl) wk2, day2
     from t2 where day2 is not null ) t2
    on wk2 = wk1
</code>```

by using select .. from dual connect by level syntax and case..when expression to scan all the current year.

Demo

ContentLicense: CC BY-SA 4.0

Body:
i have a date column and along that i need to calculate another column in oracle for week number of they year, the weeks should be from sunday to saturday, starting first day of the year.

for example for current year

Week 1 : 1 Jan 2020 (Wednesday) - 4 Jan 2020(Saturday)

Week 2 : 5 Jan 2020 (Sunday)        - 11 Jan 2020(Saturday)

. . . . .

Week 5 : 26 Jan 2020 (Sunday) - 1 Feb 2020 (Saturday)

and so on...

Body:
One other option would be

with t as
(
 select trunc(sysdate,'yyyy')+level-1 as day, to_char(trunc(sysdate,'yyyy')+level-1,'DY','NLS_DATE_LANGUAGE=AMERICAN') as weekday, level - 1 as lvl
   from dual
 connect by level <= 366
), t1 as
(
select case
         when lvl = 0 then
          day
         else
          case
            when weekday = 'SUN' then
             day
          end
       end as day1,
       lvl
  from t
), t2 as
(
select case
         when weekday = 'SAT' then
          day
       end as day2,
       lvl
  from t
)
select concat( 'Week ', wk1) as week, day1, day2
  from
  (
   select row_number() over (order by lvl) wk1, day1
     from t1 where day1 is not null ) t1
  left join
  (
   select row_number() over (order by lvl) wk2, day2
     from t2 where day2 is not null ) t2
    on wk2 = wk1

by using select .. from dual connect by level syntax and case..when expression to scan all the current year.

Demo


问:
how to set main class in SBT 0.13 project
Could you guys please explain to me how to set main class in SBT project ? I'm trying to use version 0.13.

My directory structure is very simple (unlike SBT's documentation). In the root folder I have build.sbt with following content

```<code>name := "sbt_test"

version := "1.0"

scalaVersion := "2.10.1-local"

autoScalaLibrary := false

scalaHome := Some(file("/Program Files (x86)/scala/"))

mainClass := Some("Hi")

libraryDependencies ++= Seq(
    "org.scalatest" % "scalatest_2.10" % "2.0.M5b" % "test"
)

EclipseKeys.withSource := true
</code>```

And I have subfolder project with single file Hi.scala which contains following code

```<code>object Hi {
  def main(args: Array[String]) = println("Hi!")
}
</code>```

I'm able to compile it by calling sbt compile but sbt run returns

```<code>The system cannot find the file C:\work\externals\sbt\bin\sbtconfig.txt.
[info] Loading project definition from C:\work\test_projects\sbt_test\project
[info] Set current project to sbt_test (in build file:/C:/work/test_projects/sbt_test/)
java.lang.RuntimeException: No main class detected.
        at scala.sys.package$.error(package.scala:27)
[trace] Stack trace suppressed: run last compile:run for the full output.
[error] (compile:run) No main class detected.
[error] Total time: 0 s, completed Apr 8, 2013 6:14:41 PM
</code>```

答:
I had the same issue. Resolved it after adding PlayMinimalJava plugin in build.sbt.

Not sure how it got fixed, if someone can highlight how PlayMinimalJava solves it, would be great.

```<code>enablePlugins(PlayMinimalJava)
</code>```

My build.sbt looks like this

```<code>organization := "org"
version := "1.0-SNAPSHOT"
scalaVersion := "2.13.1"
libraryDependencies += guice
enablePlugins(PlayMinimalJava)
</code>```

Log

```<code>C:\Users\KulwantSingh\repository\pdfdemo>sbt run
Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0
[info] Loading settings for project pdfdemo-build from plugins.sbt ...
[info] Loading project definition from C:\Users\KulwantSingh\repository\pdfdemo\project
[info] Loading settings for project pdfdemo from build.sbt ...
[info] Set current project to pdfdemo (in build file:/C:/Users/KulwantSingh/repository/pdfdemo/)
[warn] There may be incompatibilities among your library dependencies; run 'evicted' to see detailed eviction warnings.

--- (Running the application, auto-reloading is enabled) ---

[info] p.c.s.AkkaHttpServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

(Server started, use Enter to stop and go back to the console...)

[info] Compiling 6 Scala sources and 2 Java sources to C:\Users\KulwantSingh\repository\pdfdemo\target\scala-2.13\classes ...
[info] p.a.h.EnabledFilters - Enabled Filters (see <https://www.playframework.com/documentation/latest/Filters>):

    play.filters.csrf.CSRFFilter
    play.filters.headers.SecurityHeadersFilter
    play.filters.hosts.AllowedHostsFilter

[info] play.api.Play - Application started (Dev) (no global state)
</code>```

Body:
Could you guys please explain to me how to set main class in SBT project ? I'm trying to use version 0.13.

My directory structure is very simple (unlike SBT's documentation). In the root folder I have build.sbt with following content

name := "sbt_test"

version := "1.0"

scalaVersion := "2.10.1-local"

autoScalaLibrary := false

scalaHome := Some(file("/Program Files (x86)/scala/"))

mainClass := Some("Hi")

libraryDependencies ++= Seq(
    "org.scalatest" % "scalatest_2.10" % "2.0.M5b" % "test"
)

EclipseKeys.withSource := true

And I have subfolder project with single file Hi.scala which contains following code

object Hi {
  def main(args: Array[String]) = println("Hi!")
}

I'm able to compile it by calling sbt compile but sbt run returns

The system cannot find the file C:\work\externals\sbt\bin\sbtconfig.txt.
[info] Loading project definition from C:\work\test_projects\sbt_test\project
[info] Set current project to sbt_test (in build file:/C:/work/test_projects/sbt_test/)
java.lang.RuntimeException: No main class detected.
        at scala.sys.package$.error(package.scala:27)
[trace] Stack trace suppressed: run last compile:run for the full output.
[error] (compile:run) No main class detected.
[error] Total time: 0 s, completed Apr 8, 2013 6:14:41 PM

Body:
I had the same issue. Resolved it after adding PlayMinimalJava plugin in build.sbt.

Not sure how it got fixed, if someone can highlight how PlayMinimalJava solves it, would be great.

enablePlugins(PlayMinimalJava)

My build.sbt looks like this

organization := "org"
version := "1.0-SNAPSHOT"
scalaVersion := "2.13.1"
libraryDependencies += guice
enablePlugins(PlayMinimalJava)

Log

C:\Users\KulwantSingh\repository\pdfdemo>sbt run
Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0
[info] Loading settings for project pdfdemo-build from plugins.sbt ...
[info] Loading project definition from C:\Users\KulwantSingh\repository\pdfdemo\project
[info] Loading settings for project pdfdemo from build.sbt ...
[info] Set current project to pdfdemo (in build file:/C:/Users/KulwantSingh/repository/pdfdemo/)
[warn] There may be incompatibilities among your library dependencies; run 'evicted' to see detailed eviction warnings.

--- (Running the application, auto-reloading is enabled) ---

[info] p.c.s.AkkaHttpServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

(Server started, use Enter to stop and go back to the console...)

[info] Compiling 6 Scala sources and 2 Java sources to C:\Users\KulwantSingh\repository\pdfdemo\target\scala-2.13\classes ...
[info] p.a.h.EnabledFilters - Enabled Filters (see <https://www.playframework.com/documentation/latest/Filters>):

    play.filters.csrf.CSRFFilter
    play.filters.headers.SecurityHeadersFilter
    play.filters.hosts.AllowedHostsFilter

[info] play.api.Play - Application started (Dev) (no global state)


问:
Is there a way to call a function by setting its attribute?
I have an object which looks like this:

const trigger = {
    // ...
    addEventListener: function(evt, cb) {
        // ...
    }
};
```

<p>It has an event registration system by calling <code>addEventListener</code>.</p>

<p>I also want it can be called by <code>trigger.onxxx = xxx</code>(the function is started with <code>on</code>) for legacy purposes. How can I do that?</p>

<p>Such as if I write</p>

<pre class="lang-js prettyprint-override"><code>const handleTouch = function() { /* ... */ };
trigger.ontouch = handleTouch;
</code>```

And this is what it actually does:

trigger.addEventListener('touch', handleTouch);
```

I know I can use a setter to call a function, but in this case the function name is random.

Is there a way to automatically calling the function when I set it

or I have to hard code them separately?

答:
You can make a Proxy, and when a property is set, check if its name starts with on. If it was, call the addEventListener method, otherwise modify the underlying object (if that could ever occur):

const addEventListener = function(evt, cb) {
  console.log('adding listener for', evt);
}

const trigger = {
  addEventListener,
  // other properties
};

const proxy = new Proxy(trigger, {
  set(target, prop, newVal) {
    if (prop.startsWith('on')) {
      return addEventListener(prop.slice(2), newVal);
    }
    return target[prop] = newVal;
  }
});

proxy.onfoo = () => 'on foo';
proxy.addEventListener('foo', () => 'on foo');```

Body:
I have an object which looks like this:

const trigger = {
    // ...
    addEventListener: function(evt, cb) {
        // ...
    }
};

It has an event registration system by calling addEventListener.

I also want it can be called by trigger.onxxx = xxx(the function is started with on) for legacy purposes. How can I do that?

Such as if I write

const handleTouch = function() { /* ... */ };
trigger.ontouch = handleTouch;

And this is what it actually does:

trigger.addEventListener('touch', handleTouch);

I know I can use a setter to call a function, but in this case the function name is random.

Is there a way to automatically calling the function when I set it

or I have to hard code them separately?


问:
Deleting registrry subkey doesnt delete,no error was throwed
I am trying to delete some registry key via C#, but to code doesn't effect about the registry, I opened Visual Studio as administrator, I am trying to delete a key located in this path:

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects

Here my code:

```<code>string RegBHO = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects";
string guid = "{b908e54f-8c58-4d5d-8762-60d7d675cd39}";
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(RegBHO, true);
registryKey.DeleteSubKey(guid, false);
</code>```

But the folder named {b908e54f-8c58-4d5d-8762-60d7d675cd39} still exist enen after I run the code (I clicked F5 to refresh registry list)

答:
More than likely you are trying to delete a 32bit key from a 64bit application or vice-versa.

You will need to use the appropriate bitness in your app, or use the following to read / write / Delete the keys

RegistryView Enum

Specifies which registry view to target on a 64-bit operating system.

with

RegistryKey.OpenBaseKey

Opens a new RegistryKey that represents the requested key on the local
  machine with the specified view.

RegistryView Enumeration : On the 64-bit version of Windows, portions of the registry are stored
  separately for 32-bit and 64-bit applications. There is a 32-bit view
  for 32-bit applications and a 64-bit view for 64-bit applications.

You can specify a registry view when you use the OpenBaseKey and
  OpenRemoteBaseKey(RegistryHive, String, RegistryView) methods, and the
  FromHandle property on a RegistryKey object.

Example

```<code>using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{

}
</code>```

Body:
I am trying to delete some registry key via C#, but to code doesn't effect about the registry, I opened Visual Studio as administrator, I am trying to delete a key located in this path:

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects

Here my code:

string RegBHO = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects";
string guid = "{b908e54f-8c58-4d5d-8762-60d7d675cd39}";
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(RegBHO, true);
registryKey.DeleteSubKey(guid, false);

But the folder named {b908e54f-8c58-4d5d-8762-60d7d675cd39} still exist enen after I run the code (I clicked F5 to refresh registry list)

Body:
More than likely you are trying to delete a 32bit key from a 64bit application or vice-versa.

You will need to use the appropriate bitness in your app, or use the following to read / write / Delete the keys

RegistryView Enum

Specifies which registry view to target on a 64-bit operating system.

with

RegistryKey.OpenBaseKey

Opens a new RegistryKey that represents the requested key on the local
  machine with the specified view.

RegistryView Enumeration : On the 64-bit version of Windows, portions of the registry are stored
  separately for 32-bit and 64-bit applications. There is a 32-bit view
  for 32-bit applications and a 64-bit view for 64-bit applications.

You can specify a registry view when you use the OpenBaseKey and
  OpenRemoteBaseKey(RegistryHive, String, RegistryView) methods, and the
  FromHandle property on a RegistryKey object.

Example

using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{

}


问:
Delete extensionless files which names end with '_C' string
I have a batch code which cleans files which are older than 15 days. But I want to only delete files that end with '_C' and they have no extension.

Here is my code:

```<code>SET mypath=%cd%/downloads

ForFiles /p %mypath% /d -15 /c "cmd /c For /R %%A in (*_C.*) Do (del /q @fname)
</code>```

Here are my files:

File Name: ---------Date:

A_C_123_C ------                   18.02.2019

A_C_456_C ------                    01.01.2018

A_C_789_C  ------                   01.01.2018

Testfile-------------                01.01.2018

tmp.txt -------------                      01.01.2018

When I execute the code, it cleans Testfile also. I just want to delete extensionless files that end with '_C' and older than 15 days.

What should I do?

答:
You do not require incorporating the for loop into the forfiles command. forfiles has it's own search switch /s

You specifically mention you want to only do files ending with _C with no extension, but you added *_C.* which in fact means anything before _C with a dot and anything after the dot. You really just need:

```<code>@forfiles /p %mypath% /d -15 /s /m *_C /c "cmd /c If @IsDir==FALSE del @path"
</code>```

Body:
I have a batch code which cleans files which are older than 15 days. But I want to only delete files that end with '_C' and they have no extension.

Here is my code:

SET mypath=%cd%/downloads

ForFiles /p %mypath% /d -15 /c "cmd /c For /R %%A in (*_C.*) Do (del /q @fname)

Here are my files:

File Name: ---------Date:

A_C_123_C ------                   18.02.2019

A_C_456_C ------                    01.01.2018

A_C_789_C  ------                   01.01.2018

Testfile-------------                01.01.2018

tmp.txt -------------                      01.01.2018

When I execute the code, it cleans Testfile also. I just want to delete extensionless files that end with '_C' and older than 15 days.

What should I do?

Body:
You do not require incorporating the for loop into the forfiles command. forfiles has it's own search switch /s

You specifically mention you want to only do files ending with _C with no extension, but you added *_C.* which in fact means anything before _C with a dot and anything after the dot. You really just need:

@forfiles /p %mypath% /d -15 /s /m *_C /c "cmd /c If @IsDir==FALSE del @path"


问:
How can I copy a range to a different sheet based on checkbox value, then delete on the new sheet, while keeping both check boxes up to date
I need some help on this code. I have my source sheet "Agency List". When the check box in column J is True the data in columns K-Last Column is copied to sheet "Itinerary" starting at the first empty row and column K. This formula is working, however I need to add some functionality and can't find an answer. I need to:

I want to be able to check the box, have the row copy to "Itinerary". Then on "Itinerary" have a checked box carry over with the data. When I uncheck that box on "Itinerary" I want to data to clear, and the corresponding check box on "Agency List" to be unchecked as well.

I also need to be able to toggle both check boxes with my mouse. And it seems that if the cell contains a formula you can not toggle. Is there a way around this?

Currently I'm copying the data to the last row in "Itinerary". But if there is a formula or column anywhere else on the sheet in that row it treats the row as not empty. In particular I can't have a checkbox in column 'Itinerary'!J:J down the sheet because then the row isn't blank and the data goes to the very bottom. I tried using a code that would look at the last row of Column O, but then they entire formula stopped working:
var target = targetSheet.getRange(targetSheet.getRange(O:O).getLastRow() + 1,11);

I thought about using VLOOKUP or Match or some other formula to scan a column in "itinerary" for a match and if there isn't a match then the checkbox goes to FALSE. But again, then I can't toggle the checkbox.

Is there a way to keep both check boxes up to date and copy/clear the data on "Itinerary" based on that checkbox?
Thanks!

Here is a link to a sample sheet:
Sample Sheet

```<code>function onEdit(event) {
    // assumes source data in sheet named "Agency List"
    // target sheet of move to named "Itinerary"
    // getColumn with check-boxes is currently set to colu 3 or C
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = event.source.getActiveSheet();
    var r = event.source.getActiveRange();
    if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == true) {
        var row = r.getRow();
        var numColumns = s.getLastColumn();
        var targetSheet = ss.getSheetByName("Itinerary");
        var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 11);
        s.getRange(row, 4, 1, numColumns).copyTo(target, { contentsOnly: true });
    } else if (s.getName() == "Itinerary" && r.getColumn() == 9 && r.getValue() == false) {
        var row = r.getRow();
        var numColumns = s.getLastColumn();
        s.deleteRow(row);
    }
}
</code>```

答:
Ok @Sio I think I made a fix that could work for you.

Basically the problem that you have is keeping track of what row in Itinerary corresponds to the row in Agency List.

To have that kind of persistence in Apps Script without actually storing in the sheet I found this handy Service called PropertiesService. In there I stored the rows in pairs to later retrieve.

Code

```<code>function onEdit(event) {
    // assumes source data in sheet named "Agency List"
    // target sheet of move to named "Itinerary"
    // getColumn with check-boxes is currently set to colu 3 or C
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = event.source.getActiveSheet();
    var r = event.source.getActiveRange();
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    Logger.log(r.getValue());

    if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == true) {
        // Create the record in "Itnerary"
        var prop = PropertiesService.getDocumentProperties();
        var targetSheet = ss.getSheetByName("Itinerary");
        var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 11);
        s.getRange(row, 4, 1, numColumns).copyTo(target, { contentsOnly: true });
        // Insert checkbox cell (already checked)
        targetSheet.getRange(target.getRow(), 10).insertCheckboxes().check();
        prop.setProperty(row, target.getRow());
    } else if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == "") {
        // Remove the row from "Itinerary" when the checkbox in "Agency List" is unchecked
        var prop = PropertiesService.getDocumentProperties();
        var targetRow = prop.getProperty(row);
        ss.getSheetByName("Itinerary").deleteRow(targetRow);
        Logger.log("Deleted the " + targetRow + "row from " + s.getName());
        prop.deleteProperty(row);
    } else if (s.getName() == "Itinerary" && r.getColumn() == 10 && r.getValue() == false) {
        // Remove the row from "Itinerary"when the checkbox is unchecked and unchecks in "Agency List"
        var prop = PropertiesService.getDocumentProperties();
        s.deleteRow(row);

        // Look the corresponding row in "Agency List"
        var keys = prop.getKeys();
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (prop.getProperty(key) == row) {
                ss.getSheetByName("Agency List").getRange(key, 3).setValue(false);
                prop.deleteProperty(key)
                break;
            }
        }
    }
}
</code>```

Explanation

So you actually have three cases you need to process here.

You check the row in Agency List to create a new record in Itinerary.

```<code>if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == true) {
        // Create the record in "Itnerary"
        var prop = PropertiesService.getDocumentProperties();
        var targetSheet = ss.getSheetByName("Itinerary");
        var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 11);
        s.getRange(row, 4, 1, numColumns).copyTo(target, { contentsOnly: true });
        // Insert checkbox cell (already checked)
        targetSheet.getRange(target.getRow(), 10).insertCheckboxes().check();
        prop.setProperty(row, target.getRow());
}
</code>```

This is the one you already had, just adding the insertCheckboxes at 10th column (J). Also storing the pair of rows to later retrieve it. Look that I have store it in a document level.

You uncheck the row at Agency List to delete the row at Itinerary

```<code>} else if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == "") {
        // Remove the row from "Itinerary" when the checkbox in "Agency List" is unchecked
        var prop = PropertiesService.getDocumentProperties();
        var targetRow = prop.getProperty(row);
        ss.getSheetByName("Itinerary").deleteRow(targetRow);
        Logger.log("Deleted the " + targetRow + "row from " + s.getName());
        prop.deleteProperty(row);
}
</code>```

Getting the row we need to delete through the document properties. Then use the deleteRow in Itinerary, and get rid of the record in our properties with deleteProperty.

You uncheck the row in Itinerary to delete that row and to uncheck the row in Agency List .

```<code>} else if (s.getName() == "Itinerary" && r.getColumn() == 10 && r.getValue() == false) {
        // Remove the row from "Itinerary"when the checkbox is unchecked and unchecks in "Agency List"
        var prop = PropertiesService.getDocumentProperties();
        s.deleteRow(row);

        // Look the corresponding row in "Agency List"
        var keys = prop.getKeys();
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (prop.getProperty(key) == row) {
                ss.getSheetByName("Agency List").getRange(key, 3).setValue(false);
                prop.deleteProperty(key)
                break;
            }
        }
    }
</code>```

In here deleting the row is pretty straightforward because you retrieve that from the event object. Although in this case we will need to iterate to every pair of values from the properties because we stored the key as the row of Agency List

Reference

Storing and retrieving data in Apps Script

getDocumentProperties()

deleteProperty

insetCheckboxes()

Body:
I need some help on this code. I have my source sheet "Agency List". When the check box in column J is True the data in columns K-Last Column is copied to sheet "Itinerary" starting at the first empty row and column K. This formula is working, however I need to add some functionality and can't find an answer. I need to:

I want to be able to check the box, have the row copy to "Itinerary". Then on "Itinerary" have a checked box carry over with the data. When I uncheck that box on "Itinerary" I want to data to clear, and the corresponding check box on "Agency List" to be unchecked as well.

I also need to be able to toggle both check boxes with my mouse. And it seems that if the cell contains a formula you can not toggle. Is there a way around this?

Currently I'm copying the data to the last row in "Itinerary". But if there is a formula or column anywhere else on the sheet in that row it treats the row as not empty. In particular I can't have a checkbox in column 'Itinerary'!J:J down the sheet because then the row isn't blank and the data goes to the very bottom. I tried using a code that would look at the last row of Column O, but then they entire formula stopped working:
var target = targetSheet.getRange(targetSheet.getRange(O:O).getLastRow() + 1,11);

I thought about using VLOOKUP or Match or some other formula to scan a column in "itinerary" for a match and if there isn't a match then the checkbox goes to FALSE. But again, then I can't toggle the checkbox.

Is there a way to keep both check boxes up to date and copy/clear the data on "Itinerary" based on that checkbox?
Thanks!

Here is a link to a sample sheet:
Sample Sheet

function onEdit(event) {
    // assumes source data in sheet named "Agency List"
    // target sheet of move to named "Itinerary"
    // getColumn with check-boxes is currently set to colu 3 or C
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = event.source.getActiveSheet();
    var r = event.source.getActiveRange();
    if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == true) {
        var row = r.getRow();
        var numColumns = s.getLastColumn();
        var targetSheet = ss.getSheetByName("Itinerary");
        var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 11);
        s.getRange(row, 4, 1, numColumns).copyTo(target, { contentsOnly: true });
    } else if (s.getName() == "Itinerary" && r.getColumn() == 9 && r.getValue() == false) {
        var row = r.getRow();
        var numColumns = s.getLastColumn();
        s.deleteRow(row);
    }
}

Body:
Ok @Sio I think I made a fix that could work for you.

Basically the problem that you have is keeping track of what row in Itinerary corresponds to the row in Agency List.

To have that kind of persistence in Apps Script without actually storing in the sheet I found this handy Service called PropertiesService. In there I stored the rows in pairs to later retrieve.

Code

function onEdit(event) {
    // assumes source data in sheet named "Agency List"
    // target sheet of move to named "Itinerary"
    // getColumn with check-boxes is currently set to colu 3 or C
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = event.source.getActiveSheet();
    var r = event.source.getActiveRange();
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    Logger.log(r.getValue());

    if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == true) {
        // Create the record in "Itnerary"
        var prop = PropertiesService.getDocumentProperties();
        var targetSheet = ss.getSheetByName("Itinerary");
        var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 11);
        s.getRange(row, 4, 1, numColumns).copyTo(target, { contentsOnly: true });
        // Insert checkbox cell (already checked)
        targetSheet.getRange(target.getRow(), 10).insertCheckboxes().check();
        prop.setProperty(row, target.getRow());
    } else if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == "") {
        // Remove the row from "Itinerary" when the checkbox in "Agency List" is unchecked
        var prop = PropertiesService.getDocumentProperties();
        var targetRow = prop.getProperty(row);
        ss.getSheetByName("Itinerary").deleteRow(targetRow);
        Logger.log("Deleted the " + targetRow + "row from " + s.getName());
        prop.deleteProperty(row);
    } else if (s.getName() == "Itinerary" && r.getColumn() == 10 && r.getValue() == false) {
        // Remove the row from "Itinerary"when the checkbox is unchecked and unchecks in "Agency List"
        var prop = PropertiesService.getDocumentProperties();
        s.deleteRow(row);

        // Look the corresponding row in "Agency List"
        var keys = prop.getKeys();
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (prop.getProperty(key) == row) {
                ss.getSheetByName("Agency List").getRange(key, 3).setValue(false);
                prop.deleteProperty(key)
                break;
            }
        }
    }
}

Explanation

So you actually have three cases you need to process here.

You check the row in Agency List to create a new record in Itinerary.

if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == true) {
        // Create the record in "Itnerary"
        var prop = PropertiesService.getDocumentProperties();
        var targetSheet = ss.getSheetByName("Itinerary");
        var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 11);
        s.getRange(row, 4, 1, numColumns).copyTo(target, { contentsOnly: true });
        // Insert checkbox cell (already checked)
        targetSheet.getRange(target.getRow(), 10).insertCheckboxes().check();
        prop.setProperty(row, target.getRow());
}

This is the one you already had, just adding the insertCheckboxes at 10th column (J). Also storing the pair of rows to later retrieve it. Look that I have store it in a document level.

You uncheck the row at Agency List to delete the row at Itinerary

} else if (s.getName() == "Agency List" && r.getColumn() == 3 && r.getValue() == "") {
        // Remove the row from "Itinerary" when the checkbox in "Agency List" is unchecked
        var prop = PropertiesService.getDocumentProperties();
        var targetRow = prop.getProperty(row);
        ss.getSheetByName("Itinerary").deleteRow(targetRow);
        Logger.log("Deleted the " + targetRow + "row from " + s.getName());
        prop.deleteProperty(row);
}

Getting the row we need to delete through the document properties. Then use the deleteRow in Itinerary, and get rid of the record in our properties with deleteProperty.

You uncheck the row in Itinerary to delete that row and to uncheck the row in Agency List .

} else if (s.getName() == "Itinerary" && r.getColumn() == 10 && r.getValue() == false) {
        // Remove the row from "Itinerary"when the checkbox is unchecked and unchecks in "Agency List"
        var prop = PropertiesService.getDocumentProperties();
        s.deleteRow(row);

        // Look the corresponding row in "Agency List"
        var keys = prop.getKeys();
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (prop.getProperty(key) == row) {
                ss.getSheetByName("Agency List").getRange(key, 3).setValue(false);
                prop.deleteProperty(key)
                break;
            }
        }
    }

In here deleting the row is pretty straightforward because you retrieve that from the event object. Although in this case we will need to iterate to every pair of values from the properties because we stored the key as the row of Agency List

Reference

Storing and retrieving data in Apps Script

getDocumentProperties()

deleteProperty

insetCheckboxes()


问:
Update DataGrid Checkbox State By Property that Depends on Other Property
I have a model, which contains CanDrawProperty. I want to bind this property to IsEnabled property of DataGrid CheckBox:

```<code>public class Series : INotifyPropertyChanged
{
    private ObservableCollection<DropPhoto> _dropPhotosSeries;
    public ObservableCollection<DropPhoto> DropPhotosSeries
    {
        get
        {
            return _dropPhotosSeries;
        }
        set
        {
            _dropPhotosSeries = value;
            OnPropertyChanged(new PropertyChangedEventArgs("DropPhotosSeries"));
        }
    }

    private bool _canDrawPlot;
    public bool CanDrawPlot
    {
        get
        {
            if (_dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters != null).ToList().Count > 1)
            {
                _canDrawPlot = true;
                return _canDrawPlot;
            }

            _canDrawPlot = false;
            return _canDrawPlot;
        }
        set
        {
            _canDrawPlot = value;
            OnPropertyChanged(new PropertyChangedEventArgs("CanDrawPlot"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}
</code>```

I want to update my Datagrid CheckBox IsEnabled state based on CanDrawPlot property of this model. But this doesn't seem to work. XAML for DataGrid:

```<code>                    <DataGrid IsReadOnly="True" AutoGenerateColumns="False" SelectionMode="Single" Margin="0" BorderThickness="0" ClipToBounds="True" ItemsSource="{Binding User.UserSeries}" SelectionChanged="SeriesDataGrid_OnSelectionChanged" Name="SeriesDataGrid">
                        <DataGrid.Columns>
                            <DataGridTemplateColumn CanUserResize="False">
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <CheckBox IsEnabled="{Binding CanDrawPlot}" Checked="ChooseSeries_Checked" x:Name="ChooseSeries" Height="25"/>
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>
                        </DataGrid.Columns>
                    </DataGrid>
</code>```

I have class User. It contains UserSeries. UserSeries has property CanDrawPlot:

```<code>public class User : INotifyPropertyChanged
{
    private ObservableCollection<Series> _userSeries;
    public ObservableCollection<Series> UserSeries
    {
        get
        {
            return _userSeries;
        }
        set
        {
            _userSeries = value;
            OnPropertyChanged(new PropertyChangedEventArgs("UserSeries"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}
</code>```

答:
You need to add the following lines to your code

In the xaml:
You need to add to bindinig the UpdateSourceTrigger

```<code><CheckBox IsEnabled="{Binding CanDrawPlot,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Checked="ChooseSeries_Checked" x:Name="ChooseSeries" Height="25"/>
</code>```

And in the xaml.cs you need to creat an instance of Series class

For example:

```<code>private Series series = new Series ();
</code>```

And in the constructor of the xaml.cs you need to write:

```<code>DataContext = series;
</code>```

Successfully.

Body:
I have a model, which contains CanDrawProperty. I want to bind this property to IsEnabled property of DataGrid CheckBox:

public class Series : INotifyPropertyChanged
{
    private ObservableCollection<DropPhoto> _dropPhotosSeries;
    public ObservableCollection<DropPhoto> DropPhotosSeries
    {
        get
        {
            return _dropPhotosSeries;
        }
        set
        {
            _dropPhotosSeries = value;
            OnPropertyChanged(new PropertyChangedEventArgs("DropPhotosSeries"));
        }
    }

    private bool _canDrawPlot;
    public bool CanDrawPlot
    {
        get
        {
            if (_dropPhotosSeries?.Where(x => x.Drop.RadiusInMeters != null).ToList().Count > 1)
            {
                _canDrawPlot = true;
                return _canDrawPlot;
            }

            _canDrawPlot = false;
            return _canDrawPlot;
        }
        set
        {
            _canDrawPlot = value;
            OnPropertyChanged(new PropertyChangedEventArgs("CanDrawPlot"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}

I want to update my Datagrid CheckBox IsEnabled state based on CanDrawPlot property of this model. But this doesn't seem to work. XAML for DataGrid:

                    <DataGrid IsReadOnly="True" AutoGenerateColumns="False" SelectionMode="Single" Margin="0" BorderThickness="0" ClipToBounds="True" ItemsSource="{Binding User.UserSeries}" SelectionChanged="SeriesDataGrid_OnSelectionChanged" Name="SeriesDataGrid">
                        <DataGrid.Columns>
                            <DataGridTemplateColumn CanUserResize="False">
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <CheckBox IsEnabled="{Binding CanDrawPlot}" Checked="ChooseSeries_Checked" x:Name="ChooseSeries" Height="25"/>
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>
                        </DataGrid.Columns>
                    </DataGrid>

I have class User. It contains UserSeries. UserSeries has property CanDrawPlot:

public class User : INotifyPropertyChanged
{
    private ObservableCollection<Series> _userSeries;
    public ObservableCollection<Series> UserSeries
    {
        get
        {
            return _userSeries;
        }
        set
        {
            _userSeries = value;
            OnPropertyChanged(new PropertyChangedEventArgs("UserSeries"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChanged?.Invoke(this, e);
    }
}

Body:
You need to add the following lines to your code

In the xaml:
You need to add to bindinig the UpdateSourceTrigger

<CheckBox IsEnabled="{Binding CanDrawPlot,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Checked="ChooseSeries_Checked" x:Name="ChooseSeries" Height="25"/>

And in the xaml.cs you need to creat an instance of Series class

For example:

private Series series = new Series ();

And in the constructor of the xaml.cs you need to write:

DataContext = series;

Successfully.


问:
Combine ADFS Authentication and JWT Bearer on ASP.Net Application
I have a web API written in ASP.NET and frontend written in Angular. Authentication on the API side can be configured to use either Windows Authentication, ADFS Authentication or JWT Bearer. But for a particular deployment, only one type of authentication is supported.

For the ADFS authentication I am using angular-oauth2-oidc on the Angular side.

On the API side, this is how I am configuring the ADFS authentication in the startup.cs file.

```<code>    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseActiveDirectoryFederationServicesBearerAuthentication
            (new ActiveDirectoryFederationServicesBearerAuthenticationOptions
            {
                BackchannelCertificateValidator = new CertificateValidator(),
                MetadataEndpoint = System.Configuration.ConfigurationManager.AppSettings["ida:ADFSMetadata"],
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidAudience = System.Configuration.ConfigurationManager.AppSettings["ida:Audience"],
                    ValidIssuer = System.Configuration.ConfigurationManager.AppSettings["ida:ValidIssuer"]
                },
                Provider = new OAuthBearerAuthenticationProvider()
                {
                    OnValidateIdentity = async context =>
                    {
                        var identity = context.Ticket.Identity;
                        var emailAddress = identity.FindFirst(ClaimTypes.Email).Value;
                        using (AuthRepository repo = new AuthRepository())
                        {
                            var userManager = repo.GetUserManager();
                            var aspNetUser = userManager.FindByEmailAsync(emailAddress).GetAwaiter().GetResult();
                            if (aspNetUser != null)
                            {
                                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, aspNetUser.Id));
                                await ProfileManager.AddClaimsToIdentity(identity, aspNetUser.SelectedProfile);
                            }
                        }
                    }
                }
            });
    }
</code>```

What I want is to combine ADFS authentication with JWT Bearer in such a way that if the entered email address is associated with my company domain like "email@mycompany.com", it authenticates against the ADFS and if it's any other email, it uses JWT Bearer authentication.

I know different type of authentications can be combined in ASP.NET Core (example here) but my API is not built using the Core.

I have tried to find the same feature for ASP.NET but I couldn't find one. I would like to know if this is possible to achieve and if yes, I will really appreciate if someone can give me a pointer.

答:
On this question:

What I want is to combine ADFS authentication with JWT Bearer in such a way that if the entered email address is associated with my company domain like "email@mycompany.com", it authenticates against the ADFS and if it's any other email, it uses JWT Bearer authentication.

As far as I know, it is possible.

Have you tried Microsoft Identity Platform? This is a specific Azure SDK for managing identities, including support for ADFS 3.0 in Windows Server 2012 and later.
It is also easier to use, because this MIcrosoft Identity Platform is using OpenIDConnect with OAuth 2.0, therefore you can use ADFS that has JWT bearer.

This is the official docs page: https://learn.microsoft.com/en-us/azure/active-directory/develop/

The landing page has various samples for you to get started. Since you are using .NET Core, the Microsoft Identity Platform SDK has sample that you can use is the sample using .NET Core:
https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-aspnet-core-webapp

This is a github repo that contains various sample beside that tutorial:
https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2

UPDATE 1:
Current documentation of ADFS in Windows Server 2016 only shows support for OAuth2/OpenIDConnect, and it is using JWT Bearer:
https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/development/ad-fs-openid-connect-oauth-concepts

I have searched for specific "ADFS Bearer Token Authentication" in the MS official documentation, and it's not available at all. All of the current doc is mentioning about ADFS 3.0 and later (including ADFS in Windows Server 2016 and 2019) is using OAuth2/OpenIDConnect.

Body:
I have a web API written in ASP.NET and frontend written in Angular. Authentication on the API side can be configured to use either Windows Authentication, ADFS Authentication or JWT Bearer. But for a particular deployment, only one type of authentication is supported.

For the ADFS authentication I am using angular-oauth2-oidc on the Angular side.

On the API side, this is how I am configuring the ADFS authentication in the startup.cs file.

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseActiveDirectoryFederationServicesBearerAuthentication
            (new ActiveDirectoryFederationServicesBearerAuthenticationOptions
            {
                BackchannelCertificateValidator = new CertificateValidator(),
                MetadataEndpoint = System.Configuration.ConfigurationManager.AppSettings["ida:ADFSMetadata"],
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidAudience = System.Configuration.ConfigurationManager.AppSettings["ida:Audience"],
                    ValidIssuer = System.Configuration.ConfigurationManager.AppSettings["ida:ValidIssuer"]
                },
                Provider = new OAuthBearerAuthenticationProvider()
                {
                    OnValidateIdentity = async context =>
                    {
                        var identity = context.Ticket.Identity;
                        var emailAddress = identity.FindFirst(ClaimTypes.Email).Value;
                        using (AuthRepository repo = new AuthRepository())
                        {
                            var userManager = repo.GetUserManager();
                            var aspNetUser = userManager.FindByEmailAsync(emailAddress).GetAwaiter().GetResult();
                            if (aspNetUser != null)
                            {
                                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, aspNetUser.Id));
                                await ProfileManager.AddClaimsToIdentity(identity, aspNetUser.SelectedProfile);
                            }
                        }
                    }
                }
            });
    }

What I want is to combine ADFS authentication with JWT Bearer in such a way that if the entered email address is associated with my company domain like "email@mycompany.com", it authenticates against the ADFS and if it's any other email, it uses JWT Bearer authentication.

I know different type of authentications can be combined in ASP.NET Core (example here) but my API is not built using the Core.

I have tried to find the same feature for ASP.NET but I couldn't find one. I would like to know if this is possible to achieve and if yes, I will really appreciate if someone can give me a pointer.


问:
How to reduce context switches when traversing a Seq of Scala futures
I have a program that needs to fetch a large number (~300) records and do some operation on them. The records are cached, so it take no CPU and almost no time. However, at 50% CPU util the p95 latency is 40ms. When looking at the stack trace, threads spend most of the time in Parked state,  and the most used method is 'java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)'. So I am guesssing most of the time is used on context switching

```<code> def getObject(id: Ing): Future[SomeObject] = ??? // Can make a call to DB, but usually cached
 val ids: Seq[Int] = ??? // 300 ints

 Future.iterate(ids)(getObject)
</code>```

How can I improve the performance? I have tried Akka FastFuture, and tried using both global (work stealing thread pool) and Akka default dispatcher (ForkJoin).

Specifically
1) What can I do if we assume that some of the getObject calls blocking (cache miss)
2) What can I do if we assume that all getObject calls are served from cache (I can pre-wark the cache, and use background refresh )

p.s
Heap dump: https://heaphero.io/my-heap-report.jsp?p=YXJjaGl2ZWQvMjAyMC8wMi8xOC8tLWJhc2UtZm9yay56aXAtNC0yNi02Lmpzb24tLQ==

答:
A neat trick to avoid context switching when using Scala Futures consists in using parasitic as an ExecutionContext, which "steals execution time from other threads by having its Runnables run on the Thread which calls execute and then yielding back control to the caller after all its Runnables have been executed". parasitic is available since Scala 2.13 but you can easily understand it and port it to pre-2.13 projects by looking at its code (here for version 2.13.1). A naive but working implementation for pre-2.13 projects would simply run the Runnables without taking care of dispatching them on a thread, which does the trick, as in the following snippet:

```<code>object parasitic212 extends ExecutionContext {

  override def execute(runnable: Runnable): Unit =
    runnable.run()

  // reporting failures is left as an exercise for the reader
  override def reportFailure(cause: Throwable): Unit = ???

}
</code>```

The parasitic implementation is of course more nuanced. For more insight into the reasoning and some caveats about its usage I would suggest you refer to the PR the introduced parasitic as a publicly available API (it was already implemented but reserved for internal use).

Quoting the original PR description:

A synchronous, trampolining, ExecutionContext has been used for a long time within the Future implementation to run controlled logic as cheaply as possible.

I believe that there is a significant number of use-cases where it makes sense, for efficiency, to execute logic synchronously in a safe(-ish) way without having users to implement the logic for that ExecutionContext themselves—it is tricky to implement to say the least.

It is important to remember that ExecutionContext should be supplied via an implicit parameter, so that the caller can decide where logic should be executed. The use of ExecutionContext.parasitic means that logic may end up running on Threads/Pools that were not designed or intended to run specified logic. For instance, you may end up running CPU-bound logic on an IO-designed pool or vice versa. So use of parasitic is only advisable when it really makes sense. There is also a real risk of hitting StackOverflowErrors for certain patterns of nested invocations where a deep call chain ends up in the parasitic executor, leading to even more stack usage in the subsequent execution. Currently the parasitic ExecutionContext will allow a nested sequence of invocations at max 16, this may be changed in the future if it is discovered to cause problems.

As suggested in the official documentation for parasitic, you're advised to only use this when the executed code quickly returns control to the caller. Here is the documentation quoted for version 2.13.1:

WARNING: Only ever execute logic which will quickly return control to the caller.

This ExecutionContext steals execution time from other threads by having its Runnables run on the Thread which calls execute and then yielding back control to the caller after all its Runnables have been executed. Nested invocations of execute will be trampolined to prevent uncontrolled stack space growth.

When using parasitic with abstractions such as Future it will in many cases be non-deterministic as to which Thread will be executing the logic, as it depends on when/if that Future is completed.

Do not call any blocking code in the Runnables submitted to this ExecutionContext as it will prevent progress by other enqueued Runnables and the calling Thread.

Symptoms of misuse of this ExecutionContext include, but are not limited to, deadlocks and severe performance problems.

Any NonFatal or InterruptedExceptions will be reported to the defaultReporter.

Body:
I have a program that needs to fetch a large number (~300) records and do some operation on them. The records are cached, so it take no CPU and almost no time. However, at 50% CPU util the p95 latency is 40ms. When looking at the stack trace, threads spend most of the time in Parked state,  and the most used method is 'java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)'. So I am guesssing most of the time is used on context switching

 def getObject(id: Ing): Future[SomeObject] = ??? // Can make a call to DB, but usually cached
 val ids: Seq[Int] = ??? // 300 ints

 Future.iterate(ids)(getObject)

How can I improve the performance? I have tried Akka FastFuture, and tried using both global (work stealing thread pool) and Akka default dispatcher (ForkJoin).

Specifically
1) What can I do if we assume that some of the getObject calls blocking (cache miss)
2) What can I do if we assume that all getObject calls are served from cache (I can pre-wark the cache, and use background refresh )

p.s
Heap dump: https://heaphero.io/my-heap-report.jsp?p=YXJjaGl2ZWQvMjAyMC8wMi8xOC8tLWJhc2UtZm9yay56aXAtNC0yNi02Lmpzb24tLQ==

Body:
A neat trick to avoid context switching when using Scala Futures consists in using parasitic as an ExecutionContext, which "steals execution time from other threads by having its Runnables run on the Thread which calls execute and then yielding back control to the caller after all its Runnables have been executed". parasitic is available since Scala 2.13 but you can easily understand it and port it to pre-2.13 projects by looking at its code (here for version 2.13.1). A naive but working implementation for pre-2.13 projects would simply run the Runnables without taking care of dispatching them on a thread, which does the trick, as in the following snippet:

object parasitic212 extends ExecutionContext {

  override def execute(runnable: Runnable): Unit =
    runnable.run()

  // reporting failures is left as an exercise for the reader
  override def reportFailure(cause: Throwable): Unit = ???

}

The parasitic implementation is of course more nuanced. For more insight into the reasoning and some caveats about its usage I would suggest you refer to the PR the introduced parasitic as a publicly available API (it was already implemented but reserved for internal use).

Quoting the original PR description:

A synchronous, trampolining, ExecutionContext has been used for a long time within the Future implementation to run controlled logic as cheaply as possible.

I believe that there is a significant number of use-cases where it makes sense, for efficiency, to execute logic synchronously in a safe(-ish) way without having users to implement the logic for that ExecutionContext themselves—it is tricky to implement to say the least.

It is important to remember that ExecutionContext should be supplied via an implicit parameter, so that the caller can decide where logic should be executed. The use of ExecutionContext.parasitic means that logic may end up running on Threads/Pools that were not designed or intended to run specified logic. For instance, you may end up running CPU-bound logic on an IO-designed pool or vice versa. So use of parasitic is only advisable when it really makes sense. There is also a real risk of hitting StackOverflowErrors for certain patterns of nested invocations where a deep call chain ends up in the parasitic executor, leading to even more stack usage in the subsequent execution. Currently the parasitic ExecutionContext will allow a nested sequence of invocations at max 16, this may be changed in the future if it is discovered to cause problems.

As suggested in the official documentation for parasitic, you're advised to only use this when the executed code quickly returns control to the caller. Here is the documentation quoted for version 2.13.1:

WARNING: Only ever execute logic which will quickly return control to the caller.

This ExecutionContext steals execution time from other threads by having its Runnables run on the Thread which calls execute and then yielding back control to the caller after all its Runnables have been executed. Nested invocations of execute will be trampolined to prevent uncontrolled stack space growth.

When using parasitic with abstractions such as Future it will in many cases be non-deterministic as to which Thread will be executing the logic, as it depends on when/if that Future is completed.

Do not call any blocking code in the Runnables submitted to this ExecutionContext as it will prevent progress by other enqueued Runnables and the calling Thread.

Symptoms of misuse of this ExecutionContext include, but are not limited to, deadlocks and severe performance problems.

Any NonFatal or InterruptedExceptions will be reported to the defaultReporter.


问:
Pandas remove the row index from the pandas dataframe
i have a dataframe with the data as follows

```<code>  id  Name   Age
0  1  XXX    30
</code>```

and i have to remove the 0(the row index value) from the dataframe.

I have tried the folowing

```<code>df.reset_index(inplace=True) # Resets the index, makes factor a column
df.drop("Factor",axis=1,inplace=True)
</code>```

but it is not removing the 0.

i want output like:

```<code>id  Name   Age
 1  XXX    30
</code>```

答:
Try this one:</p>

```<code>df.set_index('id', inplace=True)
</code>```

Body:
i have a dataframe with the data as follows

  id  Name   Age
0  1  XXX    30

and i have to remove the 0(the row index value) from the dataframe.

I have tried the folowing

df.reset_index(inplace=True) # Resets the index, makes factor a column
df.drop("Factor",axis=1,inplace=True)

but it is not removing the 0.

i want output like:

id  Name   Age
 1  XXX    30

Body:
Try this one:

df.set_index('id', inplace=True)


问:
Calling multiple API requests and waiting for response using Kotlin Coroutines
Code changes applied.

I followed a guide on how to create a kotlin coroutine and do network request and ended up with:

```<code>suspend fun <T : Any> safeApiCall(call: suspend () -> Response<T>): ApiResult<T> {
    return safeApiResult(call)
}

private suspend fun <T: Any> safeApiResult(call: suspend ()-> Response<T>) : ApiResult<T>{
    val response = call.invoke()

    return if (response.isSuccessful) {
        val body = response.body()

        if (body == null) {
            ApiResult.Error(response.code())
        } else {
            ApiResult.Success(body)
        }
    } else {
        ApiResult.Error(response.code())
    }
}

suspend fun getSnappedPoints(path: String): ApiResult<SnappedPointsData> {
    return safeApiCall(
        call = { googleRoadsService.getSnappedPoints(path).await()}
    )
}
</code>```

and calling the network request looks like this:

```<code>private fun getSnappedPoints() {
    val paths = Utils.getPathFromLocations(locations)

    CoroutineScope(Dispatchers.IO).launch {
        val results = paths.map {
            async { googleRoadsRepository.getSnappedPoints(it) }
        }.awaitAll()

        Timber.i("results: ${results.size}")

        val snappedPoints = ArrayList<LocationSnap>()

        results.forEach {
            if (it is ApiResult.Success) {
                snappedPoints.addAll(it.data.snappedPoints)
            }
        }

        withContext(Dispatchers.Main) {
            if (snappedPoints.isNotEmpty()) {
                drawPolyline(snappedPoints)
            } else {
                showError()
            }
        }
    }
}
</code>```

Current problem:

The function getSnappedPoints() is called when I click on specific item. For the very first time it actually calls google API and result is > 0 (size), but if I go back and click second time on the same/other item, getSnappedPoints() is called, paths is not Empty, but somehow it does not call googleRoadsRepository.getSnappedPoints(it) and kinda skips that step in debug and all I can see is that result is always 0. What could cause this?

答:
While you at IO thread so what is the necessity of using async + await? At the IO scope, you are free to suspend and wait for the response.

Try this one and notify me to know what will the result?

```<code>private fun getSnappedPoints() {
val paths = Utils.getPathFromLocations(locations)

CoroutineScope(Dispatchers.IO).launch {
    val results = paths.map {
        googleRoadsRepository.getSnappedPoints(it)
    }

    // rest of you code...
}
</code>```

Body:
Code changes applied.

I followed a guide on how to create a kotlin coroutine and do network request and ended up with:

suspend fun <T : Any> safeApiCall(call: suspend () -> Response<T>): ApiResult<T> {
    return safeApiResult(call)
}

private suspend fun <T: Any> safeApiResult(call: suspend ()-> Response<T>) : ApiResult<T>{
    val response = call.invoke()

    return if (response.isSuccessful) {
        val body = response.body()

        if (body == null) {
            ApiResult.Error(response.code())
        } else {
            ApiResult.Success(body)
        }
    } else {
        ApiResult.Error(response.code())
    }
}

suspend fun getSnappedPoints(path: String): ApiResult<SnappedPointsData> {
    return safeApiCall(
        call = { googleRoadsService.getSnappedPoints(path).await()}
    )
}

and calling the network request looks like this:

private fun getSnappedPoints() {
    val paths = Utils.getPathFromLocations(locations)

    CoroutineScope(Dispatchers.IO).launch {
        val results = paths.map {
            async { googleRoadsRepository.getSnappedPoints(it) }
        }.awaitAll()

        Timber.i("results: ${results.size}")

        val snappedPoints = ArrayList<LocationSnap>()

        results.forEach {
            if (it is ApiResult.Success) {
                snappedPoints.addAll(it.data.snappedPoints)
            }
        }

        withContext(Dispatchers.Main) {
            if (snappedPoints.isNotEmpty()) {
                drawPolyline(snappedPoints)
            } else {
                showError()
            }
        }
    }
}

Current problem:

The function getSnappedPoints() is called when I click on specific item. For the very first time it actually calls google API and result is > 0 (size), but if I go back and click second time on the same/other item, getSnappedPoints() is called, paths is not Empty, but somehow it does not call googleRoadsRepository.getSnappedPoints(it) and kinda skips that step in debug and all I can see is that result is always 0. What could cause this?

Body:
While you at IO thread so what is the necessity of using async + await? At the IO scope, you are free to suspend and wait for the response.

Try this one and notify me to know what will the result?

private fun getSnappedPoints() {
val paths = Utils.getPathFromLocations(locations)

CoroutineScope(Dispatchers.IO).launch {
    val results = paths.map {
        googleRoadsRepository.getSnappedPoints(it)
    }

    // rest of you code...
}


问:
Execute PHP command from JavaScript
I'm working on Windows. I'm trying to call a specific form (which is saved on different location) with JavaScript/PHP.

File D:\Test\Form.php looks like this:

```<code><form action="D:\Test\submit.php" method="post">
    <select name="application">
        <option value="name">Enter your name</option>
        <option value="last name">Enter your last name</option>
    </select>
</form>
</code>```

My main page looks like this:

```<code><html>
    <script srv="js/jquery.js"></script>
    <body>
        <form method = 'post'>
            <select>
                <option value="application">application</option>
                <option value="payment">payment</option>
            </select>
        </form>

        <button onClick="createDiv">click me</button>

        <p id="demo"></p>
    </body>
</html>

<?php
    $htmlstring = shell_exec("type D:\Test\Form.php");
    //$htmlstring = "hello world";
?>
</code>```

I have this JavaScript:

```<code><script>
function createDiv()
{
    var htmlstring = "<?php echo $htmlstring; ?>";
    document.getElementById("demo").innerHTML = htmlstring;
}
</script>
</code>```

When I press F12 I can see that the form has been generated but I cannot see it on the page when I click the button, however when I uncomment the "hello world" it will print it and everything seems to be working just fine except printing the form itself...

The main idea was to generate a button that will "add" the form I was choosing from the list endlessly (either: "application/payment")

How to create this either using JS or PHP itself?

答:
so thanks to Brett Gregson, i was managed to solve my issue with an ajax.
sadly i dont understand how it works completly but i will make some reading regarding and hope to chat with him and he might explain that to me, for those that understand how ajax works and looking for the same solution here is the code:

```<code><html>
<script srv="js/jquery.js"></script>
    <body>
        <form method='post'>
            <select>
                <option value="application">application</option>
                <option value="payment">payment</option>
            </select>
        </form>
        <button class="createDiv">Click me</button>
        <p id="demo"></p> #this also can be <div id="demo"></div>
    </body>
</html>

<script>
    $(".createDiv").click(function(){
        $.get("Test\Form.php",function(output){
            $("#demo").append(output);
        });
    });
</script>
</code>```

I'm pretty sure we can pass parameters and create some if loops, all i've left to figure is why when i press F12 i don't see the "form" appears there.

hope it will help others.

Title: Execute PHP command from JavaScript

Body:
I'm working on Windows. I'm trying to call a specific form (which is saved on different location) with JavaScript/PHP.

File D:\Test\Form.php looks like this:

<form action="D:\Test\submit.php" method="post">
    <select name="application">
        <option value="name">Enter your name</option>
        <option value="last name">Enter your last name</option>
    </select>
</form>

My main page looks like this:

        <form method = 'post'>
            <select>
                <option value="application">application</option>
                <option value="payment">payment</option>
            </select>
        </form>

        <button onClick="createDiv">click me</button>

<?php
    $htmlstring = shell_exec("type D:\Test\Form.php");
    //$htmlstring = "hello world";
?>

I have this JavaScript:

When I press F12 I can see that the form has been generated but I cannot see it on the page when I click the button, however when I uncomment the "hello world" it will print it and everything seems to be working just fine except printing the form itself...

The main idea was to generate a button that will "add" the form I was choosing from the list endlessly (either: "application/payment")

How to create this either using JS or PHP itself?

Body:
so thanks to Brett Gregson, i was managed to solve my issue with an ajax.
sadly i dont understand how it works completly but i will make some reading regarding and hope to chat with him and he might explain that to me, for those that understand how ajax works and looking for the same solution here is the code:

<html>
<script srv="js/jquery.js"></script>
    <body>
        <form method='post'>
            <select>
                <option value="application">application</option>
                <option value="payment">payment</option>
            </select>
        </form>
        <button class="createDiv">Click me</button>
        <p id="demo"></p> #this also can be <div id="demo"></div>
    </body>
</html>

<script>
    $(".createDiv").click(function(){
        $.get("Test\Form.php",function(output){
            $("#demo").append(output);
        });
    });
</script>

I'm pretty sure we can pass parameters and create some if loops, all i've left to figure is why when i press F12 i don't see the "form" appears there.

hope it will help others.


问:
Find pixel indices within a shape: Opencv and Python
Suppose I have a mask of a hollow, curved (and not necessarily convex) shape that I've received from my pre-processing steps:

I now want to try and select all pixels that occur inside that shape and add them to the mask, as so:

How can I do this in Python?

Code for generating the examples:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Parameters for creating the circle
COLOR_BLUE = (255, 0, 0)
IMAGE_SHAPE = (256, 256, 3)
CIRCLE_CENTER = tuple(np.array(IMAGE_SHAPE) // 2)[:-1]
CIRCLE_RADIUS = 30
LINE_THICKNESS = 5 # Change to -1 for example of filled circle

# Draw on a circle
img = np.zeros(IMAGE_SHAPE, dtype=np.uint8)
img_circle = cv2.circle(img, CIRCLE_CENTER, CIRCLE_RADIUS, COLOR_BLUE, LINE_THICKNESS)
circle_mask = img_circle[:, :, 0]

# Show the image
plt.axis("off")
plt.imshow(circle_mask)
plt.show()
```

答: You can also use scipy.ndimage.binary_fill_holes.


问:
How to get the index of a selected row in row command in asp.net
I want to get the index of the selected row in my grid view.

This is the command im using on row_command of  my gridview

if (e.CommandName == "Select")
{
    iCol = gtsk.GetColumnIndexByDBName(grdUser, "UserID");
    if (iCol != -1)
    {
        txtUserName.Text = Server.HtmlDecode(grdUser.Rows[inDx].Cells[iCol].Text.ToString().Trim());
        txtUserName.ToolTip = Server.HtmlDecode(grdUser.Rows[inDx].Cells[iCol].Text.ToString().Trim());
    }

    iCol = gtsk.GetColumnIndexByDBName(grdUser, "UserName");
    if (iCol != -1)
    {
         txtUserName.Text = Server.HtmlDecode(grdUser.Rows[inDx].Cells[iCol].Text.ToString().Trim());
    }

    iCol = gtsk.GetColumnIndexByDBName(grdUser, "FullName");
    if (iCol != -1)
    {
        txtFullName.Text = Server.HtmlDecode(grdUser.Rows[inDx].Cells[iCol].Text.ToString().Trim());
    }

    iCol = gtsk.GetColumnIndexByDBName(grdUser, "RoleCode");
    if (iCol != -1)
    {
        ddlRoleUser.SelectedValue = Server.HtmlDecode(grdUser.Rows[inDx].Cells[iCol].Text.ToString().Trim());
    }

    //iCol = gtsk.GetColumnIndexByDBName(grdUser, "Status");
    //if (iCol != -1) { chkActive.Checked = ((CheckBox)grdUser.Rows[inDx].Cells[iCol].Controls[0]).Checked; }
}
```

答:
You can Use get the index of a selected row on row_command like this</p>

```<code>int iCol = -1;
        int inDx = Convert.ToInt32(e.CommandArgument.ToString());
</code>```

Body:
You can Use get the index of a selected row on row_command like this

int iCol = -1;
        int inDx = Convert.ToInt32(e.CommandArgument.ToString());