问:
Store Image in Room Database using typeconverter to convert bitmap into bytearray. What to write in last parameter of the model class
I don't know how to pass the bitmap as byteArray in the code below. I have added the parameter in the note model class and it is of type byte array. Now how do I use the typeConverter to convert the bitmap to bytearray and pass it? Please help.

The lines in which the parameter is to be added are in "EditActivity", under savebutton.onClicklistener, where I fill the parameters for the modelClass.

Here's my TypeConverter :

```<code>class ImageConverter {

    @TypeConverter
    fun getStringFromBitmap(bitmap: Bitmap): ByteArray {
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        return outputStream.toByteArray()
    }

    @TypeConverter
    fun getBitmapFromString(byteArray: ByteArray): Bitmap{
        return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
    }
}
</code>```

And here's my "EditActivity" that adds image from gallery to the activity:

```<code>class AddEditNoteActivity : AppCompatActivity() {
    lateinit var backButton: FloatingActionButton
    lateinit var editTitle: EditText
    lateinit var editDesc: EditText
    lateinit var saveButton: FloatingActionButton
    lateinit var viewModel: JourViewModel
    lateinit var addImageButton: FloatingActionButton
    lateinit var theimage: ImageView
    lateinit var ImageURI: Uri
    lateinit var bitmap: Bitmap

    var noteID= -1

    companion object{
        const val IMAGE_REQ_CODE=100

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_edit_note)
        editTitle = findViewById(R.id.editNoteTitle)
        editDesc = findViewById(R.id.editNoteDescription)
        saveButton=findViewById(R.id.jourSaveButton)
        backButton=findViewById(R.id.backButton)
        addImageButton=findViewById(R.id.jourAddImgButton)
        theimage=findViewById(R.id.imageView1)

        viewModel= ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        ).get(JourViewModel::class.java)

        val noteType = intent.getStringExtra("noteType")
        if(noteType.equals("Edit")){
            val noteTitle = intent.getStringExtra("noteTitle")
            val noteDesc = intent.getStringExtra("noteDescription")
            noteID= intent.getIntExtra("noteID",-1)
            editTitle.setText(noteTitle)
            editDesc.setText(noteDesc)
        }

        saveButton.setOnClickListener{
            val noteTitle= editTitle.text.toString()
            val noteDesc= editDesc.text.toString()
            val storebyte=

            if(noteType.equals("Edit")){
                if(noteTitle.isNotEmpty() && noteDesc.isNotEmpty()){
                    val sdf= SimpleDateFormat("MMM, dd,yyyy")
                    val currentDate:String= sdf.format(Date())
                    val updateNote = Note(noteTitle, noteDesc, currentDate, )
                    updateNote.id=noteID
                    viewModel.updateNote(updateNote)
                    Toast.makeText(this,"Updated!",Toast.LENGTH_SHORT).show()
                    startActivity(Intent(applicationContext,MainActivity::class.java))
                    this.finish()
                }else{
                    Toast.makeText(this,"Please fill both the columns!",Toast.LENGTH_SHORT).show()
                }
            }else{
                if(noteTitle.isNotEmpty() && noteDesc.isNotEmpty()){
                    val sdf= SimpleDateFormat("MMM dd,yyyy")
                    val currentDate:String= sdf.format(Date())
                    viewModel.addNote(Note(noteTitle,noteDesc,currentDate,))
                    Toast.makeText(this,"Added!",Toast.LENGTH_SHORT).show()
                    startActivity(Intent(applicationContext,MainActivity::class.java))
                    this.finish()
                }else{
                    Toast.makeText(this,"Please fill both the columns!",Toast.LENGTH_SHORT).show()
                }
            }

        }

        backButton.setOnClickListener{
            val intent = Intent(this@AddEditNoteActivity,MainActivity::class.java)
            startActivity(intent)
            this.finish()
        }

        addImageButton.setOnClickListener{
            pickImageGallery()

        }
    }

    private fun pickImageGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/"
        startActivityForResult(intent, IMAGE_REQ_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode== IMAGE_REQ_CODE && resultCode==RESULT_OK){

             ImageURI  = data?.data!!

            if (ImageURI!=null){
                theimage.setImageURI(data?.data)

                try {
                    bitmap =MediaStore.Images.Media.getBitmap(contentResolver, ImageURI)
                    theimage.setImageBitmap(bitmap)
                }catch(exception: IOException){
                    exception.printStackTrace()

                }

            }

        }

    }

}
</code>```

ModelClass:

```<code>@Entity(tableName = "jourTable")
class Note(
    @ColumnInfo(name = "title") val jourTitle:String,
    @ColumnInfo(name = "description") val jourDescription:String,
    @ColumnInfo(name = "date") val jourDate:String,
    @ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB) val jourImage: ByteArray
) {
    @PrimaryKey(autoGenerate = true)var id=0
}
</code>```

答:
UPDATE:

With the help of @MikeT 's response I was able to store data in the database. And
with the help of this I was able to pass bitmap from one activity to another to load the image.

The function is working now, if anyone wants to check out the issue/repo, here you go.

Body:
I don't know how to pass the bitmap as byteArray in the code below. I have added the parameter in the note model class and it is of type byte array. Now how do I use the typeConverter to convert the bitmap to bytearray and pass it? Please help.

The lines in which the parameter is to be added are in "EditActivity", under savebutton.onClicklistener, where I fill the parameters for the modelClass.

Here's my TypeConverter :

class ImageConverter {

    @TypeConverter
    fun getStringFromBitmap(bitmap: Bitmap): ByteArray {
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        return outputStream.toByteArray()
    }

    @TypeConverter
    fun getBitmapFromString(byteArray: ByteArray): Bitmap{
        return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
    }
}

And here's my "EditActivity" that adds image from gallery to the activity:

class AddEditNoteActivity : AppCompatActivity() {
    lateinit var backButton: FloatingActionButton
    lateinit var editTitle: EditText
    lateinit var editDesc: EditText
    lateinit var saveButton: FloatingActionButton
    lateinit var viewModel: JourViewModel
    lateinit var addImageButton: FloatingActionButton
    lateinit var theimage: ImageView
    lateinit var ImageURI: Uri
    lateinit var bitmap: Bitmap

    var noteID= -1

    companion object{
        const val IMAGE_REQ_CODE=100

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_edit_note)
        editTitle = findViewById(R.id.editNoteTitle)
        editDesc = findViewById(R.id.editNoteDescription)
        saveButton=findViewById(R.id.jourSaveButton)
        backButton=findViewById(R.id.backButton)
        addImageButton=findViewById(R.id.jourAddImgButton)
        theimage=findViewById(R.id.imageView1)

        viewModel= ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        ).get(JourViewModel::class.java)

        val noteType = intent.getStringExtra("noteType")
        if(noteType.equals("Edit")){
            val noteTitle = intent.getStringExtra("noteTitle")
            val noteDesc = intent.getStringExtra("noteDescription")
            noteID= intent.getIntExtra("noteID",-1)
            editTitle.setText(noteTitle)
            editDesc.setText(noteDesc)
        }

        saveButton.setOnClickListener{
            val noteTitle= editTitle.text.toString()
            val noteDesc= editDesc.text.toString()
            val storebyte=

            if(noteType.equals("Edit")){
                if(noteTitle.isNotEmpty() && noteDesc.isNotEmpty()){
                    val sdf= SimpleDateFormat("MMM, dd,yyyy")
                    val currentDate:String= sdf.format(Date())
                    val updateNote = Note(noteTitle, noteDesc, currentDate, )
                    updateNote.id=noteID
                    viewModel.updateNote(updateNote)
                    Toast.makeText(this,"Updated!",Toast.LENGTH_SHORT).show()
                    startActivity(Intent(applicationContext,MainActivity::class.java))
                    this.finish()
                }else{
                    Toast.makeText(this,"Please fill both the columns!",Toast.LENGTH_SHORT).show()
                }
            }else{
                if(noteTitle.isNotEmpty() && noteDesc.isNotEmpty()){
                    val sdf= SimpleDateFormat("MMM dd,yyyy")
                    val currentDate:String= sdf.format(Date())
                    viewModel.addNote(Note(noteTitle,noteDesc,currentDate,))
                    Toast.makeText(this,"Added!",Toast.LENGTH_SHORT).show()
                    startActivity(Intent(applicationContext,MainActivity::class.java))
                    this.finish()
                }else{
                    Toast.makeText(this,"Please fill both the columns!",Toast.LENGTH_SHORT).show()
                }
            }

        }

        backButton.setOnClickListener{
            val intent = Intent(this@AddEditNoteActivity,MainActivity::class.java)
            startActivity(intent)
            this.finish()
        }

        addImageButton.setOnClickListener{
            pickImageGallery()

        }
    }

    private fun pickImageGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/"
        startActivityForResult(intent, IMAGE_REQ_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode== IMAGE_REQ_CODE && resultCode==RESULT_OK){

             ImageURI  = data?.data!!

            if (ImageURI!=null){
                theimage.setImageURI(data?.data)

                try {
                    bitmap =MediaStore.Images.Media.getBitmap(contentResolver, ImageURI)
                    theimage.setImageBitmap(bitmap)
                }catch(exception: IOException){
                    exception.printStackTrace()

                }

            }

        }

    }

}

ModelClass:

@Entity(tableName = "jourTable")
class Note(
    @ColumnInfo(name = "title") val jourTitle:String,
    @ColumnInfo(name = "description") val jourDescription:String,
    @ColumnInfo(name = "date") val jourDate:String,
    @ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB) val jourImage: ByteArray
) {
    @PrimaryKey(autoGenerate = true)var id=0
}


来源: stackexchange

问:
How to obtain the invocation list of any event
How to get the delegate list form event of the control in WPF.

I have tried the following code but it will return the field info as null

```<code>TextBox cont = new TextBox();
cont.TextChanged += new TextChangedEventHandler(cont_TextChanged);
FieldInfo fi = cont.GetType().GetField("TextChanged", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
Delegate del = (Delegate)fi.GetValue(cont);
</code>```

答:
Reflection, as recommended by Kenneth J. Sanchez Venegas, is the only way to get an invocation list of event outside of a class. But when performance is important, we can make a helper with compiled lambdas like this:

```<code>public class EventHelper<TClass, TDelegate> where TDelegate : Delegate
{
    public EventHelper(string eventName)
    {
        var fieldInfo = typeof(TClass).GetField(eventName, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) ??
                throw new ArgumentException("Event was not found", nameof(eventName));

        var thisArg = Expression.Parameter(typeof(TClass));
        var body = Expression.Convert(Expression.Field(thisArg, fieldInfo), typeof(TDelegate));
        Get = Expression.Lambda<Func<TClass, TDelegate?>>(body, thisArg).Compile();
    }

    public Func<TClass, TDelegate?> Get { get; }

    public IEnumerable<TDelegate> GetInvocationList(TClass forInstance)
    {
        var eventDelegate = Get(forInstance);
        if (eventDelegate is null)
            yield break;

        foreach (var d in eventDelegate.GetInvocationList())
            yield return (TDelegate)d;
    }
}
</code>```

