问:
Creating a Dropdown Menu from Database
I'm trying to create a Dropdown menu from the table Holidays for the column name. But I'm too dumb to make it work.

I already tried some of the things people wrote but most of them have a second database. But I only have one.

My goal is to show all the names from the Holiday name column so, if I create a new holiday, I just get the name of the date from the Dropdown menu and don't need to write it down every time.

HolidaysController.php

public function index()
    {
        $holidays = $this->paginate($this->Holidays);
        $this->set(compact('holidays'));
        $name =$this->name->find('list');
        $this->set(compact('name'));
    }
```

<p>Holidays add.ctp</p>

<pre class="lang-php prettyprint-override"><code>        <?php
            echo $this->Form->control('date', array('label' => __('Datum', true)));
            echo $this->Form->control('name', ['options' => $name, 'empty' => true]);
        ?>
</code>```

I thought he would show me now a dropdown list from the names of the holidays but i just have a normal field and get the error:

Notice (8): Undefined variable: name [APP/Template\Holidays\add.ctp, line 19]

I'm probably missing something really basic here, I'm still learning coding so if I missed any information, you need, just let me know.

EDIT:

My add function after the edit

HolidaysController

public function add()
    {
        $name =$this->name->find('list');
        $this->set(compact('name'));
        $holiday = $this->Holidays->newEntity();
        if ($this->request->is('post')) {
            $holiday = $this->Holidays->patchEntity($holiday, $this->request->getData());
            if ($this->Holidays->save($holiday)) {
                $this->Flash->success(__('Der Feiertag wurde gespeichert.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Der Feiertag wurde nicht gespeichert. Bitte, versuchen sie es erneut.'));
        }
        $this->set(compact('holiday'));
    }
```

答:
You must find and set list in your add() method, like :

```<code>public function add()
{
    // your add code here .. then:
    $name =$this->Holidays->find('list');
    $this->set(compact('name'));
}
</code>```

By default every controller method has own view template:

```<code>index() >> index.ctp
add() >> add.ctp
edit() >> edit.ctp
myCustomMethod() >> my_custom_method.ctp
// ...
</code>```

EDIT:

If I add your code to function add() i get an Error: Call to a member
  function find() on string.

I copy code from your question. But you must update:

from: $this->name->find('list'); to

```<code>$this->Holidays->find('list', [
    'keyField' => 'name',
]);
</code>```

Title: Creating a Dropdown Menu from Database

Body:
I'm trying to create a Dropdown menu from the table Holidays for the column name. But I'm too dumb to make it work.

I already tried some of the things people wrote but most of them have a second database. But I only have one.

My goal is to show all the names from the Holiday name column so, if I create a new holiday, I just get the name of the date from the Dropdown menu and don't need to write it down every time.

HolidaysController.php

public function index()
    {
        $holidays = $this->paginate($this->Holidays);
        $this->set(compact('holidays'));
        $name =$this->name->find('list');
        $this->set(compact('name'));
    }

Holidays add.ctp

        <?php
            echo $this->Form->control('date', array('label' => __('Datum', true)));
            echo $this->Form->control('name', ['options' => $name, 'empty' => true]);
        ?>

I thought he would show me now a dropdown list from the names of the holidays but i just have a normal field and get the error:

Notice (8): Undefined variable: name [APP/Template\Holidays\add.ctp, line 19]

I'm probably missing something really basic here, I'm still learning coding so if I missed any information, you need, just let me know.

EDIT:

My add function after the edit

HolidaysController

public function add()
    {
        $name =$this->name->find('list');
        $this->set(compact('name'));
        $holiday = $this->Holidays->newEntity();
        if ($this->request->is('post')) {
            $holiday = $this->Holidays->patchEntity($holiday, $this->request->getData());
            if ($this->Holidays->save($holiday)) {
                $this->Flash->success(__('Der Feiertag wurde gespeichert.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Der Feiertag wurde nicht gespeichert. Bitte, versuchen sie es erneut.'));
        }
        $this->set(compact('holiday'));
    }

Body:
You must find and set list in your add() method, like :

public function add()
{
    // your add code here .. then:
    $name =$this->Holidays->find('list');
    $this->set(compact('name'));
}

By default every controller method has own view template:

index() >> index.ctp
add() >> add.ctp
edit() >> edit.ctp
myCustomMethod() >> my_custom_method.ctp
// ...

EDIT:

If I add your code to function add() i get an Error: Call to a member
  function find() on string.

I copy code from your question. But you must update:

from: $this->name->find('list'); to

$this->Holidays->find('list', [
    'keyField' => 'name',
]);


来源: stackexchange

问:
Rails meta programming and performance
Rails conventions force framework and gem writers to make extensive use of reflection/meta programming. I've always assumed meta programming to be less efficient, and with the trend of using an ever growing number of gems, the question is - whats the PERFORMANCE impact? </p>

答:
Programmer productivity >> Software Performance (usually)

Really, don't worry about this... in practice correct algorithms, correct architecture, correct database model and so on are much more important than pure language performance...

X effort not spent on fighting the language (java xml hell, c compilation) is effort spent on designing better algorithms, UX which results in better and more user friendlier application

ContentLicense: CC BY-SA 3.0

Title: Rails meta programming and performance


问:
I want to delete selected data from the list using the delete button in action bar

I'm new to flutter and  I want to delete the selected values from the
  list,but I don't know how to delete selected Items,can anyone help?

I have taken icon button in Appbar and I tried to setState in it by
  using  the .removelast() command,but I want to select the Item then
  delete it.

Code :

```<code>class DemoPage extends State<MyHomePage> {
  TextEditingController Controller = TextEditingController();
  List<String> msg = List();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return Scaffold(
      appBar: AppBar(
        title: Text('Demo_App'),
        actions: <Widget>[
          IconButton(icon: Icon(Icons.delete),
              onPressed: (){
                  setState(() {
                    msg.removeLast();
                  });
              }),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            alignment: Alignment.topLeft,
            margin: EdgeInsets.only(right: 150.0,top: 10.0,left: 8.0),
            child:TextField(
                controller: Controller,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'please enter your name',
                ),
              ),

          ),
          Container(
            alignment: Alignment.topRight,
            margin: EdgeInsets.only(left: 250.0,right: 10.0),
            child: RaisedButton(
              onPressed: () {
                setState(() {
                  msg.add(Controller.text);
                  Controller.clear();
                });
              },
              child: Text('Add'),
            ),
          ),
          Expanded(
            flex: 2,
              child: Container(
                child: Card(
                  margin: EdgeInsets.all(8.0),
                  child: ListView.builder(
                    itemCount: msg.length,
                    itemBuilder: (context, index){
                      if(index.isInfinite){
                        return Divider();
                      }
                      return ListTile(
                        title: Text(msg[index]),
                      );
                    },),
                ),
              )),
        ],
      ),
    );
  }

}
</code>```

I want to select the data and then delete it using the icon Button in
  the AppBar.

答:
Lets assume you want to select your items by a single click.

Take a separate a list indexList and each time you select an item, you store the clicked index into indexList.

Then upon clicking delete button run a loop on indexList and remove items from your itemList using the stored indexes.

clean indexList
update your state

```<code>class DemoPage extends State<MyHomePage> {
  TextEditingController Controller = TextEditingController();
  List<String> msg = List();
  List<int> selectedItems = List();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return Scaffold(
      appBar: AppBar(
        title: Text('Demo_App'),

    actions: <Widget>[
      IconButton(
          icon: Icon(Icons.delete),
          onPressed: () {
            setState(() {
              msg.removeLast();
            });
          }),
    ],
  ),
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    mainAxisSize: MainAxisSize.min,
    children: <Widget>[
      Container(
        alignment: Alignment.topLeft,
        margin: EdgeInsets.only(right: 150.0, top: 10.0, left: 8.0),
        child: TextField(
          controller: Controller,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            hintText: 'please enter your name',
          ),
        ),
      ),
      Container(
        alignment: Alignment.topRight,
        margin: EdgeInsets.only(left: 250.0, right: 10.0),
        child: RaisedButton(
          onPressed: () {
            setState(() {
              msg.add(Controller.text);
              Controller.clear();
            });
          },
          child: Text('Add'),
        ),
      ),
      Expanded(
          flex: 2,
          child: Container(
            child: Card(
              margin: EdgeInsets.all(8.0),
              child: ListView.builder(
                  itemCount: msg.length,
                  itemBuilder: (context, index) {
                    return new GestureDetector(
                        onLongPress: () {
                          if(selectedItems.contains(index))
                            selectedItems.remove(index);
                          else
                            selectedItems.add(index);
                        },
                        onTap: () {
                          if(selectedItems.contains(index))
                            selectedItems.remove(index);
                          else
                            selectedItems.add(index);
                        },
                        child: index.isInfinite
                            ? Divider()
                            : ListTile(
                                title: Text(msg[index]),
                              ));
                  }),
            ),
          )),
    ],
  ),
);
  }

  void _deleteItems(){ // call _deleteItems() on clicking delete button

    setState(() {
      //set your state
      for (final index in selectedItems)
          msg.removeAt(index);
      selectedItems.clear();
    });
  }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to flutter and  I want to delete the selected values from the
  list,but I don't know how to delete selected Items,can anyone help?

I have taken icon button in Appbar and I tried to setState in it by
  using  the .removelast() command,but I want to select the Item then
  delete it.

Code :