Assuming we will have one instance of this helper and use it every time:

```<code>private static readonly EventHelper<JsonSerializer, EventHandler<ErrorEventArgs>> _errorHelper = new(nameof(JsonSerializer.Error));
</code>```
```<code>...

JsonSerializerSettings settings = new();
foreach (var errorHandler in _errorHelper.GetInvocationList(serializer))
    settings.Error += errorHandler;

...
</code>```

*I'm using this code to extract settings from Json.NET JsonSerializer so examples are taken from that context

**Code examples using C# 9.0 syntax features, tested on .NET 5 and .NET 6.

ContentLicense: CC BY-SA 3.0

Body:
How to get the delegate list form event of the control in WPF.

I have tried the following code but it will return the field info as null

TextBox cont = new TextBox();
cont.TextChanged += new TextChangedEventHandler(cont_TextChanged);
FieldInfo fi = cont.GetType().GetField("TextChanged", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
Delegate del = (Delegate)fi.GetValue(cont);

Body:
Reflection, as recommended by Kenneth J. Sanchez Venegas, is the only way to get an invocation list of event outside of a class. But when performance is important, we can make a helper with compiled lambdas like this:

public class EventHelper<TClass, TDelegate> where TDelegate : Delegate
{
    public EventHelper(string eventName)
    {
        var fieldInfo = typeof(TClass).GetField(eventName, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) ??
                throw new ArgumentException("Event was not found", nameof(eventName));

        var thisArg = Expression.Parameter(typeof(TClass));
        var body = Expression.Convert(Expression.Field(thisArg, fieldInfo), typeof(TDelegate));
        Get = Expression.Lambda<Func<TClass, TDelegate?>>(body, thisArg).Compile();
    }

    public Func<TClass, TDelegate?> Get { get; }

    public IEnumerable<TDelegate> GetInvocationList(TClass forInstance)
    {
        var eventDelegate = Get(forInstance);
        if (eventDelegate is null)
            yield break;

        foreach (var d in eventDelegate.GetInvocationList())
            yield return (TDelegate)d;
    }
}

Assuming we will have one instance of this helper and use it every time:

private static readonly EventHelper<JsonSerializer, EventHandler<ErrorEventArgs>> _errorHelper = new(nameof(JsonSerializer.Error));

...

JsonSerializerSettings settings = new();
foreach (var errorHandler in _errorHelper.GetInvocationList(serializer))
    settings.Error += errorHandler;

...

*I'm using this code to extract settings from Json.NET JsonSerializer so examples are taken from that context

**Code examples using C# 9.0 syntax features, tested on .NET 5 and .NET 6.

ContentLicense: CC BY-SA 4.0


问:
Export values to Excel file format
Hello I having trouble exporting values from  an array to excel for example how would I
export the following:</p>

```<code>echo "<table ' border='1' >"
    echo "<th>ComputerName</th>"));
    echo "<th>SerialNumber</th>";
    echo "<th>SystemModel</th>";
    echo "<th>DateTime</th>";
    echo "<th>Software</th>";
    echo "<th>Hardware</th>";
    echo "<th>Support</th>";
    echo "<th>Delete</th>";
    echo "</tr>";

$alt_color = 0;
while($row = mysql_fetch_array($result))

  {
    error_reporting (E_ALL ^ E_NOTICE);
    //foreach( $array_values as $value )
 $bgc = ( $alt_color % 2 ? 'Dark' : 'Light' );
     echo "<tr class=".$bgc.">";
    //echo "<td><a href=\"update.php?LSUserID=" .$row['LSUserID']."\">" .$row['LSUserID']."</a></td>";
    echo "<td><a href=\"update.php?LSUserID=" .$row['LSUserID']."\">" .$row['ComputerName']."</a></td>";
    echo "<td>" . $row['SerialNumber'] . "</td>";
    echo "<td>" . $row['SystemModel'] . "</td>";
    echo "<td>" . $row['DateTime'] . "</td>";
</code>```

答:
With phpBlock you can create your db->excel export in a drag drop environment which is inspired from OpenBlock from MIT or AppInventor from Google.
This means it is not necessary to code anything in PHP.

But the export feature is only one possibility of the php-lib. You can use this lib as a dynamic extension to your existing PHP application. Like dyn. formula or calculation.
I hope this more clear than the posting before.

Title: Export values to Excel file format

Body:
Hello I having trouble exporting values from  an array to excel for example how would I
export the following:

echo "
"
    echo "ComputerName	"));
    echo "SerialNumber	";
    echo "SystemModel	";
    echo "DateTime	";
    echo "Software	";
    echo "Hardware	";
    echo "Support	";
    echo "Delete	";
    echo "
";

$alt_color = 0;
while($row = mysql_fetch_array($result))

  {
    error_reporting (E_ALL ^ E_NOTICE);
    //foreach( $array_values as $value )
 $bgc = ( $alt_color % 2 ? 'Dark' : 'Light' );
     echo "
";
    //echo "" .$row['LSUserID']."	";
    echo "" .$row['ComputerName']."	";
    echo "" . $row['SerialNumber'] . "	";
    echo "" . $row['SystemModel'] . "	";
    echo "" . $row['DateTime'] . "	";


问:
Why is the b same as c at the console.log part? B should be same as c after the console.log
im trying to assign b to c after using c in the calculation, they cant be equal at the same time
right now the console.log returns them both with the same number

let b = 1,
  c = 1;

for (i = 0; i < 8; i++) {
  let a = b + c;
  c = a;

  a = b + c;

  console.log(b);
  console.log(c);

  b = c;
}```

答:
Its not the same, just add some separation to see in console.

let b = 1,
  c = 1;

for (i = 0; i < 8; i++) {
  let a = b + c;
  c = a;

  a = b + c;

  console.log(b);
  console.log(c);
  console.log('-------------------------');
  b = c;
}```


问:
How to migrate this Many-to-Many table using an SSIS package?
I have a Many-to-Many table that I need to migrate. The old Many-To-Many table has two INT columns that are the primary keys of the related tables. The new Many-To-Many table has two GUID columns that are the primary keys of the related tables. The GUID column names are StreetId and StreetCategoryId.

I am having an issue with the StreetId GUID column. This column references the Street table, which has the following columns: GUID StreetId, NVARCHAR Street and GUID DrawingId. The old Street table has the same columns, except StreetId and DrawingId are of INT type.

I am trying to migrate the Many-to-Many table using an SSIS Data Flow. The logic is as follows: 1. OLE DB Source that uses the old Many-to-Many StreetCategory_Streets table. 2. Lookup that uses the old Streets table. StreetCategory_Streets.StreetId is linked to Streets.StreetId. Lookup Match Output. 3. Lookup that uses the new Streets table. This is where the challenge arises. What Available Input Column(s) can I use to link to Available Lookup Column(s)? I cannot use StreetCategory_Streets.StreetId because it is of INT type and the Streets.StreetId in the new table is of GUID type.

When I try to migrate the data from the old Many-To-Many table to the new Many-To-Many table, I receive an error message regarding a duplicate record. The reason is that the Street and DrawingId columns can have duplicate values. Only StreetId is unique. However, I cannot link it to the old StreetId column due to INT vs. GUID. How can I migrate this data?

答:
The following is my solution:

Create a backup table of the original table to copy: select * into tableBackup from tableOriginal

Add a temporary column to the backup table and the receiving table: Add a column of INT type to both tableBackup and tableReceiving

Copy the unique values of an existing column to the temporary column in the backup table: update tableBackup set tempColumn = uniqueIDColumn

Copy the values of the backup table to the receiving table using an SSIS Data Flow. Make sure to map the temporary columns with the unique values in both tables: Map tableBackup.tempColumn to tableReceiving.tempColumn

Delete the temporary column in both tables.

In this scenario, the only unique values in the Street table were in the ID column. However, the StreetId column could not be mapped in the old and new tables because they were of different types, INT and GUID.


问:
Extjs 4 combobox default value
I'm migrating my application from ExtJs 3 to 4 version.
I have several comboboxes at my formPanel, and previously I've used hiddenName
and all that stuff to submit valueField instead of displayField.

All my adaptation works fine (value field IS submitting), but I can't set the default values for comboboxes, they are shown as empty after page load.
Previously, I did that just with specifying the 'value' parameter in config.
Is there any ideas how to fix that?

My code - Model and Store:

```<code>Ext.define('idNamePair', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'id', type: 'string'},
        {name: 'name',  type: 'string'}
    ]
});

var dirValuesStore = new Ext.data.Store({
    model: 'idNamePair',
    proxy: {
        type: 'ajax',
        url: '../filtervalues.json',
        reader: {
            type: 'json',
            root: 'dir'
        }
    },
    autoLoad: true
});
</code>```

Combo config:

```<code>{
    triggerAction: 'all',
    id: 'dir_id',
    fieldLabel: 'Direction',
    queryMode: 'local',
    editable: false,
    xtype: 'combo',
    store : dirValuesStore,
    displayField:'name',
    valueField:'id',
    value: 'all',
    width: 250,
    forceSelection:true
}
</code>```

答:
I had the same problem, afaik has to do with selectlist rendering before the items are added to the store. I tried the callback method mentioned above without any luck (guess it would have to be a callback on the selectlist rather than the store).

I added this line after adding items to the store and it works fine:

```<code>Ext.getCmp('selectList').setValue(store.getAt('0').get('id'));
</code>```

Title: Extjs 4 combobox default value

Body:
I'm migrating my application from ExtJs 3 to 4 version.
I have several comboboxes at my formPanel, and previously I've used hiddenName
and all that stuff to submit valueField instead of displayField.

All my adaptation works fine (value field IS submitting), but I can't set the default values for comboboxes, they are shown as empty after page load.
Previously, I did that just with specifying the 'value' parameter in config.
Is there any ideas how to fix that?

My code - Model and Store:

Ext.define('idNamePair', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'id', type: 'string'},
        {name: 'name',  type: 'string'}
    ]
});

var dirValuesStore = new Ext.data.Store({
    model: 'idNamePair',
    proxy: {
        type: 'ajax',
        url: '../filtervalues.json',
        reader: {
            type: 'json',
            root: 'dir'
        }
    },
    autoLoad: true
});

Combo config:

{
    triggerAction: 'all',
    id: 'dir_id',
    fieldLabel: 'Direction',
    queryMode: 'local',
    editable: false,
    xtype: 'combo',
    store : dirValuesStore,
    displayField:'name',
    valueField:'id',
    value: 'all',
    width: 250,
    forceSelection:true
}

Body:
I had the same problem, afaik has to do with selectlist rendering before the items are added to the store. I tried the callback method mentioned above without any luck (guess it would have to be a callback on the selectlist rather than the store).

I added this line after adding items to the store and it works fine:

Ext.getCmp('selectList').setValue(store.getAt('0').get('id'));


问:
PHP error. result not showing as required
I am following some video tutorials. but whenever i run the code it doesnt show the form.it prints the code on chrome.
code is under.</p>

```<code>   <?php
   require('config.php')
   if(isset($_POST['submit'])
   ?>
  <html>
  <head>
  </head>
  <body>
  <form action='regiser.php' method='POST'>
   Name:<input type ='text' name='Name' placeholder='Name'><br>
   Username:<input type ='text' name='Username' placeholder='Username'><br>
   Password:<input type ='password' name='Password' placeholder='Password'>            <br>
  <input type='submit' name='submit' value='Register'>
  </form>
  </body>
  </html>
</code>```

答:
This line has an error:

```<code>if(isset($_POST['submit'])
</code>```

A closing bracket is missing.

Depending on how you look at it either your isset function, or your if statement, is missing a closing bracket.

Body:
I am following some video tutorials. but whenever i run the code it doesnt show the form.it prints the code on chrome.
code is under.

   <?php
   require('config.php')
   if(isset($_POST['submit'])
   ?>

  <form action='regiser.php' method='POST'>
   Name:<input type ='text' name='Name' placeholder='Name'>

   Username:<input type ='text' name='Username' placeholder='Username'>

   Password:<input type ='password' name='Password' placeholder='Password'>

  <input type='submit' name='submit' value='Register'>
  </form>

Body:
This line has an error:

if(isset($_POST['submit'])

A closing bracket is missing.

Depending on how you look at it either your isset function, or your if statement, is missing a closing bracket.


问:
How to get the results of a TDE in MarkLogic in RDF/JSON or Turtle format?
With any kind of Template Driven Extraction (TDE) in MarkLogic, how can I convert the results I get from the tde:node-data-extract function into RDF/JSON format? The JSON format returned by this method is not compliant with RDF/JSON, so I can't use it directly to insert triples into another database. In this case, I don't want to insert the triples into the same database that I'm applying the template against, I just want to use the template to create triples from XML data.

Here's an example of the JSON output that I get from the tde:node-data-extract function:

```<code>{
    "document/pt/document/39627370": [{
            "triple": {
                "subject": "http://www.example.com/document/id/39627370",
                "predicate": "http://www.example.com/typeOf",
                "object": {
                    "datatype": "http://www.w3.org/2001/XMLSchema#string",
                    "value": "http://www.example.com/document"
                }
            }
        },
        {
            "triple": {
                "subject": "http://www.example.com/publisher/Oxford_University_Press",
                "predicate": "http://www.example.com/typeOf",
                "object": {
                    "datatype": "http://www.w3.org/2001/XMLSchema#string",
                    "value": "http://www.example.com/publisher"
                }
            }
        }
   }
}
</code>```

答:
Convert each "triple" property into a triple object using sem.triple(). Then serialize the array of sem.triple objects using sem.rdfSerialize().

https://docs.marklogic.com/sem.triple

https://docs.marklogic.com/sem.rdfSerialize

Body:
With any kind of Template Driven Extraction (TDE) in MarkLogic, how can I convert the results I get from the tde:node-data-extract function into RDF/JSON format? The JSON format returned by this method is not compliant with RDF/JSON, so I can't use it directly to insert triples into another database. In this case, I don't want to insert the triples into the same database that I'm applying the template against, I just want to use the template to create triples from XML data.

Here's an example of the JSON output that I get from the tde:node-data-extract function:

{
    "document/pt/document/39627370": [{
            "triple": {
                "subject": "http://www.example.com/document/id/39627370",
                "predicate": "http://www.example.com/typeOf",
                "object": {
                    "datatype": "http://www.w3.org/2001/XMLSchema#string",
                    "value": "http://www.example.com/document"
                }
            }
        },
        {
            "triple": {
                "subject": "http://www.example.com/publisher/Oxford_University_Press",
                "predicate": "http://www.example.com/typeOf",
                "object": {
                    "datatype": "http://www.w3.org/2001/XMLSchema#string",
                    "value": "http://www.example.com/publisher"
                }
            }
        }
   }
}


问:
Check if User sending request is in different model
I'm trying to create an API using the REST Framework. I ran into a little problem. I want to be able to get a list of events for a specific user by sending a request to the API. Is there a possibility to check if the User sending the request is in the team the event belongs to when an event list is requested?

```<code>class Teams(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=1000, blank=True)
    Users = models.ManyToManyField(User, blank=True)

class Event(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    eventTime = models.DateTimeField()
    title = models.CharField(max_length=100, default='')
    description = models.TextField(max_length=1000, blank=True)
    group = models.ForeignKey(Teams, on_delete=models.CASCADE)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

those are the realtionships between the models i implemented so far

答:
You can do that by overwriting .get_queryset(). This should do the trick:

```<code>class EventList(generics.ListAPIView):

    def get_queryset(self):
        #
        return Event.objects.filter(group__users=self.request.user)
</code>```

Querying many-to-many fields is (in my opinion) not very intuitive.

Event.objects.filter(group__users=self.request.user) basically means "get all events that have a group/team that contain the current user".

Body:
I'm trying to create an API using the REST Framework. I ran into a little problem. I want to be able to get a list of events for a specific user by sending a request to the API. Is there a possibility to check if the User sending the request is in the team the event belongs to when an event list is requested?

class Teams(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=1000, blank=True)
    Users = models.ManyToManyField(User, blank=True)

class Event(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    eventTime = models.DateTimeField()
    title = models.CharField(max_length=100, default='')
    description = models.TextField(max_length=1000, blank=True)
    group = models.ForeignKey(Teams, on_delete=models.CASCADE)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

those are the realtionships between the models i implemented so far

Body:
You can do that by overwriting .get_queryset(). This should do the trick:

class EventList(generics.ListAPIView):

    def get_queryset(self):
        #
        return Event.objects.filter(group__users=self.request.user)

Querying many-to-many fields is (in my opinion) not very intuitive.

Event.objects.filter(group__users=self.request.user) basically means "get all events that have a group/team that contain the current user".


问:
Merge two tables with same columns and get the column value in specific table
I have two tables that have the same column of position and salary.

Table_a

ID
Name
Position
Salary

1
Peter
Sale
10,000

2
Tom
IT
15,000

3
Jane
Sale
12,000

4
Mary
PR
8,000

5
John
IT
14,000

Table_b

ID
Position
Salary

1
Driver
9,000

2
Manager
20,000

4
Sale
13,000

I would like to merge two tables that the output is based on the Position value and Salary value of Table_b.

Output

ID
Name
Position
Salary

1
Peter
Driver
9,000

2
Tom
Manager
20,000

3
Jane
Sale
12,000

4
Mary
Sale
13,000

5
John
IT
14,000

Please give me an advice how can I query and get the above output.

答:
Some rows in table_a don't have a matching row in table_b. Any rows in table_b that don't have a matching row in table_a will be ignored. We assume that ID is unique in each table (meaning for example there won't be two rows in table_b with the same ID value). We will match the rows on ID value.

We can make table_a the driving table in an outer join to table_b. Let's first get that working, returning all the columns from both tables, and verify the return is what we expect.

```<code>SELECT a.ID
     , a.Name
     , a.Position
     , a.Salary
     , b.ID            AS b_ID
     , b.Position      AS b_position
     , b.Salary        AS b_salary
  FROM table_a a
  LEFT
  JOIN table_b b
    ON b.ID = a.ID
 ORDER
    BY a.ID
</code>```

We see that in the result from the first query, on rows where we didn't get a matching row from table_b,  column b_ID (and all the columns from table_b) are NULL.

We can add some expressions in the SELECT list to get the Salary from table_b where we found a matching row, or otherwise return Salary from table_a where we didn't.

There's lots of possible expressions to do that, but they all key on the idea that when we don't have a matching row from the outer joined table, the values in those columns will be NULL.

So the trick is test whether we found a matching row from table_b (or if we did get a matching row in table_b, the row had a NULL value for Salary)

Adding some example expressions to check if b.ID or b.Salary is NULL.

```<code>SELECT a.Name
     , a.Position
     , a.Salary
     , b.ID            AS b_ID
     , b.Position      AS b_position
     , b.Salary        AS b_salary

     , CASE WHEN b.ID IS NULL THEN a.Salary ELSE b.Salary END AS _Salary_x1
     , IFNULL(b.Salary,a.Salary)              AS _Salary_x2
     , IF(b.Salary IS NULL,a.Salary,b.Salary) AS _Salary_x3

  FROM table_a a
  LEFT
  JOIN table_b b
    ON b.ID = a.ID
 ORDER
    BY a.ID
</code>```

Body:
Some rows in table_a don't have a matching row in table_b. Any rows in table_b that don't have a matching row in table_a will be ignored. We assume that ID is unique in each table (meaning for example there won't be two rows in table_b with the same ID value). We will match the rows on ID value.

We can make table_a the driving table in an outer join to table_b. Let's first get that working, returning all the columns from both tables, and verify the return is what we expect.

SELECT a.ID
     , a.Name
     , a.Position
     , a.Salary
     , b.ID            AS b_ID
     , b.Position      AS b_position
     , b.Salary        AS b_salary
  FROM table_a a
  LEFT
  JOIN table_b b
    ON b.ID = a.ID
 ORDER
    BY a.ID

We see that in the result from the first query, on rows where we didn't get a matching row from table_b,  column b_ID (and all the columns from table_b) are NULL.

We can add some expressions in the SELECT list to get the Salary from table_b where we found a matching row, or otherwise return Salary from table_a where we didn't.

There's lots of possible expressions to do that, but they all key on the idea that when we don't have a matching row from the outer joined table, the values in those columns will be NULL.

So the trick is test whether we found a matching row from table_b (or if we did get a matching row in table_b, the row had a NULL value for Salary)

Adding some example expressions to check if b.ID or b.Salary is NULL.

SELECT a.Name
     , a.Position
     , a.Salary
     , b.ID            AS b_ID
     , b.Position      AS b_position
     , b.Salary        AS b_salary

     , CASE WHEN b.ID IS NULL THEN a.Salary ELSE b.Salary END AS _Salary_x1
     , IFNULL(b.Salary,a.Salary)              AS _Salary_x2
     , IF(b.Salary IS NULL,a.Salary,b.Salary) AS _Salary_x3

  FROM table_a a
  LEFT
  JOIN table_b b
    ON b.ID = a.ID
 ORDER
    BY a.ID


问:
As per CSP, can an allowed JavaScript code run another JavaScript code downloading from different domain on a Web page?
I have a JavaScript code snippet embedded inline on a page that downloads and appends to body my main JavaScript code from a different CDN, cdnjs.com/xyz/main.js. So far this has worked fine for my customers. main.js is able to make AJAX calls and perform normally.

Is my assumption correct that clients must have allowed in their CSP policy the cdnjs.com domain? And this process is a required for a setup like mine?

If I change my main JavaScript to additionally download and run new JavaScript code from another domain, cdnjs2.com/abc/new.js, will this new JavaScript code run fine and be able to make AJAX calls?

答:
Is my assumption correct that clients must have allowed in their CSP policy the cdnjs.com domain?

Well, since by default there is no CSP policy for a page, it would be truer to say they must not forbid that domain if they have a CSP.

If I change my main JavaScript to additionally download and run new JavaScript code from another domain…

When there is a CSP, every location that JS is sourced from must be allowed, even if the code that sources it is from an allowed location.


问:
How to click on copy button with cypress
So in my app i have a button and when i click on it, it will save some text into my clipboard, then i can past it by ctrl+v somewhere.

And i am trying to write cypress test for this. Problem is, when i click on that button i got cypress error:

I can´t figured out. Element is clearly viewed on page. I tryied to wait few second before clicking and it didn´t help.

Is there a way how to test it?

Thank you for your answers.

答:
Your application has thrown an error, not cypress. To avoid this, you will want to add this either to your test file or /support/index.js. This code was pulled from this example. Remember cy. requires a test or a hook to work, while Cypress. does not.

```<code>// inspect the caught error
cy.on('uncaught:exception', (e) => {
  if (e.message.includes('Things went bad')) {
    // we expected this error, so let's ignore it
    // and let the test continue
    return false
  }
  // on any other error message the test fails
})
</code>```

Body:
Your application has thrown an error, not cypress. To avoid this, you will want to add this either to your test file or /support/index.js. This code was pulled from this example. Remember cy. requires a test or a hook to work, while Cypress. does not.

// inspect the caught error
cy.on('uncaught:exception', (e) => {
  if (e.message.includes('Things went bad')) {
    // we expected this error, so let's ignore it
    // and let the test continue
    return false
  }
  // on any other error message the test fails
})


问:
Script within a jQueryUI modal dialog box only works once
I have a table that, when any row is clicked, launches a jQueryUI modal dialog box to allow users to edit that record. I use the following script which seems to work, successfully loading the relevant record's details in using AJAX:

```<code>$("#datatbl tr").bind('click', function() {
        var url = 'item_edit.asp?id='+$(this).attr("data-myid");
        var dialog = $('<div style="display:hidden" title="Record details:"></div>').appendTo('body');
        // load remote content
        dialog.load(
            url,
            {},
            function (responseText, textStatus, XMLHttpRequest) {
                dialog.dialog({
                    height: 440,
                    width: 550,
                    autoOpen: false,
                    modal: true,
                    buttons: {
                        "Update this record": function() {
                         $('#editform').submit();
                            },
                        Cancel: function() {
                        $( this ).dialog( "close" );
                        }
                    }
        });
        dialog.dialog('open');
            }
        );
        //prevent the browser to follow the link
        return false;
});
</code>```

It works ok the first time I click on a record, but if I click cancel and try to edit another record, the dialog box does appear (with the correct record details) however, no scripts within the dialog box work - eg: there's a jqueryUI datepicker input and some validation.

There are no javascript errors and, from my limited understanding of FireBug, I can't spot anything going wrong so I would appreciate some advice how to proceed, thanks!

EDIT: Argh! Sometimes, it takes something like typing it out here to spot the obvious. I just realised that the DIV created for the dialog box doesn't get destroyed when the box closes. I've added a line to do this and it now works. Thanks for listening. :)

For future reference, I added an ID to the DIV created in 'var dialog' and removed it in the Cancel function:

```<code>Cancel: function() {
                        $( this ).dialog( "close" );
                        $('#dialogbox').remove();
                        }
</code>```

I'd still appreciate if anybody suggests a better way to handle this behaviour.

答:
You can create the dialog at one time only, not on every load of its content, just set the autoOpen to false.</p>

```<code><div id="dialog">
    <div id="content" style="display:hidden" title="Record details:"></div>
</div>

$('#dialog').dialog({
    height: 440,
    width: 550,
    autoOpen: false,
    modal: true,
    buttons: {
        "Update this record": function() {
            $('#editform').submit();
        },
        Cancel: function() {
            $( this ).dialog( "close" );
        }
    }
});
$("#datatbl tr").bind('click', function() {
    var url = 'item_edit.asp?id='+$(this).attr("data-myid");
    // load remote content
    $('#content').load(url);
    $('#dialog').dialog('open');
    return false;
}};
</code>```

Body:
I have a table that, when any row is clicked, launches a jQueryUI modal dialog box to allow users to edit that record. I use the following script which seems to work, successfully loading the relevant record's details in using AJAX:

$("#datatbl tr").bind('click', function() {
        var url = 'item_edit.asp?id='+$(this).attr("data-myid");
        var dialog = $('

').appendTo('body');
        // load remote content
        dialog.load(
            url,
            {},
            function (responseText, textStatus, XMLHttpRequest) {
                dialog.dialog({
                    height: 440,
                    width: 550,
                    autoOpen: false,
                    modal: true,
                    buttons: {
                        "Update this record": function() {
                         $('#editform').submit();
                            },
                        Cancel: function() {
                        $( this ).dialog( "close" );
                        }
                    }
        });
        dialog.dialog('open');
            }
        );
        //prevent the browser to follow the link
        return false;
});

It works ok the first time I click on a record, but if I click cancel and try to edit another record, the dialog box does appear (with the correct record details) however, no scripts within the dialog box work - eg: there's a jqueryUI datepicker input and some validation.

There are no javascript errors and, from my limited understanding of FireBug, I can't spot anything going wrong so I would appreciate some advice how to proceed, thanks!

EDIT: Argh! Sometimes, it takes something like typing it out here to spot the obvious. I just realised that the DIV created for the dialog box doesn't get destroyed when the box closes. I've added a line to do this and it now works. Thanks for listening. :)

For future reference, I added an ID to the DIV created in 'var dialog' and removed it in the Cancel function:

Cancel: function() {
                        $( this ).dialog( "close" );
                        $('#dialogbox').remove();
                        }

I'd still appreciate if anybody suggests a better way to handle this behaviour.

Body:
You can create the dialog at one time only, not on every load of its content, just set the autoOpen to false.

<div id="dialog">
    <div id="content" style="display:hidden" title="Record details:"></div>
</div>

$('#dialog').dialog({
    height: 440,
    width: 550,
    autoOpen: false,
    modal: true,
    buttons: {
        "Update this record": function() {
            $('#editform').submit();
        },
        Cancel: function() {
            $( this ).dialog( "close" );
        }
    }
});
$("#datatbl tr").bind('click', function() {
    var url = 'item_edit.asp?id='+$(this).attr("data-myid");
    // load remote content
    $('#content').load(url);
    $('#dialog').dialog('open');
    return false;
}};


问:
Running python script in Visual Studio Code; how to get `input ()` to work?

I'm trying to grab a simple input using input(), but when I run the script within Visual Code the program hangs whenever that line of code is hit.

How can I run code within Visual Studio Code and use input()?

task

```<code>{
    "version": "0.1.0",

    "command": "python",

    "isShellCommand": true,

    "showOutput": "always",

    "args": ["${file}"],
}
</code>```

答:
just click on the RUN CODE
option at the top right corner of visual studio ode interference. When you run code it automatically runs (input()) function in Terminal.</p>

Body:
I'm trying to grab a simple input using input(), but when I run the script within Visual Code the program hangs whenever that line of code is hit.

How can I run code within Visual Studio Code and use input()?

task

{
    "version": "0.1.0",

    "command": "python",

    "isShellCommand": true,

    "showOutput": "always",

    "args": ["${file}"],
}


问:
NSLengthFormatter get stringFromMeters: in miles/kilometers only
I am using the NSLengthFormatter class to format the distance between the user and some destination.

```<code>CLLocation *userLocation; //<- Coordinates fetched from CLLocationManager
CLLocation *targetLocation; //<- Some location retrieved from server data

CLLocationDistance distance = [userLocation distanceFromLocation:targetLocation];

NSLengthFormatter *lengthFormatter = [NSLengthFormatter new];
NSString *formattedLength = [lengthFormatter stringFromMeters:distance];
</code>```

Now, if the length is less than 1000 meters, the formatted distance is always shown in yards or meters (depending on the locale).

Eg. if distance = 450.0, the formatted string will be 492.7 yd or 450 m.

How can I tweak NSLengthFormatter to return the distance strings in miles/kilometers only?

答:
```<code>-(NSString *)formattedDistance {

    CLLocationDistance distance = _distance;

    NSLengthFormatter *lengthFormatter = [NSLengthFormatter new];
    [lengthFormatter.numberFormatter setMaximumFractionDigits:1];

    if ([[[NSLocale currentLocale] objectForKey:NSLocaleUsesMetricSystem] boolValue])
    {
        return [lengthFormatter stringFromValue:distance / 1000 unit:NSLengthFormatterUnitKilometer];
    }
    else
    {
        return [lengthFormatter stringFromValue:distance / 1609.34 unit:NSLengthFormatterUnitMile];
    }
}
</code>```

Body:
I am using the NSLengthFormatter class to format the distance between the user and some destination.

CLLocation *userLocation; //<- Coordinates fetched from CLLocationManager
CLLocation *targetLocation; //<- Some location retrieved from server data

CLLocationDistance distance = [userLocation distanceFromLocation:targetLocation];

NSLengthFormatter *lengthFormatter = [NSLengthFormatter new];
NSString *formattedLength = [lengthFormatter stringFromMeters:distance];

Now, if the length is less than 1000 meters, the formatted distance is always shown in yards or meters (depending on the locale).

Eg. if distance = 450.0, the formatted string will be 492.7 yd or 450 m.

How can I tweak NSLengthFormatter to return the distance strings in miles/kilometers only?


问:
SwiftUI: Pattern matching causes view to animate incorrectly
I'm implementing a very simple view (ChildView) that will slide up from the bottom of ParentView when a button is tapped. I've reproduced the issue below in a minimal example.

struct ChildView: View {
    @Binding var foo: String?

    var body: some View {
        HStack {
            if case .some = foo {
                Text("Foo")
            }

            Spacer()

            Text("Bar")
        }
        .offset(y: foo != nil ? 0 : UIScreen.main.bounds.height)
    }
}

struct ParentView: View {
    @State private var foo: String?

    var body: some View {
        ZStack {
            Button(action: {
                withAnimation {
                    foo = "Foo"
                }
            }) {
                Text("Tap me")
            }

            ChildView(foo: $foo)
        }.frame(width: 300, height: 500)
    }
}
```

I pass a binding into ChildView that is a simple String? here, but ultimately it will be an enum instance which I will switch on inside ChildView.

The problem is that Text("Foo") inside ChildView doesn't slide up from the bottom, but rather fades in place. Text("Bar") slides correctly, and the only difference is that the former touches the foo binding. See GIF below:

One can observe the same thing if foo was an enum and we switched on it.

What is going on?

I saw this question, but the accepted answer didn't work for me.

答:
As a bonus, now with enum, hope it helps.

The enum switch case sets a state var which controls the view.

```<code>struct ChildView: View {

    @Binding var myEnum: MyEnum?
    @State private var label = ""

    var body: some View {
        HStack {
            Text(label)

            Spacer()

            Text("Bar")
        }
        .offset(y: myEnum != nil ? 0 : UIScreen.main.bounds.height)

        .onChange(of: myEnum, perform: { newValue in
            switch myEnum {
            case .fun: label = "Fun"
            case .work: label = "Work"
            case .home: label = "Home"
            default: label = ""
            }
        })
    }
}
</code>```

Body:
I'm implementing a very simple view (ChildView) that will slide up from the bottom of ParentView when a button is tapped. I've reproduced the issue below in a minimal example.

struct ChildView: View {
    @Binding var foo: String?

    var body: some View {
        HStack {
            if case .some = foo {
                Text("Foo")
            }

            Spacer()

            Text("Bar")
        }
        .offset(y: foo != nil ? 0 : UIScreen.main.bounds.height)
    }
}

struct ParentView: View {
    @State private var foo: String?

    var body: some View {
        ZStack {
            Button(action: {
                withAnimation {
                    foo = "Foo"
                }
            }) {
                Text("Tap me")
            }

            ChildView(foo: $foo)
        }.frame(width: 300, height: 500)
    }
}

I pass a binding into ChildView that is a simple String? here, but ultimately it will be an enum instance which I will switch on inside ChildView.

The problem is that Text("Foo") inside ChildView doesn't slide up from the bottom, but rather fades in place. Text("Bar") slides correctly, and the only difference is that the former touches the foo binding. See GIF below:

One can observe the same thing if foo was an enum and we switched on it.

What is going on?

I saw this question, but the accepted answer didn't work for me.

Body:
As a bonus, now with enum, hope it helps.

The enum switch case sets a state var which controls the view.

struct ChildView: View {

    @Binding var myEnum: MyEnum?
    @State private var label = ""

    var body: some View {
        HStack {
            Text(label)

            Spacer()

            Text("Bar")
        }
        .offset(y: myEnum != nil ? 0 : UIScreen.main.bounds.height)

        .onChange(of: myEnum, perform: { newValue in
            switch myEnum {
            case .fun: label = "Fun"
            case .work: label = "Work"
            case .home: label = "Home"
            default: label = ""
            }
        })
    }
}


问:
Is it possible to authenticate using JSF 2.0 and Glassfish without realm?
I have a routine that checks if a couple user/password is correct (it simply ask another server and returns true or false). I would like to use it instead of implement a realm file or a jdbc realm. The reason behind this is because I don't want to manage passwords.
Is there any way to implement such an authorization?
I know that programmatic security in servlet 3.0 specifies methods like HttpServletRequest.login. Can I use my own login funcion instead? Can anyone suggest me how?

My application needs just a simple authorization model: if the user is not authenticated he will have access only to the login page; if the user is authenticated he will have access to all the pages.

I'm using JSF 2.0 and Glassfish 3.1.

答:
If you don't want to manage passwords could you use openid/openauth type libraries (a la StackOverflow)?

Glassfish and OpenId


问:
How to Implement IComparable interface?
I am populating an array with instances of a class:

```<code>BankAccount[] a;
. . .

a = new BankAccount[]
{
    new BankAccount("George Smith", 500m),
    new BankAccount("Sid Zimmerman", 300m)
};
</code>```

Once I populate this array, I would like to sort it by balance amounts. In order to do that, I would like to be able to check whether each element is sortable using IComparable.

I need to do this using interfaces. So far I have the following code:

```<code>public interface IComparable
{
    decimal CompareTo(BankAccount obj);
}
</code>```

But I'm not sure if this is the right solution.  Any advice?

答:
This is an example to the multiple fields solution provided by @Daniel Lidström by using tuple:

   public static void Main1()
        {
            BankAccount[] accounts = new BankAccount[]
            {
        new BankAccount()
        {
            Name = "Jack", Balance =150.08M
        }, new BankAccount()
        {
            Name = "James",Balance =70.45M
        }, new BankAccount()
        {
            Name = "Mary",Balance =200.01M
        }, new BankAccount()
        {
            Name = "John",Balance =200.01M
        }};
            Array.Sort(accounts);
            Array.ForEach(accounts, x => Console.WriteLine($"{x.Name} {x.Balance}"));
        }

    }
    public class BankAccount : IComparable<BankAccount>
    {
        public string Name { get; set; }

        public int Balance { get; set; }

        public int CompareTo(BankAccount other) =>
           (Balance,Name).CompareTo(
               (other.Balance,other.Name ));

    }

```

Try it

Title: How to Implement IComparable interface?

Body:
I am populating an array with instances of a class:

BankAccount[] a;
. . .

a = new BankAccount[]
{
    new BankAccount("George Smith", 500m),
    new BankAccount("Sid Zimmerman", 300m)
};

Once I populate this array, I would like to sort it by balance amounts. In order to do that, I would like to be able to check whether each element is sortable using IComparable.

I need to do this using interfaces. So far I have the following code:

public interface IComparable
{
    decimal CompareTo(BankAccount obj);
}

But I'm not sure if this is the right solution.  Any advice?

Body:
This is an example to the multiple fields solution provided by @Daniel Lidström by using tuple:

   public static void Main1()
        {
            BankAccount[] accounts = new BankAccount[]
            {
        new BankAccount()
        {
            Name = "Jack", Balance =150.08M
        }, new BankAccount()
        {
            Name = "James",Balance =70.45M
        }, new BankAccount()
        {
            Name = "Mary",Balance =200.01M
        }, new BankAccount()
        {
            Name = "John",Balance =200.01M
        }};
            Array.Sort(accounts);
            Array.ForEach(accounts, x => Console.WriteLine($"{x.Name} {x.Balance}"));
        }

    }
    public class BankAccount : IComparable<BankAccount>
    {
        public string Name { get; set; }

        public int Balance { get; set; }

        public int CompareTo(BankAccount other) =>
           (Balance,Name).CompareTo(
               (other.Balance,other.Name ));

    }

Try it


问:
how to prevent screen recording on a website in a web browser?
I am making an educational website for one of my clients and he demanded to implement a function that can prevent users to record the screen on the website because the website would have paid content and some Vimeo videos so he doesn't want to allow someone to steal his videos by doing screen record. I know this can be done for android or IOS apps. being a react developer I can also implement this for android apps using expo. but the client wants to do it for a website on a web browser. I've spent 4 hours, searching on the web, still am blanked because I didn't get a single solution.
can you please tell me how can I make it or even if it's possible or not?</p>

答:
Unfortunately, this doesn't appear to be possible. Currently, there is no way for a browser to understand if someone is recording the screen.

It would be quite a security risk if a browser were able to identify something as simple as a screen recorder. It would imply that a browser has far higher level permissions than it should have.

You should convey this to your client. Sometimes clients simply don't understand the technology.


问:
Correctly compute the divergence of a vector field in Python
I am trying to compute the divergence of a vector field:

```<code>Fx  = np.cos(xx + 2*yy)
Fy  = np.sin(xx - 2*yy)
F = np.array([Fx, Fy])
</code>```

Analytic Solution

This is how the divergence (div(F) = dF/dx + dF/dy ) should look like, based on the analytic computation of the divergence (see Wolfram Alpha here):

dFx/dx = d/dx cos(x+2y) = -sin(x+2y)

dFy/dy = d/dy sin(x-2y) = -2*cos(x-2y)

The divergence:

```<code>div_analy = -np.sin(xx + 2*yy) - 2*np.cos(xx - 2*yy)
</code>```

The code:

```<code>import numpy as np
import matplotlib.pyplot as plt

# Number of points (NxN)
N = 50
# Boundaries
ymin = -2.; ymax = 2.
xmin = -2.; xmax = 2.

# Create Meshgrid
x = np.linspace(xmin,xmax, N)
y = np.linspace(ymin,ymax, N)
xx, yy = np.meshgrid(x, y)

# Analytic computation of the divergence (EXACT)
div_analy = -np.sin(xx + 2*yy) - 2*np.cos(xx - 2*yy)

# PLOT
plt.imshow(div_analy , extent=[xmin,xmax,ymin,ymax],  origin="lower", cmap="jet")
</code>```

Numeric Solution

Now, I am trying to obtain the same numerically, so I used this function to compute the divergence

```<code>def divergence(f,sp):
    """ Computes divergence of vector field
    f: array -> vector field components [Fx,Fy,Fz,...]
    sp: array -> spacing between points in respecitve directions [spx, spy,spz,...]
    """
    num_dims = len(f)
    return np.ufunc.reduce(np.add, [np.gradient(f[i], sp[i], axis=i) for i in range(num_dims)])
</code>```

When I plot the divergence using this function:

```<code> # Compute Divergence
 points = [x,y]
 sp = [np.diff(p)[0] for p in points]
 div_num = divergence(F, sp)

 # PLOT
 plt.imshow(div_num, extent=[xmin,xmax,ymin,ymax], origin="lower",  cmap="jet")
</code>```

... I get:

The issue

The numeric solution is different from the analytic solution! What am I doing wrong?

答:
Both graphs are wrong, because you use np.meshgrid the wrong way.

The other parts of your code are expecting xx[a, b], yy[a, b] == x[a], y[b],
where a, b are integers between 0 and 49 in your case.

On the other hand, you write

```<code>xx, yy = np.meshgrid(x, y)
</code>```

which causes xx[a, b], yy[a, b] == x[b], y[a]. Futhermore, the value of div_analy[a, b] becomes -sin(x[b]+2y[a]) - 2cos(x[b]+2y[a]) and the value of div_num[a, b] also becomes some other wrong value.

You can simply fix it by writing

```<code>yy, xx = np.meshgrid(x, y)
</code>```

Then you will see both solutions get the correct result.

By the way, you set N = 50, so that np.linspace(xmin,xmax, N) takes 50 points from interval [-2, 2] and the distance between contiguous points will be 1/49. Setting N=51 may get a more radable line sapce.

Body:
I am trying to compute the divergence of a vector field:

Fx  = np.cos(xx + 2*yy)
Fy  = np.sin(xx - 2*yy)
F = np.array([Fx, Fy])

Analytic Solution

This is how the divergence (div(F) = dF/dx + dF/dy ) should look like, based on the analytic computation of the divergence (see Wolfram Alpha here):

dFx/dx = d/dx cos(x+2y) = -sin(x+2y)

dFy/dy = d/dy sin(x-2y) = -2*cos(x-2y)

The divergence:

div_analy = -np.sin(xx + 2*yy) - 2*np.cos(xx - 2*yy)

The code:

import numpy as np
import matplotlib.pyplot as plt

# Number of points (NxN)
N = 50
# Boundaries
ymin = -2.; ymax = 2.
xmin = -2.; xmax = 2.

# Create Meshgrid
x = np.linspace(xmin,xmax, N)
y = np.linspace(ymin,ymax, N)
xx, yy = np.meshgrid(x, y)

# Analytic computation of the divergence (EXACT)
div_analy = -np.sin(xx + 2*yy) - 2*np.cos(xx - 2*yy)

# PLOT
plt.imshow(div_analy , extent=[xmin,xmax,ymin,ymax],  origin="lower", cmap="jet")

Numeric Solution

Now, I am trying to obtain the same numerically, so I used this function to compute the divergence

def divergence(f,sp):
    """ Computes divergence of vector field
    f: array -> vector field components [Fx,Fy,Fz,...]
    sp: array -> spacing between points in respecitve directions [spx, spy,spz,...]
    """
    num_dims = len(f)
    return np.ufunc.reduce(np.add, [np.gradient(f[i], sp[i], axis=i) for i in range(num_dims)])

When I plot the divergence using this function:

 # Compute Divergence
 points = [x,y]
 sp = [np.diff(p)[0] for p in points]
 div_num = divergence(F, sp)

 # PLOT
 plt.imshow(div_num, extent=[xmin,xmax,ymin,ymax], origin="lower",  cmap="jet")

... I get:

The issue

The numeric solution is different from the analytic solution! What am I doing wrong?

Body:
Both graphs are wrong, because you use np.meshgrid the wrong way.

The other parts of your code are expecting xx[a, b], yy[a, b] == x[a], y[b],
where a, b are integers between 0 and 49 in your case.

On the other hand, you write

xx, yy = np.meshgrid(x, y)

which causes xx[a, b], yy[a, b] == x[b], y[a]. Futhermore, the value of div_analy[a, b] becomes -sin(x[b]+2y[a]) - 2cos(x[b]+2y[a]) and the value of div_num[a, b] also becomes some other wrong value.

You can simply fix it by writing

yy, xx = np.meshgrid(x, y)

Then you will see both solutions get the correct result.

By the way, you set N = 50, so that np.linspace(xmin,xmax, N) takes 50 points from interval [-2, 2] and the distance between contiguous points will be 1/49. Setting N=51 may get a more radable line sapce.


问:
Django DetailView don't show data in template
Hello I'm just starting use the CBV in Django. My ListView working normal it can get the id in models except DetailView. It don't show the detail data.

https://drive.google.com/file/d/17yeU-LdvV_yLjnBB2A2gYt5ymSeKvPAR/view?usp=sharing

Here the code:

models.py:

```<code>class School(models.Model):
    name = models.CharField(max_length=125)
    principal = models.CharField(max_length=125)
    location = models.CharField(max_length=125)

def __str__(self):
    return self.name

class Student(models.Model):
    name = models.CharField(max_length=70)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE)

    def __str__(self):
        return self.name