class DemoPage extends State<MyHomePage> {
  TextEditingController Controller = TextEditingController();
  List<String> msg = List();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return Scaffold(
      appBar: AppBar(
        title: Text('Demo_App'),
        actions: <Widget>[
          IconButton(icon: Icon(Icons.delete),
              onPressed: (){
                  setState(() {
                    msg.removeLast();
                  });
              }),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            alignment: Alignment.topLeft,
            margin: EdgeInsets.only(right: 150.0,top: 10.0,left: 8.0),
            child:TextField(
                controller: Controller,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'please enter your name',
                ),
              ),

          ),
          Container(
            alignment: Alignment.topRight,
            margin: EdgeInsets.only(left: 250.0,right: 10.0),
            child: RaisedButton(
              onPressed: () {
                setState(() {
                  msg.add(Controller.text);
                  Controller.clear();
                });
              },
              child: Text('Add'),
            ),
          ),
          Expanded(
            flex: 2,
              child: Container(
                child: Card(
                  margin: EdgeInsets.all(8.0),
                  child: ListView.builder(
                    itemCount: msg.length,
                    itemBuilder: (context, index){
                      if(index.isInfinite){
                        return Divider();
                      }
                      return ListTile(
                        title: Text(msg[index]),
                      );
                    },),
                ),
              )),
        ],
      ),
    );
  }

}

I want to select the data and then delete it using the icon Button in
  the AppBar.

Body:
Lets assume you want to select your items by a single click.

Take a separate a list indexList and each time you select an item, you store the clicked index into indexList.

Then upon clicking delete button run a loop on indexList and remove items from your itemList using the stored indexes.

clean indexList
update your state

class DemoPage extends State<MyHomePage> {
  TextEditingController Controller = TextEditingController();
  List<String> msg = List();
  List<int> selectedItems = List();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return Scaffold(
      appBar: AppBar(
        title: Text('Demo_App'),

    actions: <Widget>[
      IconButton(
          icon: Icon(Icons.delete),
          onPressed: () {
            setState(() {
              msg.removeLast();
            });
          }),
    ],
  ),
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    mainAxisSize: MainAxisSize.min,
    children: <Widget>[
      Container(
        alignment: Alignment.topLeft,
        margin: EdgeInsets.only(right: 150.0, top: 10.0, left: 8.0),
        child: TextField(
          controller: Controller,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            hintText: 'please enter your name',
          ),
        ),
      ),
      Container(
        alignment: Alignment.topRight,
        margin: EdgeInsets.only(left: 250.0, right: 10.0),
        child: RaisedButton(
          onPressed: () {
            setState(() {
              msg.add(Controller.text);
              Controller.clear();
            });
          },
          child: Text('Add'),
        ),
      ),
      Expanded(
          flex: 2,
          child: Container(
            child: Card(
              margin: EdgeInsets.all(8.0),
              child: ListView.builder(
                  itemCount: msg.length,
                  itemBuilder: (context, index) {
                    return new GestureDetector(
                        onLongPress: () {
                          if(selectedItems.contains(index))
                            selectedItems.remove(index);
                          else
                            selectedItems.add(index);
                        },
                        onTap: () {
                          if(selectedItems.contains(index))
                            selectedItems.remove(index);
                          else
                            selectedItems.add(index);
                        },
                        child: index.isInfinite
                            ? Divider()
                            : ListTile(
                                title: Text(msg[index]),
                              ));
                  }),
            ),
          )),
    ],
  ),
);
  }

  void _deleteItems(){ // call _deleteItems() on clicking delete button

    setState(() {
      //set your state
      for (final index in selectedItems)
          msg.removeAt(index);
      selectedItems.clear();
    });
  }

}


问:
Creating "Not Exists"/Insert Into Statements - Stumped by nothing (NULL)
I need a script that generate insert statements but with check for if the data doesn't already exist, this because it should be periodically run on parallell systems where different dtata will be added to the systems but we want them tables to be in sync. I have the basic ides and borrowed parts of code but get a syntax error i have trouble solving.

I'm basing my code on the code Param Yadav showed at Converting Select results into Insert script - SQL Server but I need to check for data already in the table. (I need to add more "bells & whistles later, but take this step-by-step)

My own main addition is the @NOT_EXISTS part which should be in the WHERE clause of the NOT EXISTS check. If I replace that with a plain WHERE 0=1 I get no syntax error so it indicates the error is in my @NOT_EXISTS string.

Edit: Yesterday I thought I had an answer to my own question but when running on "real data" I saw that some lines are too long for QUOTENAME, I have to fix those quotation marks "manually" (concats in script) instead...

```<code>
SET NOCOUNT ON

DECLARE @CSV_COLUMN VARCHAR(MAX),
    @QUOTED_DATA VARCHAR(MAX),
    @NOT_EXISTS VARCHAR(MAX),
    @SQL_KOD VARCHAR(MAX),
    @TABLE_NAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)='',
    @FIRST_COL INT,
    @LAST_COL INT

/* INPUT DATA */
SELECT @TABLE_NAME = 'WorkflowError'
SELECT @FIRST_COL = 2
SELECT @LAST_COL = 4
/* */

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

--SELECT @CSV_COLUMN

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)

SELECT @QUOTED_DATA

SELECT @NOT_EXISTS=STUFF
(
    (
     SELECT ' ['+ COLUMN_NAME +']=', 'ISNULL(QUOTENAME('+COLUMN_NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+') AND '
     FROM information_schema.columns
     WHERE table_name = @TABLE_NAME AND
     ordinal_position BETWEEN @FIRST_COL AND @LAST_COL
     FOR XML PATH('')
    ),1,1,''
)

SELECT @NOT_EXISTS=SUBSTRING(@NOT_EXISTS,1,LEN(@NOT_EXISTS)-4)

SELECT @NOT_EXISTS
--SELECT @NOT_EXISTS=' 0=1 '

SELECT @SQL_KOD='SELECT ''
    IF NOT EXISTS(SELECT 1
    FROM ' + @TABLE_NAME + ' WHERE ' + @NOT_EXISTS + ')
    BEGIN
        INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')
        VALUES('''+'+'+@QUOTED_DATA+'+'+''')
    END
    GO '''+' Insert_Scripts
FROM '+@TABLE_NAME + @FILTER_CONDITION

SELECT @SQL_KOD
EXECUTE (@SQL_KOD)

GO

[stackoverflow won't let me post code unless it's formatted, but then the strings below won't be as they are created in the script...]
When I do SELECT @NOT_EXISTS=' 0=1 ' I get an INSERT line for each row in my table:

IF NOT EXISTS(SELECT 1 FROM WorkflowError WHERE  0=1 )
    BEGIN
        INSERT INTO WorkflowError([TargetSystem],[ErrorCode],[ErrorText],[RetryMaxCount],[RetryStrategyName],[ErrorDescription])
        VALUES('EttLiv','800','Value cannot be null.  Parameter name: source','0',NULL,'Value cannot be null.  Parameter name: source')
    END
GO

With my @NOT_EXISTS code the @SQL_KOD string becomes this:

SELECT 'IF NOT EXISTS(SELECT 1 FROM WorkflowError
                      WHERE [TargetSystem]=ISNULL(QUOTENAME(TargetSystem,''''),'NULL'))
BEGIN
    INSERT INTO WorkflowError([TargetSystem],[ErrorCode],[ErrorText],[RetryMaxCount],[RetryStrategyName],[ErrorDescription])
    VALUES('+ISNULL(QUOTENAME(TargetSystem,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorCode,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorText,''''),'NULL')+','
    + ISNULL(QUOTENAME(RetryMaxCount,''''),'NULL')+','
    + ISNULL(QUOTENAME(RetryStrategyName,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorDescription,''''),'NULL')+')
END
GO ' Insert_Scripts FROM WorkflowError
However, trying to execute that @SQL_KOD line just gives:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'NULL'.

...and I can't find out where I have done wrong, if it's in my thinking or if it's just a misplaced quotation mark...
</code>```

答:
Where do you expect @SQL_KOD to get its values from? Because if you are retrieving your values for TargetSystem / ErrorCode / ... / ErrorDescription from somewhere outside of your insert statement, I would expect a "from" statement. If you want to input variables, you are missing both the definition of the variables and the @-sign in front of the variable name.

As far as keeping quotes happy: try writing your code with QUOTED_IDENTIFIER OFF - you can create the entire @SQL_KOD variable by writing between double quotes ("), and single quotes would behave like normal quotation marks.

A very basic re-write of your code could be something as follows:

```<code>SET QUOTED_IDENTIFIER OFF

DECLARE @SQL_KOD VARCHAR(MAX)

SET @SQL_KOD =

"DECLARE @WorkFlowError TABLE ([TargetSystem] NVARCHAR(200),[ErrorCode] NVARCHAR(200))

IF NOT EXISTS ( SELECT 1 FROM @WorkFlowError )
BEGIN
    INSERT INTO @WorkFlowError ([TargetSystem],[ErrorCode])
    SELECT ISNULL(QUOTENAME([TargetSystem],''''),'NULL')
        , ISNULL(QUOTENAME([ErrorCode],''''),'NULL')
    FROM (
        SELECT [TargetSystem]='Foo'
            , [ErrorCode]='Bar'
    ) src
END";
</code>```

Body:
I need a script that generate insert statements but with check for if the data doesn't already exist, this because it should be periodically run on parallell systems where different dtata will be added to the systems but we want them tables to be in sync. I have the basic ides and borrowed parts of code but get a syntax error i have trouble solving.

I'm basing my code on the code Param Yadav showed at Converting Select results into Insert script - SQL Server but I need to check for data already in the table. (I need to add more "bells & whistles later, but take this step-by-step)

My own main addition is the @NOT_EXISTS part which should be in the WHERE clause of the NOT EXISTS check. If I replace that with a plain WHERE 0=1 I get no syntax error so it indicates the error is in my @NOT_EXISTS string.

Edit: Yesterday I thought I had an answer to my own question but when running on "real data" I saw that some lines are too long for QUOTENAME, I have to fix those quotation marks "manually" (concats in script) instead...

SET NOCOUNT ON

DECLARE @CSV_COLUMN VARCHAR(MAX),
    @QUOTED_DATA VARCHAR(MAX),
    @NOT_EXISTS VARCHAR(MAX),
    @SQL_KOD VARCHAR(MAX),
    @TABLE_NAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)='',
    @FIRST_COL INT,
    @LAST_COL INT