</code>```

urls.py:

```<code>  urlpatterns = [
    path('',views.School_List.as_view(),name='school_list'),
    path('<int:pk>/',views.School_Detail.as_view(),name='school_detail'),
]
</code>```

views.py:

```<code>class School_List(ListView):
    context_object_name = 'schoollist'
    model = School

class School_Detail(DetailView):
    contex_object_name = 'schooldetail'
    model = School
    template_name = 'basicapp/School_detail.html'
</code>```

detail.html:

```<code>{% block content %}
    <h1>Site showing School Detail</h1>
    <div class="container">
        <div class="p-5 text-white bg-dark rounded-3 container">
            <p>Name: {{schooldetail.name}}</p>
            <p>Principal: {{schooldetail.principal}}</p>
            <p>Location: {{schooldetail.location}}</p>
            <h2>Student: </h2>
            {% for student in schooldetail.students.all %}
                <p>{{student.name}} who is {{student.age}} years old</p>
            {% endfor %}
        </div>
    </div>
{% endblock %}
</code>```

Thank you

答:
it should be {{schooldetail.school.name}} not {{schooldetaill.name}} as you using Student model in your details views so you can access School model via your foreign key fields of Student model.

```<code>{% block content %}
        <h1>Site showing School Detail</h1>
        <div class="container">
            <div class="p-5 text-white bg-dark rounded-3 container">
                <p>Name: {{schooldetail.school.name}}</p>
                <p>Principal: {{schooldetail.school.principal}}</p>
                <p>Location: {{schooldetail.school.location}}</p>
                <h2>Student: </h2>
                {% for student in schooldetail.students.all %}
                    <p>{{student.name}} who is {{student.age}} years old</p>
                {% endfor %}
            </div>
        </div>
    {% endblock %}
</code>```

Body:
Hello I'm just starting use the CBV in Django. My ListView working normal it can get the id in models except DetailView. It don't show the detail data.

https://drive.google.com/file/d/17yeU-LdvV_yLjnBB2A2gYt5ymSeKvPAR/view?usp=sharing

Here the code:

models.py:

class School(models.Model):
    name = models.CharField(max_length=125)
    principal = models.CharField(max_length=125)
    location = models.CharField(max_length=125)

def __str__(self):
    return self.name

class Student(models.Model):
    name = models.CharField(max_length=70)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE)

    def __str__(self):
        return self.name

urls.py:

  urlpatterns = [
    path('',views.School_List.as_view(),name='school_list'),
    path('<int:pk>/',views.School_Detail.as_view(),name='school_detail'),
]

views.py:

class School_List(ListView):
    context_object_name = 'schoollist'
    model = School

class School_Detail(DetailView):
    contex_object_name = 'schooldetail'
    model = School
    template_name = 'basicapp/School_detail.html'

detail.html:

{% block content %}

Site showing School Detail

Name: {{schooldetail.name}}

Principal: {{schooldetail.principal}}

Location: {{schooldetail.location}}

Student:

            {% for student in schooldetail.students.all %}

{{student.name}} who is {{student.age}} years old

            {% endfor %}

{% endblock %}

Thank you

Body:
it should be {{schooldetail.school.name}} not {{schooldetaill.name}} as you using Student model in your details views so you can access School model via your foreign key fields of Student model.

{% block content %}
        <h1>Site showing School Detail</h1>
        <div class="container">
            <div class="p-5 text-white bg-dark rounded-3 container">
                <p>Name: {{schooldetail.school.name}}</p>
                <p>Principal: {{schooldetail.school.principal}}</p>
                <p>Location: {{schooldetail.school.location}}</p>
                <h2>Student: </h2>
                {% for student in schooldetail.students.all %}
                    <p>{{student.name}} who is {{student.age}} years old</p>
                {% endfor %}
            </div>
        </div>
    {% endblock %}


问:
Adding role to user does not work, giving "Missing Permissions" error - discord.py
I have started making a Discord bot which follows basic commands like kick, ban, etc. I was trying to make a verify function which adds the "Member" role to a user when they activate the command. However, when the bot tries running the line await author.add_roles(role), it gives back this error:

```<code>An exception has occurred while executing command `verify`:
...
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
</code>```

I have checked if the bot has the right permissions to execute this command, and it does. It has the Administrator permission which should be enough to give a role to a user.

This is the code I'm working with:

```<code>@slash.slash(
    name="verify",
    description="...",
    guild_ids=guilds
)