/* INPUT DATA */
SELECT @TABLE_NAME = 'WorkflowError'
SELECT @FIRST_COL = 2
SELECT @LAST_COL = 4
/* */

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

--SELECT @CSV_COLUMN

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)

SELECT @QUOTED_DATA

SELECT @NOT_EXISTS=STUFF
(
    (
     SELECT ' ['+ COLUMN_NAME +']=', 'ISNULL(QUOTENAME('+COLUMN_NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+') AND '
     FROM information_schema.columns
     WHERE table_name = @TABLE_NAME AND
     ordinal_position BETWEEN @FIRST_COL AND @LAST_COL
     FOR XML PATH('')
    ),1,1,''
)

SELECT @NOT_EXISTS=SUBSTRING(@NOT_EXISTS,1,LEN(@NOT_EXISTS)-4)

SELECT @NOT_EXISTS
--SELECT @NOT_EXISTS=' 0=1 '

SELECT @SQL_KOD='SELECT ''
    IF NOT EXISTS(SELECT 1
    FROM ' + @TABLE_NAME + ' WHERE ' + @NOT_EXISTS + ')
    BEGIN
        INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')
        VALUES('''+'+'+@QUOTED_DATA+'+'+''')
    END
    GO '''+' Insert_Scripts
FROM '+@TABLE_NAME + @FILTER_CONDITION

SELECT @SQL_KOD
EXECUTE (@SQL_KOD)

GO

[stackoverflow won't let me post code unless it's formatted, but then the strings below won't be as they are created in the script...]
When I do SELECT @NOT_EXISTS=' 0=1 ' I get an INSERT line for each row in my table:

IF NOT EXISTS(SELECT 1 FROM WorkflowError WHERE  0=1 )
    BEGIN
        INSERT INTO WorkflowError([TargetSystem],[ErrorCode],[ErrorText],[RetryMaxCount],[RetryStrategyName],[ErrorDescription])
        VALUES('EttLiv','800','Value cannot be null.  Parameter name: source','0',NULL,'Value cannot be null.  Parameter name: source')
    END
GO

With my @NOT_EXISTS code the @SQL_KOD string becomes this:

SELECT 'IF NOT EXISTS(SELECT 1 FROM WorkflowError
                      WHERE [TargetSystem]=ISNULL(QUOTENAME(TargetSystem,''''),'NULL'))