async def _verify(ctx: SlashCommand):
    role = discord.utils.get(ctx.guild.roles, name="Member")
    if role not in ctx.author.roles: # I am using ctx.author instead of ctx.message.author, because this is a slash command.
        await author.add_roles(role)
</code>```

答: I totally forgot that you cannot manage a role above yours, and I had the Member role above the bot's role. This is why it gave the error.</p>

Body:
I have started making a Discord bot which follows basic commands like kick, ban, etc. I was trying to make a verify function which adds the "Member" role to a user when they activate the command. However, when the bot tries running the line await author.add_roles(role), it gives back this error:

An exception has occurred while executing command `verify`:
...
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

I have checked if the bot has the right permissions to execute this command, and it does. It has the Administrator permission which should be enough to give a role to a user.

This is the code I'm working with:

@slash.slash(
    name="verify",
    description="...",
    guild_ids=guilds
)

async def _verify(ctx: SlashCommand):
    role = discord.utils.get(ctx.guild.roles, name="Member")
    if role not in ctx.author.roles: # I am using ctx.author instead of ctx.message.author, because this is a slash command.
        await author.add_roles(role)


问:
Developing Generic AXI4 Peripheral with Chisel
I want to develop a generic AXI4 peripheral with Chisel. Can I use the Rocket-Chip's AMBA library for this purpose? I could only find the document in the link below on this subject;

MMIO-Peripherals

However, the example in this document is designed to be used with the Rocket-Chip. I want to develop a standalone AXI4 peripheral.

答:
Your question mentions following:

I want to develop a standalone Axi4 peripheral

When I had started developing AXI4 interfaces in Chisel, my starting point was the Chisel official documentation where they start with a typical Verilog peripheral using AXI4 for a write channel as following:

```<code> module my_module(

// Write Channel
  input        AXI_AWVALID,
  output       AXI_AWREADY,
  input [3:0]  AXI_AWID,
  input [19:0] AXI_AWADDR,
  input [1:0]  AXI_AWLEN,
  input [1:0]  AXI_AWSIZE,
  // ...
);
</code>```

To this end, the Chisel Bundle would be as following:

```<code>class VerilogAXIBundle(val addrWidth: Int) extends Bundle {
  val AWVALID = Output(Bool())
  val AWREADY = Input(Bool())
  val AWID = Output(UInt(4.W))
  val AWADDR = Output(UInt(addrWidth.W))
  val AWLEN = Output(UInt(2.W))
  val AWSIZE = Output(UInt(2.W))
  // The rest of AW and other AXI channels here
}

// Instantiated as
class my_module extends RawModule {
  val AXI = IO(new VerilogAXIBundle(20))
}

</code>```

Although the aforementioned example is trivial but this was helpful for me to start writing generic AXI4 interfaces in Chisel.

Having said that, I have also used some of the following resources to develop AXI interfaces in Chisel:

AXI-in-Chisel

AXI interfaces-in-Chisel

Body:
Your question mentions following:

I want to develop a standalone Axi4 peripheral

When I had started developing AXI4 interfaces in Chisel, my starting point was the Chisel official documentation where they start with a typical Verilog peripheral using AXI4 for a write channel as following:

 module my_module(

// Write Channel
  input        AXI_AWVALID,
  output       AXI_AWREADY,
  input [3:0]  AXI_AWID,
  input [19:0] AXI_AWADDR,
  input [1:0]  AXI_AWLEN,
  input [1:0]  AXI_AWSIZE,
  // ...
);

To this end, the Chisel Bundle would be as following:

class VerilogAXIBundle(val addrWidth: Int) extends Bundle {
  val AWVALID = Output(Bool())
  val AWREADY = Input(Bool())
  val AWID = Output(UInt(4.W))
  val AWADDR = Output(UInt(addrWidth.W))
  val AWLEN = Output(UInt(2.W))
  val AWSIZE = Output(UInt(2.W))
  // The rest of AW and other AXI channels here
}

// Instantiated as
class my_module extends RawModule {
  val AXI = IO(new VerilogAXIBundle(20))
}

Although the aforementioned example is trivial but this was helpful for me to start writing generic AXI4 interfaces in Chisel.

Having said that, I have also used some of the following resources to develop AXI interfaces in Chisel:

AXI-in-Chisel

AXI interfaces-in-Chisel


问:
Could not build the application for the simulator. Error launching application on iPhone 11 Pro Max
My problem is I cannot start debugging on iOS simulator for some reason. I have tried several solutions it helped in their ways I guess but the problem is not gone and I am desperate now. I don't know how exactly is this site works or is there any existing solution, but thing is I couldn't find and I need your help.

Error is here:

```<code>Launching lib/main.dart on iPhone 11 Pro Max in debug mode...
Running Xcode build...
Xcode build done.                                           45,6s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:155:24: error: no visible @interface for 'FIRQuery' declares the selector 'queryWhereField:arrayContainsAny:'
            query = [query queryWhereField:fieldName arrayContainsAny:value];
                     ~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:157:24: error: no visible @interface for 'FIRQuery' declares the selector 'queryWhereFieldPath:arrayContainsAny:'
            query = [query queryWhereFieldPath:fieldPath arrayContainsAny:value];
                     ~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:163:24: error: no visible @interface for 'FIRQuery' declares the selector 'queryWhereField:in:'
            query = [query queryWhereField:fieldName in:value];
                     ~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:165:24: error: no visible @interface for 'FIRQuery' declares the selector 'queryWhereFieldPath:in:'
            query = [query queryWhereFieldPath:fieldPath in:value];
                     ~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:764:16: warning: 'timestampsInSnapshotsEnabled' is deprecated [-Wdeprecated-declarations]
          settings.timestampsInSnapshotsEnabled = (bool)call.arguments[@"timestampsInSnapshotsEnabled"];
                   ^
    In module 'FirebaseFirestore' imported from /Users/omerugurerden/AndroidStudioProjects/faltana/ios/Pods/Headers/Public/Firebase/Firebase.h:31:
    /Users/omerugurerden/AndroidStudioProjects/faltana/ios/Pods/FirebaseFirestore/Firestore/Source/Public/FIRFirestoreSettings.h:69:20: note: 'timestampsInSnapshotsEnabled' has been explicitly marked deprecated here
        __attribute__((deprecated));
                       ^
    1 warning and 4 errors generated.
    note: Using new build system
    note: Planning build
    note: Constructing build description
    warning: Mapping architecture armv7 to i386. Ensure that this target's Architectures and Valid Architectures build settings are configured correctly for the iOS Simulator platform. (in target 'image_picker' from project 'Pods')
    warning: Mapping architecture arm64 to x86_64. Ensure that this target's Architectures and Valid Architectures build settings are configured correctly for the iOS Simulator platform. (in target 'image_picker' from project 'Pods')
    warning: Mapping architecture armv7 to i386. Ensure that this target's Architectures and Valid Architectures build settings are configured correctly for the iOS Simulator platform. (in target 'in_app_purchase' from project 'Pods')
    warning: Mapping architecture arm64 to x86_64. Ensure that this target's Architectures and Valid Architectures build settings are configured correctly for the iOS Simulator platform. (in target 'in_app_purchase' from project 'Pods')
    warning: Capabilities for Signing & Capabilities may not function correctly because its entitlements use a placeholder team ID. To resolve this, select a development team in the Runner editor. (in target 'Runner' from project 'Runner')

Could not build the application for the simulator.
Error launching application on iPhone 11 Pro Max.

</code>```

and my flutter doctor is here

```<code>[✓] Flutter (Channel stable, v1.12.13+hotfix.5, on Mac OS X 10.15.2 19C57,
    locale tr-TR)
    • Flutter version 1.12.13+hotfix.5 at /Users/omerugurerden/Developer/flutter
    • Framework revision 27321ebbad (7 weeks ago), 2019-12-10 18:15:01 -0800
    • Engine revision 2994f7e1e6
    • Dart version 2.7.0

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/omerugurerden/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling
      support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_202-release-1483-b49-5587405)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.3.1, Build version 11C504
    • CocoaPods version 1.8.4

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 42.1.1
    • Dart plugin version 191.8593
    • Java version OpenJDK Runtime Environment (build
      1.8.0_202-release-1483-b49-5587405)

[✓] Connected device (1 available)
    • iPhone 11 Pro Max • E8102A9F-0AC3-497D-8DB7-44F965E3E533 • ios •
      com.apple.CoreSimulator.SimRuntime.iOS-13-3 (simulator)

• No issues found!

</code>```

Edit: Can it be because of I don't have developer account yet?

答:
After investigating quite a while, I found out about running flutter with the -v option (flutter run -v).

Initially I was playing around with custom icons in my app and then suddenly stumbled upon the error mentioned above. The problem was that I had structured my assets as /assets/icons/Icon.tff and forgot the assets path infront of my  asset declaration:

Before:

```<code>fonts:
    - family: MyFlutterApp
      fonts:
        - asset: icons/MyFlutterApp.ttf
</code>```

After:

```<code>fonts:
    - family: MyFlutterApp
      fonts:
        - asset: assets/icons/MyFlutterApp.ttf
</code>```

I hope I can help someone not to waste so much time on this error as I did :D

Body:
My problem is I cannot start debugging on iOS simulator for some reason. I have tried several solutions it helped in their ways I guess but the problem is not gone and I am desperate now. I don't know how exactly is this site works or is there any existing solution, but thing is I couldn't find and I need your help.

Error is here:

Launching lib/main.dart on iPhone 11 Pro Max in debug mode...
Running Xcode build...
Xcode build done.                                           45,6s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:155:24: error: no visible @interface for 'FIRQuery' declares the selector 'queryWhereField:arrayContainsAny:'
            query = [query queryWhereField:fieldName arrayContainsAny:value];
                     ~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:157:24: error: no visible @interface for 'FIRQuery' declares the selector 'queryWhereFieldPath:arrayContainsAny:'
            query = [query queryWhereFieldPath:fieldPath arrayContainsAny:value];
                     ~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:163:24: error: no visible @interface for 'FIRQuery' declares the selector 'queryWhereField:in:'
            query = [query queryWhereField:fieldName in:value];
                     ~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:165:24: error: no visible @interface for 'FIRQuery' declares the selector 'queryWhereFieldPath:in:'
            query = [query queryWhereFieldPath:fieldPath in:value];
                     ~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/omerugurerden/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.12.11/ios/Classes/CloudFirestorePlugin.m:764:16: warning: 'timestampsInSnapshotsEnabled' is deprecated [-Wdeprecated-declarations]
          settings.timestampsInSnapshotsEnabled = (bool)call.arguments[@"timestampsInSnapshotsEnabled"];
                   ^
    In module 'FirebaseFirestore' imported from /Users/omerugurerden/AndroidStudioProjects/faltana/ios/Pods/Headers/Public/Firebase/Firebase.h:31:
    /Users/omerugurerden/AndroidStudioProjects/faltana/ios/Pods/FirebaseFirestore/Firestore/Source/Public/FIRFirestoreSettings.h:69:20: note: 'timestampsInSnapshotsEnabled' has been explicitly marked deprecated here
        __attribute__((deprecated));
                       ^
    1 warning and 4 errors generated.
    note: Using new build system
    note: Planning build
    note: Constructing build description
    warning: Mapping architecture armv7 to i386. Ensure that this target's Architectures and Valid Architectures build settings are configured correctly for the iOS Simulator platform. (in target 'image_picker' from project 'Pods')
    warning: Mapping architecture arm64 to x86_64. Ensure that this target's Architectures and Valid Architectures build settings are configured correctly for the iOS Simulator platform. (in target 'image_picker' from project 'Pods')
    warning: Mapping architecture armv7 to i386. Ensure that this target's Architectures and Valid Architectures build settings are configured correctly for the iOS Simulator platform. (in target 'in_app_purchase' from project 'Pods')
    warning: Mapping architecture arm64 to x86_64. Ensure that this target's Architectures and Valid Architectures build settings are configured correctly for the iOS Simulator platform. (in target 'in_app_purchase' from project 'Pods')
    warning: Capabilities for Signing & Capabilities may not function correctly because its entitlements use a placeholder team ID. To resolve this, select a development team in the Runner editor. (in target 'Runner' from project 'Runner')

Could not build the application for the simulator.
Error launching application on iPhone 11 Pro Max.

and my flutter doctor is here

[✓] Flutter (Channel stable, v1.12.13+hotfix.5, on Mac OS X 10.15.2 19C57,
    locale tr-TR)
    • Flutter version 1.12.13+hotfix.5 at /Users/omerugurerden/Developer/flutter
    • Framework revision 27321ebbad (7 weeks ago), 2019-12-10 18:15:01 -0800
    • Engine revision 2994f7e1e6
    • Dart version 2.7.0

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/omerugurerden/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling
      support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_202-release-1483-b49-5587405)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.3.1, Build version 11C504
    • CocoaPods version 1.8.4

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 42.1.1
    • Dart plugin version 191.8593
    • Java version OpenJDK Runtime Environment (build
      1.8.0_202-release-1483-b49-5587405)

[✓] Connected device (1 available)
    • iPhone 11 Pro Max • E8102A9F-0AC3-497D-8DB7-44F965E3E533 • ios •
      com.apple.CoreSimulator.SimRuntime.iOS-13-3 (simulator)

• No issues found!

Edit: Can it be because of I don't have developer account yet?

Body:
After investigating quite a while, I found out about running flutter with the -v option (flutter run -v).

Initially I was playing around with custom icons in my app and then suddenly stumbled upon the error mentioned above. The problem was that I had structured my assets as /assets/icons/Icon.tff and forgot the assets path infront of my  asset declaration:

Before:

fonts:
    - family: MyFlutterApp
      fonts:
        - asset: icons/MyFlutterApp.ttf

After:

fonts:
    - family: MyFlutterApp
      fonts:
        - asset: assets/icons/MyFlutterApp.ttf

I hope I can help someone not to waste so much time on this error as I did :D


问:
In a grouped SQL query, efficiently discard groups that have or do not have some values in a column
I am trying to construct a query that aggregates records in a table while filtering out groups based on constraints that involve the presence or absence of certain values in one of the columns. Here is some example data:

CREATE TABLE test (
person_id smallint,
position_id smallint
);

INSERT INTO test
VALUES (1, 30), (1, 99), (1, 98), (2, 98), (2, 99), (3, 30), (3, 28);

SELECT * FROM test;
```
```+-----------+-------------+
| person_id | position_id |
+-----------+-------------+
|         1 |          30 |
|         1 |          99 |
|         1 |          98 |
|         2 |          98 |
|         2 |          99 |
|         3 |          30 |
|         3 |          28 |
+-----------+-------------+
```
<p>I want to aggregate this over person_id, but only for persons who have position 30, and do not have position 28 (for example). The correct query result should be:</p>
```+-----------+------------+
| person_id | positions  |
+-----------+------------+
|         1 | 30, 99, 98 |
+-----------+------------+
```
<p>The question is, <strong>how to do this efficiently?</strong> The actual table I will be doing this on is larger.</p>
<p>I have two working queries that get the correct result:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT person_id, Group_concat(position_id SEPARATOR ', ') AS positions
FROM test
GROUP BY person_id
HAVING Sum(CASE WHEN position_id = 30 THEN 1 ELSE 0 END) > 0
AND Sum(CASE WHEN position_id = 28 THEN 1 ELSE 0 END) = 0;