BEGIN
    INSERT INTO WorkflowError([TargetSystem],[ErrorCode],[ErrorText],[RetryMaxCount],[RetryStrategyName],[ErrorDescription])
    VALUES('+ISNULL(QUOTENAME(TargetSystem,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorCode,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorText,''''),'NULL')+','
    + ISNULL(QUOTENAME(RetryMaxCount,''''),'NULL')+','
    + ISNULL(QUOTENAME(RetryStrategyName,''''),'NULL')+','
    + ISNULL(QUOTENAME(ErrorDescription,''''),'NULL')+')
END
GO ' Insert_Scripts FROM WorkflowError
However, trying to execute that @SQL_KOD line just gives:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'NULL'.

...and I can't find out where I have done wrong, if it's in my thinking or if it's just a misplaced quotation mark...

Body:
Where do you expect @SQL_KOD to get its values from? Because if you are retrieving your values for TargetSystem / ErrorCode / ... / ErrorDescription from somewhere outside of your insert statement, I would expect a "from" statement. If you want to input variables, you are missing both the definition of the variables and the @-sign in front of the variable name.

As far as keeping quotes happy: try writing your code with QUOTED_IDENTIFIER OFF - you can create the entire @SQL_KOD variable by writing between double quotes ("), and single quotes would behave like normal quotation marks.

A very basic re-write of your code could be something as follows:

SET QUOTED_IDENTIFIER OFF

DECLARE @SQL_KOD VARCHAR(MAX)

SET @SQL_KOD =

"DECLARE @WorkFlowError TABLE ([TargetSystem] NVARCHAR(200),[ErrorCode] NVARCHAR(200))

IF NOT EXISTS ( SELECT 1 FROM @WorkFlowError )
BEGIN
    INSERT INTO @WorkFlowError ([TargetSystem],[ErrorCode])
    SELECT ISNULL(QUOTENAME([TargetSystem],''''),'NULL')
        , ISNULL(QUOTENAME([ErrorCode],''''),'NULL')
    FROM (
        SELECT [TargetSystem]='Foo'
            , [ErrorCode]='Bar'
    ) src
END";


问:
Datatables Checkboxes select multiple on matching ids
I have a server-side datatable setup with the checkboxes plugin.
Each checkbox has the data of a product_id.

```<code>var table = $('#display_users').DataTable( {
        "processing": true,
        "serverSide": true,
        'ajax': '{{ route ('/getUsers') }}',
        'columns' : [
            {"data" : "product_id"},
            {"data" : "product_id"},
            {"data" : "first_name"},
            {"data" : "last_name"},
            {"data" : "email"},
            {"data" : "company"},
            {"data" : "department"},
            {"data" : "created_at"}
        ],
        'columnDefs': [
            {
                'targets': 0,
                'checkboxes': {
                    'selectRow': true
                },
</code>```

I would like to be able to, when a checkbox is selected, select all the checkboxes with the same product_id. This is only necessary for the records on the currently selected page.
It seems this should be possible with the checkboxes select api, however I haven't been successful so far

答:
I don't see much value in 'checkbox' plug-in as its features can be effortlessly implemented with few lines of code while giving you greater flexibility.

However, you don't really need to dig deep into 'checkbox' plug-in internals as your required feature can be easily coded with native DataTables API:

```<code>//listen for the clicking first column checkboxes
$('#display_users').click('tbody td:eq(0) [type="checkbox"]', function(){
  //grab current checkbox state and criteria to match (product_id) from the row data
  const state = $(event.target).prop('checked');
  const productId = dataTable.row($(event.target).closest('tr')).data().product_id;
  //iterate through current page rows and adjust checkboxes upon matching product_id
  dataTable.rows({page:'current'}).every(function(){
    if(this.data().product_id == productId) $(this.node()).find('td:eq(0) [type="checkbox"]').prop('checked', state);
  });
});
</code>```

Complete demo of this concept you may find below:

//data sample
const srcData = [
  {product_id: 7, first_name: 'Nick', last_name: 'Furry', company: 'Avengers Inc'},
  {product_id: 7, first_name: 'Steve', last_name: 'Rogers', company: 'Avengers Inc'},
  {product_id: 4, first_name: 'Arthur', last_name: 'Curry', company: 'Justice Ltd'},
  {product_id: 4, first_name: 'Clark', last_name: 'Kent', company: 'Justice Ltd'},
  {product_id: 4, first_name: 'Barry', last_name: 'Allen', company: 'Justice Ltd'}
];

//datatable initialization
const dataTable = $('#display_users').DataTable({
  dom: 't',
  order: [1, 'asc'],
  data: srcData,
  columns: [null, ...Object.keys(srcData[0])].map(header => ({title: header || '', data: header})),
  columnDefs: [
    {targets: 0, orderable: false, render: () => '<input type="checkbox"></input>'}
  ]
});

//essential part - row checkbox click hander
$('#display_users').click('tbody td:eq(0) [type="checkbox"]', function(){
  //grab current checkbox state and criteria to match (product_id)
  const state = $(event.target).prop('checked');
  const productId = dataTable.row($(event.target).closest('tr')).data().product_id;
  //iterate through current page rows and adjust checkboxes upon matching product_id
  dataTable.rows({page:'current'}).every(function(){
    if(this.data().product_id == productId) $(this.node()).find('td:eq(0) [type="checkbox"]').prop('checked', state);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="display_users"></table>
</body>
</html></code>```

Body:
I have a server-side datatable setup with the checkboxes plugin.
Each checkbox has the data of a product_id.

var table = $('#display_users').DataTable( {
        "processing": true,
        "serverSide": true,
        'ajax': '{{ route ('/getUsers') }}',
        'columns' : [
            {"data" : "product_id"},
            {"data" : "product_id"},
            {"data" : "first_name"},
            {"data" : "last_name"},
            {"data" : "email"},
            {"data" : "company"},
            {"data" : "department"},
            {"data" : "created_at"}
        ],
        'columnDefs': [
            {
                'targets': 0,
                'checkboxes': {
                    'selectRow': true
                },

I would like to be able to, when a checkbox is selected, select all the checkboxes with the same product_id. This is only necessary for the records on the currently selected page.
It seems this should be possible with the checkboxes select api, however I haven't been successful so far

Body:
I don't see much value in 'checkbox' plug-in as its features can be effortlessly implemented with few lines of code while giving you greater flexibility.

However, you don't really need to dig deep into 'checkbox' plug-in internals as your required feature can be easily coded with native DataTables API:

//listen for the clicking first column checkboxes
$('#display_users').click('tbody td:eq(0) [type="checkbox"]', function(){
  //grab current checkbox state and criteria to match (product_id) from the row data
  const state = $(event.target).prop('checked');
  const productId = dataTable.row($(event.target).closest('tr')).data().product_id;
  //iterate through current page rows and adjust checkboxes upon matching product_id
  dataTable.rows({page:'current'}).every(function(){
    if(this.data().product_id == productId) $(this.node()).find('td:eq(0) [type="checkbox"]').prop('checked', state);
  });
});

Complete demo of this concept you may find below:

//data sample
const srcData = [
  {product_id: 7, first_name: 'Nick', last_name: 'Furry', company: 'Avengers Inc'},
  {product_id: 7, first_name: 'Steve', last_name: 'Rogers', company: 'Avengers Inc'},
  {product_id: 4, first_name: 'Arthur', last_name: 'Curry', company: 'Justice Ltd'},
  {product_id: 4, first_name: 'Clark', last_name: 'Kent', company: 'Justice Ltd'},
  {product_id: 4, first_name: 'Barry', last_name: 'Allen', company: 'Justice Ltd'}
];

//datatable initialization
const dataTable = $('#display_users').DataTable({
  dom: 't',
  order: [1, 'asc'],
  data: srcData,
  columns: [null, ...Object.keys(srcData[0])].map(header => ({title: header || '', data: header})),
  columnDefs: [
    {targets: 0, orderable: false, render: () => '<input type="checkbox"></input>'}
  ]
});

//essential part - row checkbox click hander
$('#display_users').click('tbody td:eq(0) [type="checkbox"]', function(){
  //grab current checkbox state and criteria to match (product_id)
  const state = $(event.target).prop('checked');
  const productId = dataTable.row($(event.target).closest('tr')).data().product_id;
  //iterate through current page rows and adjust checkboxes upon matching product_id
  dataTable.rows({page:'current'}).every(function(){
    if(this.data().product_id == productId) $(this.node()).find('td:eq(0) [type="checkbox"]').prop('checked', state);
  });
});

<!doctype html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="display_users"></table>
</body>
</html>


问:
How to draw lines and circles in a shader efficently
I have used this website to create a shader that displays a snowman and some snowflakes:

http://glslsandbox.com/e#54840.8

In case the link doesn't work, heres the code:

```<code>#ifdef GL_ES
precision mediump float;
#endif

#extension GL_OES_standard_derivatives : enable

uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
uniform sampler2D backbuffer;

#define PI 3.14159265

vec2 p;
float bt;

float seed=0.1;
float rand(){
    seed+=fract(sin(seed)*seed*1000.0)+.123;

    return mod(seed,1.0);
}

//No I don't know why he loks so creepy

float thicc=.003;
vec3 color=vec3(1.);
vec3 border=vec3(.4);

void diff(float p){
    if( (p)<thicc)
        gl_FragColor.rgb=color;
}
void line(vec2 a, vec2 b){

    vec2 q=p-a;

    vec2 r=normalize(b-a);

    if(dot(r,q)<0.){
        diff(length(q));
        return;
    }

    if(dot(r,q)>length(b-a)){
        diff(length(p-b));
        return;
    }

    vec2 rr=vec2(r.y,-r.x);

    diff(abs(dot(rr,q)));

}
void circle(vec2 m,float r){
    vec2 q=p-m;
    vec3 c=color;
    diff(length(q)-r);
    color=border;
    diff(abs(length(q)-r));
    color=c;
}

void main() {
    p=gl_FragCoord.xy/resolution.y;

    bt=mod(time,4.*PI);
    gl_FragColor.rgb=vec3(0.);

    vec2 last;

    //Body
    circle(vec2(1.,.250),.230);
    circle(vec2(1.,.520),.180);
    circle(vec2(1.,.75),.13);

    //Nose
    color=vec3(1.,.4,.0);
    line(vec2(1,.720),vec2(1.020,.740));
    line(vec2(1,.720),vec2(.980,.740));
    line(vec2(1,.720),vec2(.980,.740));
    line(vec2(1.020,.740),vec2(.980,.740));

    border=vec3(0);
    color=vec3(1);
    thicc=.006;
    //Eyes

    circle(vec2(.930,.800),.014);
    circle(vec2(1.060,.800),.014);

    color=vec3(.0);
    thicc=0.;

    //mouth
    for(float x=0.;x<.1300;x+=.010)
        circle(vec2(.930+x,.680+cos(x*40.0+.5)*.014),.005);

    //buttons
    for(float x=0.02;x<.450;x+=.070)
        circle(vec2(1.000,.150+x),0.01);

    color=vec3(0.9);
    thicc=0.;

    //snowflakes
    for(int i=0;i<99;i++){
         circle(vec2(rand()*2.0,mod(rand()-time,1.0)),0.01);
    }

    gl_FragColor.a=1.0;

}
</code>```

The way it works is, that for each pixel on the screen, the shader checks for each elment (button, body, head, eyes mouth, carrot, snowflake) wheter it's inside an area, n which case it replaces the current color at that position with the current draw color.

So we have a complexity of O(pixels_width * pixels_height * elements), which leads to to the shader slowing down when too many snowflakes are own screen.
So now I was wondering, how can this code be optimized? I already thought about using bounding boxes or even a 3d Octree (I guess that would be a quadtree) to quickly discard elements that are outside a certain pixel (or fragments) area.

Does anyone have another idea how to optimize this shadercode? Keeping in mind that every shader execution is completely independant of all others and I can't use any overarching structure.

答:
You would need to break up your screen into regions, "tiles" and compute the snowflakes per tile. Tiles would have the same number of snowflakes and share the same seed, so that one particle leaving the tile's boundary would have an identical particle entering the next tile, making it look seamless. The pattern might still appear depending on your settings, but you could consider adding an extra uniform transformation, potentially based on the final screen position.

On a side note, your method for drawing circles could be more efficient by removing all conditional branching (and look anti-aliased in the process) and could get rid of the square root generated by length().

Body:
I have used this website to create a shader that displays a snowman and some snowflakes:

http://glslsandbox.com/e#54840.8

In case the link doesn't work, heres the code:

#ifdef GL_ES
precision mediump float;
#endif

#extension GL_OES_standard_derivatives : enable

uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
uniform sampler2D backbuffer;

#define PI 3.14159265

vec2 p;
float bt;

float seed=0.1;
float rand(){
    seed+=fract(sin(seed)*seed*1000.0)+.123;

    return mod(seed,1.0);
}

//No I don't know why he loks so creepy

float thicc=.003;
vec3 color=vec3(1.);
vec3 border=vec3(.4);

void diff(float p){
    if( (p)<thicc)
        gl_FragColor.rgb=color;
}
void line(vec2 a, vec2 b){

    vec2 q=p-a;

    vec2 r=normalize(b-a);

    if(dot(r,q)<0.){
        diff(length(q));
        return;
    }

    if(dot(r,q)>length(b-a)){
        diff(length(p-b));
        return;
    }

    vec2 rr=vec2(r.y,-r.x);

    diff(abs(dot(rr,q)));

}
void circle(vec2 m,float r){
    vec2 q=p-m;
    vec3 c=color;
    diff(length(q)-r);
    color=border;
    diff(abs(length(q)-r));
    color=c;
}

void main() {
    p=gl_FragCoord.xy/resolution.y;

    bt=mod(time,4.*PI);
    gl_FragColor.rgb=vec3(0.);

    vec2 last;

    //Body
    circle(vec2(1.,.250),.230);
    circle(vec2(1.,.520),.180);
    circle(vec2(1.,.75),.13);

    //Nose
    color=vec3(1.,.4,.0);
    line(vec2(1,.720),vec2(1.020,.740));
    line(vec2(1,.720),vec2(.980,.740));
    line(vec2(1,.720),vec2(.980,.740));
    line(vec2(1.020,.740),vec2(.980,.740));

    border=vec3(0);
    color=vec3(1);
    thicc=.006;
    //Eyes

    circle(vec2(.930,.800),.014);
    circle(vec2(1.060,.800),.014);

    color=vec3(.0);
    thicc=0.;

    //mouth
    for(float x=0.;x<.1300;x+=.010)
        circle(vec2(.930+x,.680+cos(x*40.0+.5)*.014),.005);

    //buttons
    for(float x=0.02;x<.450;x+=.070)
        circle(vec2(1.000,.150+x),0.01);

    color=vec3(0.9);
    thicc=0.;

    //snowflakes
    for(int i=0;i<99;i++){
         circle(vec2(rand()*2.0,mod(rand()-time,1.0)),0.01);
    }

    gl_FragColor.a=1.0;

}

The way it works is, that for each pixel on the screen, the shader checks for each elment (button, body, head, eyes mouth, carrot, snowflake) wheter it's inside an area, n which case it replaces the current color at that position with the current draw color.

So we have a complexity of O(pixels_width * pixels_height * elements), which leads to to the shader slowing down when too many snowflakes are own screen.
So now I was wondering, how can this code be optimized? I already thought about using bounding boxes or even a 3d Octree (I guess that would be a quadtree) to quickly discard elements that are outside a certain pixel (or fragments) area.

Does anyone have another idea how to optimize this shadercode? Keeping in mind that every shader execution is completely independant of all others and I can't use any overarching structure.


问:
"SQL Server Compact 2008" including spatial support
I've read somewhere that there will be a "SQL Server Compact 2008" including spatial support but now that I search for it, I can't find it anywhere. For example, there's nothing on https://connect.microsoft.com/SQLServer/content/content.aspx?ContentID=5470 regarding the compact version.

Does anyone know what the scoop is?

I have a situation here, i have created WPF application with SQL Compact edition database , now i want to store some spatial data in it. I am using google maps and want to use the geography data type which is not supported in CE. Now, what should be the best approach i should follow, should i use the express edition but then how will i encrypt the data in db / make it safe?

答: You can store the Geography data in an "image" column in the SQL Server Compact db, no support for Geography. You can alos encrypty the SQL Server Compact db (as you probably know already)</p>


问:
Getting contacts error - how to fix that?
My problem is that I am listing contacts, the phone numbers show up just fine however I can not get the names to work.

I have tried several ways to gain the 'DISPLAY_NAME' however none of them have worked

```<code>    private void initializeRecyclerView() {
        mUserList = findViewById(R.id.userList);
        mUserList.setNestedScrollingEnabled(false);
        mUserList.setHasFixedSize(false);
        mUserListLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.VERTICAL, false);
        mUserList.setLayoutManager(mUserListLayoutManager);
        mUserListAdapter = new UserListAdapter(userList);
        mUserList.setAdapter(mUserListAdapter);
        getContactsList();
    }

This is my adaptor ^^

    private void getContactsList(){
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while(phones.moveToNext()){
            String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            UserObject mContact = new UserObject(name, phone);
            userList.add(mContact);
            mUserListAdapter.notifyDataSetChanged();
        }
    }
</code>```

答:
i am getting the contacts with this :- </p>

```<code>private void getContactsList(){
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while(phones.moveToNext()){
            String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
 UserObject mContact = new UserObject(name, phone);
            userList.add(mContact);
        }

 mUserListAdapter = new UserListAdapter(userList);
    mUserList.setAdapter(mUserListAdapter);
    }
</code>```

<p>and also set the permission for get contacts :- </p>

```<code><uses-permission android:name="android.permission.READ_CONTACTS" />
</code>```

Body:
My problem is that I am listing contacts, the phone numbers show up just fine however I can not get the names to work.

I have tried several ways to gain the 'DISPLAY_NAME' however none of them have worked

    private void initializeRecyclerView() {
        mUserList = findViewById(R.id.userList);
        mUserList.setNestedScrollingEnabled(false);
        mUserList.setHasFixedSize(false);
        mUserListLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.VERTICAL, false);
        mUserList.setLayoutManager(mUserListLayoutManager);
        mUserListAdapter = new UserListAdapter(userList);
        mUserList.setAdapter(mUserListAdapter);
        getContactsList();
    }

This is my adaptor ^^

    private void getContactsList(){
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while(phones.moveToNext()){
            String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            UserObject mContact = new UserObject(name, phone);
            userList.add(mContact);
            mUserListAdapter.notifyDataSetChanged();
        }
    }

Body:
i am getting the contacts with this :-

private void getContactsList(){
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while(phones.moveToNext()){
            String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
 UserObject mContact = new UserObject(name, phone);
            userList.add(mContact);
        }

 mUserListAdapter = new UserListAdapter(userList);
    mUserList.setAdapter(mUserListAdapter);
    }

and also set the permission for get contacts :-

<uses-permission android:name="android.permission.READ_CONTACTS" />


问:
I can't select the text on my website, I think it's masked by some css
Could someone take a quick look, why the text in the dark grey isn't selectable.

I think it's masked by a invisible layer or somewhat, but I don't see it.

The url:

http://www.coldcharlie.nl/test/

Edit: I think it's the shadow part, I'll take a look at that first.

答:
The user-select CSS property controls whether the user can select
  text.

https://developer.mozilla.org/en-US/docs/Web/CSS/user-select

If the text is not overlapped by an element look for this in your CSS.

```<code>user-select: none;
</code>```

Body:
The user-select CSS property controls whether the user can select
  text.

https://developer.mozilla.org/en-US/docs/Web/CSS/user-select

If the text is not overlapped by an element look for this in your CSS.

user-select: none;


问:
Runing a "child" python file as regular user when main python file needs to be run as root
I'm doing a python program (and using PyQt5 for GUI) that needs to be run as root (because I'm programming sockets on it). It has a button,when I click on it, it opens another python file (the "child" file: chrometest.py, it's based on this library, eel: https://www.youtube.com/watch?v=2kbeBzEQfXE, it lets me open a js file). The problem is that eel won't work when it's run as root, so I don't know how I could switch users to run only this function as regular user.

Main python program (sample, the one runing as root)

```<code>import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QMainWindow):
    def __init__(self, *args):
        super(Window, self).__init__()
        self.img = QtWidgets.QLabel()
        self.open_js= QtWidgets.QPushButton('Load')
        self.width = 400
        self.height = 150
        self.init_ui()

    def init_ui(self):
        self.img.setPixmap(QtGui.QPixmap("someimage.png"))
        self.open_js.clicked.connect(self.openjs)
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        h_layout = QtWidgets.QHBoxLayout(central_widget)
        h_layout.addWidget(self.img)
        h_layout.addWidget(self.open_js)
        self.setWindowTitle('Main Window')
        self.setGeometry(600,150,self.width,self.height)

    def openjs(self):
        #here is where I think I need to switch to regular user
        exec(open("chrometest.py").read())

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

chrometest.py (program that needs to be run as regular user)

```<code>import eel
eel.init('webfiles')
eel.start('index.html')
</code>```

I tried to use this tutorial https://www.tutorialspoint.com/python/os_chown.htm in the line commented but it didn't work

答:
It is common in Unix-like systems to have a process that needs to be root at a time, for example to listen on ports below 1024, but then executes  as a regular non priviledges user for security reasons. Whatever the language the design is as follow:

priviledged part (extensively tested for security flaws) executes only code requiring root privileges

as soon as code that does not require root has to be executed it forks and

parent remains priviledged and continue to run priviledged code

child switch to a regular user (allowed because it is still at priviledged-root level) and executes normal code

That is what you should do here:

```<code>def openjs(self):
    pid = os.fork()
    if 0 == pid:
        os.setuid(uid_of_non_priviledged_user)
        # you can now safely execute code from chrometest.
    else:
        # optionaly wait for child:
        os.waitpid(pid, os.WEXITED)
</code>```

Body:
I'm doing a python program (and using PyQt5 for GUI) that needs to be run as root (because I'm programming sockets on it). It has a button,when I click on it, it opens another python file (the "child" file: chrometest.py, it's based on this library, eel: https://www.youtube.com/watch?v=2kbeBzEQfXE, it lets me open a js file). The problem is that eel won't work when it's run as root, so I don't know how I could switch users to run only this function as regular user.

Main python program (sample, the one runing as root)

import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QMainWindow):
    def __init__(self, *args):
        super(Window, self).__init__()
        self.img = QtWidgets.QLabel()
        self.open_js= QtWidgets.QPushButton('Load')
        self.width = 400
        self.height = 150
        self.init_ui()

    def init_ui(self):
        self.img.setPixmap(QtGui.QPixmap("someimage.png"))
        self.open_js.clicked.connect(self.openjs)
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        h_layout = QtWidgets.QHBoxLayout(central_widget)
        h_layout.addWidget(self.img)
        h_layout.addWidget(self.open_js)
        self.setWindowTitle('Main Window')
        self.setGeometry(600,150,self.width,self.height)

    def openjs(self):
        #here is where I think I need to switch to regular user
        exec(open("chrometest.py").read())

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

chrometest.py (program that needs to be run as regular user)

import eel
eel.init('webfiles')
eel.start('index.html')

I tried to use this tutorial https://www.tutorialspoint.com/python/os_chown.htm in the line commented but it didn't work

Body:
It is common in Unix-like systems to have a process that needs to be root at a time, for example to listen on ports below 1024, but then executes  as a regular non priviledges user for security reasons. Whatever the language the design is as follow:

priviledged part (extensively tested for security flaws) executes only code requiring root privileges

as soon as code that does not require root has to be executed it forks and

parent remains priviledged and continue to run priviledged code

child switch to a regular user (allowed because it is still at priviledged-root level) and executes normal code

That is what you should do here:

def openjs(self):
    pid = os.fork()
    if 0 == pid:
        os.setuid(uid_of_non_priviledged_user)
        # you can now safely execute code from chrometest.
    else:
        # optionaly wait for child:
        os.waitpid(pid, os.WEXITED)


问:
Remove top line from TabBar
On iOS 10 this code doesn't work in order to remove the tabBar shadow line:

```<code>[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
</code>```

Somebody knows, what must I do to remove it?

On iOS 9.3 with this two lines the line is removed, but iOS 10 ignores setShadowImage command.

答:
Tested on iOS 14

```<code>override func viewDidLoad() {
    // Remove default border line
    tabBar.shadowImage = UIImage()
    tabBar.backgroundImage = UIImage()
    tabBar.backgroundColor = UIColor.white
}
</code>```

Title: Remove top line from TabBar

Body:
On iOS 10 this code doesn't work in order to remove the tabBar shadow line:

[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];

Somebody knows, what must I do to remove it?

On iOS 9.3 with this two lines the line is removed, but iOS 10 ignores setShadowImage command.

Body:
Tested on iOS 14

override func viewDidLoad() {
    // Remove default border line
    tabBar.shadowImage = UIImage()
    tabBar.backgroundImage = UIImage()
    tabBar.backgroundColor = UIColor.white
}


问:
Scrapy returning items within spider before first request/parse
I need to return some items from inside a spider before starting to parse requests. Because I need to make sure some parent items exist in database before parsing child items.

I now yield them from the parse method first thing, and this seem to work fine. But I was wondering if there is a better way to do this?

答: Instead of yielding the items, write them into the database directly on the constructor of the pipeline where you add regular items to the database.</p>


问:
FATAL EXCEPTION: AsyncTask #1 Relating to java.lang.NoClassDefFoundError
I did the same thing on what my professor taught us, but when i try to do it in my own computer (which i did in our school computers) I'm having a error with AsyncTask that is related with java.lang.NoClassDefFoundError, But I'm a little bit beginner in android development using java, Cause I'm using react-native in mobile development.

I have not tried anything else because I'm a little bit noob in java and android studio.
But I've found out that my system and in school have some different specs or version of software.

```<code>Softare/Tool   |  My_SYSTEM | School_SYSTEM
Android Studio | 3.0+       | 2.1
Java           |  8         | 8
Javac          |  8         | 11
</code>```

Is there a problem with my software or tools that causes me the error

This is the doInBackground Method

```<code>@Override
        protected String doInBackground(String... args0) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("lastname", lname));

            JSONObject json = jsonParser.makeHttpRequest(url_sample1, "POST", params);
            Log.d("Create Response", json.toString());

            try {
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    //success
                    String success_res = "Success";
                    Log.d("Success Response", success_res);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "Successfully Saved!",
                                    Toast.LENGTH_LONG).show();
                        }
                    });

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "Error",
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
</code>```

This is my PHP file. I have double check it on my browser still no error for it

```<code><?php
include("connection.php");

$response = array();

if(isset($_POST['lastname'])){
    $last = $_POST['lastname'];
    $result = mysqli_query($con, "INSERT INTO tblsample1('lname') VALUES ('$last')");

    if($result){
        $response["success"] = 1;
        $response["message"] = "successful";
        echo json_encode($response);
    }else{
        $response["success"] = 0;
        $response["message"] = "error";
        echo json_encode($response);
    }
}else{
    $response["success"] = 0;
        $response["message"] = "Please input lastname";
        echo json_encode($response);
}

?>
</code>```

I also included the permission tag on AndroidManifest so I could use internet on my android app.

And this is my logcat whenever I press the submit button

```<code>2019-05-27 15:06:25.887 13296-13330/com.example.prjsample1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: com.example.prjsample1, PID: 13296
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:354)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/commons/logging/LogFactory;
        at org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:187)
        at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:146)
        at com.example.prjsample1.JSONParser.makeHttpRequest(JSONParser.java:42)
        at com.example.prjsample1.MainActivity$sample1.doInBackground(MainActivity.java:69)
        at com.example.prjsample1.MainActivity$sample1.doInBackground(MainActivity.java:51)
        at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.commons.logging.LogFactory" on path: DexPathList[[zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/base.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_resources_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/lib/x86, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:187)
        at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:146)
        at com.example.prjsample1.JSONParser.makeHttpRequest(JSONParser.java:42)
        at com.example.prjsample1.MainActivity$sample1.doInBackground(MainActivity.java:69)
        at com.example.prjsample1.MainActivity$sample1.doInBackground(MainActivity.java:51)
        at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
        Suppressed: java.io.IOException: No original dex files found for dex location /data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_resources_apk.apk
        at dalvik.system.DexFile.openDexFileNative(Native Method)
        at dalvik.system.DexFile.openDexFile(DexFile.java:354)
        at dalvik.system.DexFile.<init>(DexFile.java:101)
        at dalvik.system.DexFile.<init>(DexFile.java:75)
        at dalvik.system.DexPathList.loadDexFile(DexPathList.java:394)
        at dalvik.system.DexPathList.makeDexElements(DexPathList.java:354)
        at dalvik.system.DexPathList.<init>(DexPathList.java:164)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:74)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
        at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:73)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:88)
2019-05-27 15:06:25.890 13296-13330/com.example.prjsample1 E/AndroidRuntime:     at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:74)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:40)
        at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:727)
        at android.app.LoadedApk.getClassLoader(LoadedApk.java:810)
        at android.app.LoadedApk.getResources(LoadedApk.java:1032)
        at android.app.ContextImpl.createAppContext(ContextImpl.java:2345)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5749)
        at android.app.ActivityThread.access$1100(ActivityThread.java:199)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

I should have a toastmaketest when I press the submit button which it actually did when we do it on the schoool computer

答:
The crash says Didn't find class "org.apache.commons.logging.LogFactory" on path.

It means, there is a missing dependency of slf4j. Add slf4j to the module level build.gradle file.

```<code>// https://mvnrepository.com/artifact/org.slf4j/slf4j-android
implementation group: 'org.slf4j', name: 'slf4j-android', version: '1.7.26'
</code>```

How to add the dependency to the build.gradle file.

Open the project tools window (Shortcut: Windows: Alt + 1    or Mac: Command + 1). [You'll see it in the top left corner of the Android Studio.]

Expand the app folder to find the build.gradle file. [There will be multiple build.gradle files. Make sure the file is inside the app folder alongside src, build folder and not outside it.]

Open the build.gradle file and scroll down to find the dependencies block. [Looks something like below.]

```<code>dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion"
    implementation "com.android.support:appcompat-v7:$supportVersion"
    implementation "com.android.support.constraint:constraint-layout:$constraintVersion"
...
    implementation group: 'org.slf4j', name: 'slf4j-android', version: '1.7.26'
}
</code>```

Add the dependency to the block (like above).

Body:
I did the same thing on what my professor taught us, but when i try to do it in my own computer (which i did in our school computers) I'm having a error with AsyncTask that is related with java.lang.NoClassDefFoundError, But I'm a little bit beginner in android development using java, Cause I'm using react-native in mobile development.

I have not tried anything else because I'm a little bit noob in java and android studio.
But I've found out that my system and in school have some different specs or version of software.

Softare/Tool   |  My_SYSTEM | School_SYSTEM
Android Studio | 3.0+       | 2.1
Java           |  8         | 8
Javac          |  8         | 11

Is there a problem with my software or tools that causes me the error

This is the doInBackground Method

@Override
        protected String doInBackground(String... args0) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("lastname", lname));

            JSONObject json = jsonParser.makeHttpRequest(url_sample1, "POST", params);
            Log.d("Create Response", json.toString());

            try {
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    //success
                    String success_res = "Success";
                    Log.d("Success Response", success_res);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "Successfully Saved!",
                                    Toast.LENGTH_LONG).show();
                        }
                    });

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "Error",
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

This is my PHP file. I have double check it on my browser still no error for it

<?php
include("connection.php");

$response = array();

if(isset($_POST['lastname'])){
    $last = $_POST['lastname'];
    $result = mysqli_query($con, "INSERT INTO tblsample1('lname') VALUES ('$last')");

    if($result){
        $response["success"] = 1;
        $response["message"] = "successful";
        echo json_encode($response);
    }else{
        $response["success"] = 0;
        $response["message"] = "error";
        echo json_encode($response);
    }
}else{
    $response["success"] = 0;
        $response["message"] = "Please input lastname";
        echo json_encode($response);
}

?>

I also included the permission tag on AndroidManifest so I could use internet on my android app.

And this is my logcat whenever I press the submit button

2019-05-27 15:06:25.887 13296-13330/com.example.prjsample1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: com.example.prjsample1, PID: 13296
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:354)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/commons/logging/LogFactory;
        at org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:187)
        at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:146)
        at com.example.prjsample1.JSONParser.makeHttpRequest(JSONParser.java:42)
        at com.example.prjsample1.MainActivity$sample1.doInBackground(MainActivity.java:69)
        at com.example.prjsample1.MainActivity$sample1.doInBackground(MainActivity.java:51)
        at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.commons.logging.LogFactory" on path: DexPathList[[zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/base.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_resources_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/lib/x86, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:187)
        at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:146)
        at com.example.prjsample1.JSONParser.makeHttpRequest(JSONParser.java:42)
        at com.example.prjsample1.MainActivity$sample1.doInBackground(MainActivity.java:69)
        at com.example.prjsample1.MainActivity$sample1.doInBackground(MainActivity.java:51)
        at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
        Suppressed: java.io.IOException: No original dex files found for dex location /data/app/com.example.prjsample1-87DfVwPm8J-fG1nxPkKpFQ==/split_lib_resources_apk.apk
        at dalvik.system.DexFile.openDexFileNative(Native Method)
        at dalvik.system.DexFile.openDexFile(DexFile.java:354)
        at dalvik.system.DexFile.<init>(DexFile.java:101)
        at dalvik.system.DexFile.<init>(DexFile.java:75)
        at dalvik.system.DexPathList.loadDexFile(DexPathList.java:394)
        at dalvik.system.DexPathList.makeDexElements(DexPathList.java:354)
        at dalvik.system.DexPathList.<init>(DexPathList.java:164)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:74)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
        at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:73)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:88)
2019-05-27 15:06:25.890 13296-13330/com.example.prjsample1 E/AndroidRuntime:     at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:74)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:40)
        at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:727)
        at android.app.LoadedApk.getClassLoader(LoadedApk.java:810)
        at android.app.LoadedApk.getResources(LoadedApk.java:1032)
        at android.app.ContextImpl.createAppContext(ContextImpl.java:2345)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5749)
        at android.app.ActivityThread.access$1100(ActivityThread.java:199)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

I should have a toastmaketest when I press the submit button which it actually did when we do it on the schoool computer

Body:
The crash says Didn't find class "org.apache.commons.logging.LogFactory" on path.

It means, there is a missing dependency of slf4j. Add slf4j to the module level build.gradle file.

// https://mvnrepository.com/artifact/org.slf4j/slf4j-android
implementation group: 'org.slf4j', name: 'slf4j-android', version: '1.7.26'

How to add the dependency to the build.gradle file.

Open the project tools window (Shortcut: Windows: Alt + 1    or Mac: Command + 1). [You'll see it in the top left corner of the Android Studio.]

Expand the app folder to find the build.gradle file. [There will be multiple build.gradle files. Make sure the file is inside the app folder alongside src, build folder and not outside it.]

Open the build.gradle file and scroll down to find the dependencies block. [Looks something like below.]

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion"
    implementation "com.android.support:appcompat-v7:$supportVersion"
    implementation "com.android.support.constraint:constraint-layout:$constraintVersion"
...
    implementation group: 'org.slf4j', name: 'slf4j-android', version: '1.7.26'
}

Add the dependency to the block (like above).


问:
SSL crashes periodically caused by certificate server certificate is not configured properly with HTTP.SYS
I'm trying to install a self-host WCF service on a server with Windows Server 2012.
I was following these steps:

import my pfx file with mmc

run "netsh http add sslcert ipport=0.0.0.0:49000 certhash=e09280ded2322eb858b38b3250e1a488f797b269 appid={4dc3e181-e14b-4a21-b022-59fc669b0914}"

install my service and start it

At first it works well. But after a few hours the ssl crashes and I can only get error msg at client as below

An unhandled exception of type 'System.ServiceModel.CommunicationException' occurred in mscorlib.dll.
  Additional information: An error occurred while making the HTTP request to https://servername:49000/WCFServiceName. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.

run "netsh http delete sslcert ipport=0.0.0.0:49000"
and delete the imported pfx and then redo step1 and 2 can make ssl works again, but the problem will still appears in a few hours.

It's definitely not the SecurityProtocol problem, for I have already tried adding

```<code>System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
</code>```

before request. And both server and client uses .Net Framework 4.5.2

I've tried "netsh http show sslcert", and got below result:

```<code>    IP:port                      : 0.0.0.0:49000
    Certificate Hash             : e09280ded2322eb858b38b3250e1a488f797b269
    Application ID               : {4dc3e181-e14b-4a21-b022-59fc669b0914}
    Certificate Store Name       : My
    Verify Client Certificate Revocation : Enabled
    Verify Revocation Using Cached Client Certificate Only : Disabled
    Usage Check                  : Enabled
    Revocation Freshness Time    : 0
    URL Retrieval Timeout        : 0
    Ctl Identifier               : (null)
    Ctl Store Name               : (null)
    DS Mapper Usage              : Disabled
    Negotiate Client Certificate : Disabled
</code>```

I've tried delete the sslcert binding on port 49000 and created an empty website binding to port 49000 in IIS and make my service listening to that port then. It works the first time and lasted for about a week before the same error pops out.

Where should I begin to locate and solve this wired problem?

答:
First, we should ensure that the certificate private key could be accessed by WCF. The Network Service account (or Everyone account) should be added in the certificate READ/Writer group, then we run the application (windows service, or console?) with corresponding account.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-make-x-509-certificates-accessible-to-wcf

Second, as you know, TLS version need OS and Dotnetframework support, the default protocol version is ssl3.0/tls1.0(auto-negotiate, could not be configured). We had better use the latest OS version and .netframework4.7. I think this may be the cause of unstable communications.

Please refer to the below document.

https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls

Feel free to let me know if the problem still exists.

Body:
I'm trying to install a self-host WCF service on a server with Windows Server 2012.
I was following these steps:

import my pfx file with mmc

run "netsh http add sslcert ipport=0.0.0.0:49000 certhash=e09280ded2322eb858b38b3250e1a488f797b269 appid={4dc3e181-e14b-4a21-b022-59fc669b0914}"

install my service and start it

At first it works well. But after a few hours the ssl crashes and I can only get error msg at client as below

An unhandled exception of type 'System.ServiceModel.CommunicationException' occurred in mscorlib.dll.
  Additional information: An error occurred while making the HTTP request to https://servername:49000/WCFServiceName. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.

run "netsh http delete sslcert ipport=0.0.0.0:49000"
and delete the imported pfx and then redo step1 and 2 can make ssl works again, but the problem will still appears in a few hours.

It's definitely not the SecurityProtocol problem, for I have already tried adding

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

before request. And both server and client uses .Net Framework 4.5.2

I've tried "netsh http show sslcert", and got below result:

    IP:port                      : 0.0.0.0:49000
    Certificate Hash             : e09280ded2322eb858b38b3250e1a488f797b269
    Application ID               : {4dc3e181-e14b-4a21-b022-59fc669b0914}
    Certificate Store Name       : My
    Verify Client Certificate Revocation : Enabled
    Verify Revocation Using Cached Client Certificate Only : Disabled
    Usage Check                  : Enabled
    Revocation Freshness Time    : 0
    URL Retrieval Timeout        : 0
    Ctl Identifier               : (null)
    Ctl Store Name               : (null)
    DS Mapper Usage              : Disabled
    Negotiate Client Certificate : Disabled

I've tried delete the sslcert binding on port 49000 and created an empty website binding to port 49000 in IIS and make my service listening to that port then. It works the first time and lasted for about a week before the same error pops out.

Where should I begin to locate and solve this wired problem?


问:
How to Solve Similar No Of Parameter Combinations in Urls using Mod Rewrite Rule in Htaccess PHP
I have Four Urls which need to be optimized using ht-access PHP.

All Parameter values stored in DB.

First url : has TWO Parameters and values in the un-optimized url.

1st - (scode)Parameter used for Alphabets - Ex: Only state codes: DL or AP

2nd - (disturl)Parameter used for Alphabets,Letters & Symbols  - Ex: District Name: "east-godavarai" District in Andhra Pradesh.

First Url Working - Check Code.

Second Url: has THREE Parameters and values in the un-optimized url.

1st - (scode)Parameter only Alphabets - Ex: AP

2nd - (disturl)Parameter only Alphabets & Hypens   Ex: east-godavari

3rd - (talukurl) Parameter only Alphabets & Hypens Ex: vizag-west

Second Url also working - Check code

Third Url: has TWO Parameters and values in the un-optimized url.

1st - (scode)Parameter only Alphabets - Ex: AP

2nd - (pourl)Parameter only Alphabets, Numbers & Hypens   Ex: Narasaraopeta-712345

Url - Not Working Error - Showing The second Url page - No data is getting displayed.

Fourth Url: has TWO Parameters and values in the un-optimized url.

1st - (scode)Parameter only Alphabets - Ex: AP

2nd - (pincode)Parameter only Numbers - Ex: 712345

Url - Not Working Error - Showing The second Url page - No data is getting displayed.

I tried checking each rule separately, 1st rule & 2nd rule worked. When I tried removing 1st & 2nd urls then third url is working and 4th rule is showing 3rd rule url page.

```<code>RewriteEngine On

RewriteRule ^([0-9a-zA-Z]+)/([-|0-9|a-z|A-Z]+)\.php$ dist.php?scode=$1&disturl=$2 [NC]

RewriteRule ^([0-9a-zA-Z]+)/([-|0-9|a-z|A-Z]+)/([-|0-9|a-z|A-Z]+)\.php$ pos.php?scode=$1&disturl=$2&talukurl=$3 [NC]

RewriteRule ^([a-zA-Z]+)/([-|0-9|a-z|A-Z]+).php loc.php?scode=$1&pourl=$2 [NC]

RewriteRule ^([a-zA-Z]+)/([-|0-9]+)\.php$ pincode.php?scode=$1&pincode=$2 [NC]
</code>```

I am expecting the output something like Optimized Urls..

First Rule:
Main URL: https://www.example.com/dist.php?scode=ap&disturl=krishna

Optimized URL:  https://www.example.com/ap/krishna.php

Second Rule:
Main URL: https://www.example.com/pos.php?scode=ap&disturl=krishna&talukurl=east-godavari

Optimized URL:  https://www.example.com/ap/krishna/east-godavari.php

Third Rule:
Main URL: https://www.example.com/loc.php?scode=ap&pourl=krishnalanka-342563

Optimized URL:  https://www.example.com/ap/krishnalanka-342563.php

Fourth Rule:
Main URL: https://www.example.com/pincode.php?scode=ap&pincode=342563

Optimized URL:  https://www.example.com/ap/342563.php

答: You cannot do that with data alone unless you first look up each possible combination of parameters in your database before passing it to the relevant script, this would also miss non-unique parameter combinations. Try instead to prefix each URL type with another slug, e.g. https://www.example.com/pos/ap/krishna/east-godavari

Body:
I have Four Urls which need to be optimized using ht-access PHP.

All Parameter values stored in DB.

First url : has TWO Parameters and values in the un-optimized url.

1st - (scode)Parameter used for Alphabets - Ex: Only state codes: DL or AP

2nd - (disturl)Parameter used for Alphabets,Letters & Symbols  - Ex: District Name: "east-godavarai" District in Andhra Pradesh.

First Url Working - Check Code.

Second Url: has THREE Parameters and values in the un-optimized url.

1st - (scode)Parameter only Alphabets - Ex: AP

2nd - (disturl)Parameter only Alphabets & Hypens   Ex: east-godavari

3rd - (talukurl) Parameter only Alphabets & Hypens Ex: vizag-west

Second Url also working - Check code

Third Url: has TWO Parameters and values in the un-optimized url.

1st - (scode)Parameter only Alphabets - Ex: AP

2nd - (pourl)Parameter only Alphabets, Numbers & Hypens   Ex: Narasaraopeta-712345

Url - Not Working Error - Showing The second Url page - No data is getting displayed.

Fourth Url: has TWO Parameters and values in the un-optimized url.

1st - (scode)Parameter only Alphabets - Ex: AP

2nd - (pincode)Parameter only Numbers - Ex: 712345

Url - Not Working Error - Showing The second Url page - No data is getting displayed.

I tried checking each rule separately, 1st rule & 2nd rule worked. When I tried removing 1st & 2nd urls then third url is working and 4th rule is showing 3rd rule url page.

RewriteEngine On

RewriteRule ^([0-9a-zA-Z]+)/([-|0-9|a-z|A-Z]+)\.php$ dist.php?scode=$1&disturl=$2 [NC]

RewriteRule ^([0-9a-zA-Z]+)/([-|0-9|a-z|A-Z]+)/([-|0-9|a-z|A-Z]+)\.php$ pos.php?scode=$1&disturl=$2&talukurl=$3 [NC]

RewriteRule ^([a-zA-Z]+)/([-|0-9|a-z|A-Z]+).php loc.php?scode=$1&pourl=$2 [NC]

RewriteRule ^([a-zA-Z]+)/([-|0-9]+)\.php$ pincode.php?scode=$1&pincode=$2 [NC]

I am expecting the output something like Optimized Urls..

First Rule:
Main URL: https://www.example.com/dist.php?scode=ap&disturl=krishna

Optimized URL:  https://www.example.com/ap/krishna.php

Second Rule:
Main URL: https://www.example.com/pos.php?scode=ap&disturl=krishna&talukurl=east-godavari

Optimized URL:  https://www.example.com/ap/krishna/east-godavari.php

Third Rule:
Main URL: https://www.example.com/loc.php?scode=ap&pourl=krishnalanka-342563

Optimized URL:  https://www.example.com/ap/krishnalanka-342563.php

Fourth Rule:
Main URL: https://www.example.com/pincode.php?scode=ap&pincode=342563

Optimized URL:  https://www.example.com/ap/342563.php


问:
Pivot top 100 rows into columns for all tables in a database
My mission is to get top 100 rows from all my tables in a database, and union them into one result output.
Since the tables have varying columncount and varying types, the only way I see to do this is to put the row number as columns, and the column name in the first column. Row 1 from all tables will then be represented in column 2 and so forth.

My skills in SQL aren't good enough to figure this one out, so I hope the community can assist me in this.

Here is some code:

```<code>--Example table
create table Worker (Id int, FirstName nvarchar(max));

--Some data
insert into Worker values (1,'John'),(2,'Jane'),(3,'Elisa');

--Static pivot example
select * from (select
ROW_NUMBER() over (order by Id) as IdRows, FirstName  from worker) as st
pivot
(
    max(FirstName) for IdRows in ([1],[2],[3])
) as pt;

--Code to incorporate to get column name on column 1
select name from sys.columns where object_id('Worker') = object_id;

--Cleanup
drop table Worker;
</code>```

I reckon the static pivot must be dynamic, which is not a problem. The above code is just to create a proof of concept, so I have something to build further on.

End result of query should be like this:

```<code>Column      1       2       3
FirstName   John    Erina   Jane
</code>```

I hope this can be solved without using cursors and temp tables, but maybe that's the way to go?

EDIT:
Forgot to mention, I'm using sqlserver (mssql)

EDIT2:
I'm not all that good at explaining, so here is some more code to do that job for me.
This will add another column to Worker table, and a query to show the desired result. It's the query that has to be "smarter" so it can handle future added tables and columns added. (again, this is a proof of concept. The database has > 200 tables and > 1000 columns)

```<code>--Add a column
alter table Worker add LastName nvarchar(max);
--Add some data
update Worker set LastName = 'Smith' where Id = 1;
update Worker set LastName = 'Smith' where Id = 2;
update Worker set LastName = 'Smith' where Id = 3;

--Query to give desired output (top 100, but only 3 rows in this table)
select 'FirstName' as 'Column',* from (select top 100
ROW_NUMBER() over (order by Id) as IdRows, FirstName  from worker) as st
pivot
(
    max(FirstName) for IdRows in ([1],[2],[3])
) as pt
union
select 'LastName' as 'Column',* from (select top 100
ROW_NUMBER() over (order by Id) as IdRows, LastName  from worker) as st
pivot
(
    max(LastName) for IdRows in ([1],[2],[3])
) as pt
</code>```

答: To solve this, I used temp table, and put it into a loop. Not a good solution, but it works. Had to cast all the data to nvarchar to make it work.</p>

Body:
My mission is to get top 100 rows from all my tables in a database, and union them into one result output.
Since the tables have varying columncount and varying types, the only way I see to do this is to put the row number as columns, and the column name in the first column. Row 1 from all tables will then be represented in column 2 and so forth.

My skills in SQL aren't good enough to figure this one out, so I hope the community can assist me in this.

Here is some code:

--Example table
create table Worker (Id int, FirstName nvarchar(max));

--Some data
insert into Worker values (1,'John'),(2,'Jane'),(3,'Elisa');

--Static pivot example
select * from (select
ROW_NUMBER() over (order by Id) as IdRows, FirstName  from worker) as st
pivot
(
    max(FirstName) for IdRows in ([1],[2],[3])
) as pt;

--Code to incorporate to get column name on column 1
select name from sys.columns where object_id('Worker') = object_id;

--Cleanup
drop table Worker;

I reckon the static pivot must be dynamic, which is not a problem. The above code is just to create a proof of concept, so I have something to build further on.

End result of query should be like this:

Column      1       2       3
FirstName   John    Erina   Jane

I hope this can be solved without using cursors and temp tables, but maybe that's the way to go?

EDIT:
Forgot to mention, I'm using sqlserver (mssql)

EDIT2:
I'm not all that good at explaining, so here is some more code to do that job for me.
This will add another column to Worker table, and a query to show the desired result. It's the query that has to be "smarter" so it can handle future added tables and columns added. (again, this is a proof of concept. The database has > 200 tables and > 1000 columns)

--Add a column
alter table Worker add LastName nvarchar(max);
--Add some data
update Worker set LastName = 'Smith' where Id = 1;
update Worker set LastName = 'Smith' where Id = 2;
update Worker set LastName = 'Smith' where Id = 3;

--Query to give desired output (top 100, but only 3 rows in this table)
select 'FirstName' as 'Column',* from (select top 100
ROW_NUMBER() over (order by Id) as IdRows, FirstName  from worker) as st
pivot
(
    max(FirstName) for IdRows in ([1],[2],[3])
) as pt
union
select 'LastName' as 'Column',* from (select top 100
ROW_NUMBER() over (order by Id) as IdRows, LastName  from worker) as st
pivot
(
    max(LastName) for IdRows in ([1],[2],[3])
) as pt


问:
How to extract anchor elements nested in multiple division elements
I am trying to extract anchor elements from my beautiful soup object with a common class attr each nested in multiple divisions. The divisions are repeated and separated with some scripts

I have tried to take advantage of the common class attrs in the anchor elements to extract them

The code I got:

```<code><div id='container'>
<div class='nested'>
<a href='some url' class='link'>
</a>
</div>
</div>

#some scripts ....

<div id='container'>
<div class='nested'>
<a href='some url' class='link'>
</a>
</div>
</div>
</code>```

What I tried:

```<code>import requests, bs4, webbrowser

webpage=requests.get('some url')
webpage.raise_for_status()
soup=bs4.BeautifulSoup(webpage.text)
links=soup.select('.link a')

for i in range(0,5):
  webrowser.open('intial site url'+links[i].get('href'))
print(links)
</code>```

No tabs were opened.Print links gave a blank list

答:
Replace your line code:

```<code>links=soup.select('.link a')
</code>```

To

```<code>  links=soup.find_all('a',{'class':'link'})
  print(links)
</code>```

O/P:

```<code>[<a class="link" href="some url">
</a>, <a class="link" href="some url">
</a>]
</code>```

To Get href form a tag:

```<code>for link in links:
  href = link['href']
  print(href)
</code>```

Body:
I am trying to extract anchor elements from my beautiful soup object with a common class attr each nested in multiple divisions. The divisions are repeated and separated with some scripts

I have tried to take advantage of the common class attrs in the anchor elements to extract them

The code I got:

#some scripts ....

What I tried:

import requests, bs4, webbrowser

webpage=requests.get('some url')
webpage.raise_for_status()
soup=bs4.BeautifulSoup(webpage.text)
links=soup.select('.link a')

for i in range(0,5):
  webrowser.open('intial site url'+links[i].get('href'))
print(links)

No tabs were opened.Print links gave a blank list

Body:
Replace your line code:

links=soup.select('.link a')

To

  links=soup.find_all('a',{'class':'link'})
  print(links)

O/P:

[<a class="link" href="some url">
</a>, <a class="link" href="some url">
</a>]

To Get href form a tag:

for link in links:
  href = link['href']
  print(href)


问:
how to add/convert certificate file into pkcs12 file
I have received the three certificates(.CER files) to access the production server. How I am going to add/convert these certificates into PKCS12 file.</p>

答:
the server on which you sign your certification $(hostname -f).pem should have the same java version as the nodes you plan to import cert like the following:

$JAVA_HOME/bin/keytool -importcert -alias $(hostname -f) -file /opt/cloudera/security/pki/$(hostname -f).pem -keystore /opt/cloudera/security/pki/$(hostname -f).jks

if you take lower version on the server to sign your certification but you take new java version on the nodes for TLS/SSL, you will see the warning.