SELECT person_id, Group_concat(position_id SEPARATOR ', ') AS positions
FROM test
GROUP BY person_id
HAVING Max(position_id = 30) = 1
AND Max(position_id = 28) = 0;
</code>```

However, it seems to me that it shouldn't be necessary to actually do the full aggregations (with Sum() or Max()) for each group, like these queries do, and that it would be more efficient to reformulate this using logical 'any' conditions. E.g.

the first time I encounter a '30' position_id, I have satisfied the first condition;

the first time I encounter a '28' position_id, I have failed the second condition;

there is no need to proceed through the rest of the position_id's for a group after that. However, I'm not sure how to do that, and maybe I am in any case on the wrong track here.

This is using MySQL 8.

答:
You can try with EXISTS and NOT EXISTS

```<code>SELECT person_id, Group_concat(position_id SEPARATOR ', ') AS positions
from test t
WHERE EXISTS  ( SELECT person_id
                     FROM test t1
                     WHERE t.person_id=t1.person_id
                     AND t1.position_id=30
                   )
AND  NOT EXISTS  (  SELECT person_id
                     FROM test t2
                     WHERE t.person_id=t2.person_id
                     AND t2.position_id=28  )
GROUP BY person_id ;
</code>```

Result:

```<code>person_id positions
    1     30, 99, 98
</code>```

Demo

Body:
I am trying to construct a query that aggregates records in a table while filtering out groups based on constraints that involve the presence or absence of certain values in one of the columns. Here is some example data:

CREATE TABLE test (
person_id smallint,
position_id smallint
);

INSERT INTO test
VALUES (1, 30), (1, 99), (1, 98), (2, 98), (2, 99), (3, 30), (3, 28);

SELECT * FROM test;

+-----------+-------------+
| person_id | position_id |
+-----------+-------------+
|         1 |          30 |
|         1 |          99 |
|         1 |          98 |
|         2 |          98 |
|         2 |          99 |
|         3 |          30 |
|         3 |          28 |
+-----------+-------------+

I want to aggregate this over person_id, but only for persons who have position 30, and do not have position 28 (for example). The correct query result should be:

+-----------+------------+
| person_id | positions  |
+-----------+------------+
|         1 | 30, 99, 98 |
+-----------+------------+

The question is, how to do this efficiently? The actual table I will be doing this on is larger.

I have two working queries that get the correct result:

SELECT person_id, Group_concat(position_id SEPARATOR ', ') AS positions
FROM test
GROUP BY person_id
HAVING Sum(CASE WHEN position_id = 30 THEN 1 ELSE 0 END) > 0
AND Sum(CASE WHEN position_id = 28 THEN 1 ELSE 0 END) = 0;

SELECT person_id, Group_concat(position_id SEPARATOR ', ') AS positions
FROM test
GROUP BY person_id
HAVING Max(position_id = 30) = 1
AND Max(position_id = 28) = 0;

However, it seems to me that it shouldn't be necessary to actually do the full aggregations (with Sum() or Max()) for each group, like these queries do, and that it would be more efficient to reformulate this using logical 'any' conditions. E.g.

the first time I encounter a '30' position_id, I have satisfied the first condition;

the first time I encounter a '28' position_id, I have failed the second condition;

there is no need to proceed through the rest of the position_id's for a group after that. However, I'm not sure how to do that, and maybe I am in any case on the wrong track here.

This is using MySQL 8.

Body:
You can try with EXISTS and NOT EXISTS

SELECT person_id, Group_concat(position_id SEPARATOR ', ') AS positions
from test t
WHERE EXISTS  ( SELECT person_id
                     FROM test t1
                     WHERE t.person_id=t1.person_id
                     AND t1.position_id=30
                   )
AND  NOT EXISTS  (  SELECT person_id
                     FROM test t2
                     WHERE t.person_id=t2.person_id
                     AND t2.position_id=28  )
GROUP BY person_id ;

Result:

person_id positions
    1     30, 99, 98

Demo


问:
Displaying large amount of data
I am working on a mobile application using Bluetooth sensor. My goal is to visualize Bluetooth data on graph. I have 3 different pages on my mobile application:

First page having 3 channels (you can imagine it as as 1 graph and 3 signals, thus 3 curves)

Second page having 8 channels

Third page having 3 channels

The moment I have many channels (like at the second page, 8 channels) the display is slowing down. It is so slow that I cannot even switch between pages. Like if I am clicking but nothing is happening, totally freezed.

I am guessing it is because of the display library that I am using. For those who already have experienced the same issue, any suggestions about real-time charts in Flutter? I have already tested Syncfusion and it is indeed freezing.

Thank you very much.

答: Answering my own question because having discovered many libraries, I kind of found the answer: I have tested Flutter Charts library. It works perfectly fine and looks good. Even though I am displaying +3 channel per page, it is not lagging and I can easily switch between pages.</p>

Title: Displaying large amount of data


问:
A SQL Server function to generate of sequential numbers
I would like to have a SQL Server function dbo.GetNextNumber(), which would generate sequential numbers for each call. As far as I understand this is impossible with a native T-SQL function as SQL Server insists the functions has to be deterministic. But, if you could show me a native T-SQL function that does this would really make my day.

I thought perhaps this could be possible to write using a CLR function. As CLR functions are static, the sequence numbers need to be stored in the calling context of the set operation, as storing it as a static variable would result in several connections using the same sequence, resulting in not-so-sequential numbers. I do not know enough about embedded CLR to see if set operation's (select, update, delete, insert) calling context is reachable from the CLR side.

At the end of the day, the following query

```<code>select dbo.GetNextNumber() from sysobjects
</code>```

must return the result

```<code>1
2
3
4
5
</code>```

It is OK if another function call to reset the context is necessary like

```<code>exec dbo.ResetSequenceNumbers()
</code>```

To prevent some misunderstandings and reduce the chances of wasting your time answering wrong question, please note that I am not looking for an ID generation function for a table and I am aware of some hacks (albeit using a proc not a function) that involves some temp tables with identity columns. The ROW_NUMBER() function is close but it also does not cut.

Thanks a lot for any responses

Kemal

P.S. It is amazing that SQL Server does have a built-in function for that. A function (provided that it cannot be used in joins and where clauses) is really easy to do and extremely useful, but for some reason it is not included.

答:
As you have implemented the CLR sequence based on my article related to the calculation of Running Totals, you can achieve the same using the ROW_NUBER() function.

The ROW_NUMBER() function requires the ORDER BY in the OVER clause, however there is a nice workaround how to avoid sorting due to the ORDER BY. You cannot put an expression in the order by, but you can put SELECT aConstant there. So you can easily achieve number generating using below statement.

```<code>SELECT
    ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber,
    *
FROM aTable
</code>```

Body:
I would like to have a SQL Server function dbo.GetNextNumber(), which would generate sequential numbers for each call. As far as I understand this is impossible with a native T-SQL function as SQL Server insists the functions has to be deterministic. But, if you could show me a native T-SQL function that does this would really make my day.

I thought perhaps this could be possible to write using a CLR function. As CLR functions are static, the sequence numbers need to be stored in the calling context of the set operation, as storing it as a static variable would result in several connections using the same sequence, resulting in not-so-sequential numbers. I do not know enough about embedded CLR to see if set operation's (select, update, delete, insert) calling context is reachable from the CLR side.

At the end of the day, the following query

select dbo.GetNextNumber() from sysobjects

must return the result

1
2
3
4
5

It is OK if another function call to reset the context is necessary like

exec dbo.ResetSequenceNumbers()

To prevent some misunderstandings and reduce the chances of wasting your time answering wrong question, please note that I am not looking for an ID generation function for a table and I am aware of some hacks (albeit using a proc not a function) that involves some temp tables with identity columns. The ROW_NUMBER() function is close but it also does not cut.

Thanks a lot for any responses

Kemal

P.S. It is amazing that SQL Server does have a built-in function for that. A function (provided that it cannot be used in joins and where clauses) is really easy to do and extremely useful, but for some reason it is not included.

Body:
As you have implemented the CLR sequence based on my article related to the calculation of Running Totals, you can achieve the same using the ROW_NUBER() function.

The ROW_NUMBER() function requires the ORDER BY in the OVER clause, however there is a nice workaround how to avoid sorting due to the ORDER BY. You cannot put an expression in the order by, but you can put SELECT aConstant there. So you can easily achieve number generating using below statement.

SELECT
    ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber,
    *
FROM aTable


问:
Offset value to the Left
I am trying to use the result of a calculation done on bar_index==189 from before it was calculated.

Is it possible to do it somehow?

If I write plot_to_the_past = ta.valuewhen(bar_index == 189, high-low, 0) plot(plot_to_the_past)

the result is cannot be used from before it was calculated. I just need to use the result of a calculation from before it was calculated.

答:
No, you cannot use any result before it is calculated. Your script will be executed on every bar and the results will then be available.

You can, however, wait till the 189th bar to form, do your calculations and plot the result somewhere in the past.

Edit:

plot() has an offset parameter which you can use to shift the plot in either direction.

```<code>//@version=5
indicator("My script", overlay=true)

var float diff = na

if (bar_index == 189)
    diff := high - low

plotshape(bar_index == 189, size=size.small)
plot(diff, offset=-10)
</code>```

Title: Offset value to the Left

Body:
No, you cannot use any result before it is calculated. Your script will be executed on every bar and the results will then be available.

You can, however, wait till the 189th bar to form, do your calculations and plot the result somewhere in the past.

Edit:

plot() has an offset parameter which you can use to shift the plot in either direction.

//@version=5
indicator("My script", overlay=true)

var float diff = na

if (bar_index == 189)
    diff := high - low

plotshape(bar_index == 189, size=size.small)
plot(diff, offset=-10)