问:
encountered an error and could not solve it : count(): Argument #1 ($value) must be of type Countable|array, string given
I encountered the error when I try to sign in my application mede by laravel 8.41.0 and PHP 8.0.3.

error

```<code>TypeError
count(): Argument #1 ($value) must be of type Countable|array, string given
</code>```

location

```<code>vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php:235
</code>```

file

```<code><?php

namespace Illuminate\Database\Eloquent\Concerns;

use Illuminate\Support\Str;

trait GuardsAttributes
{
    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [];

    /**
     * The attributes that aren't mass assignable.
     *
     * @var string[]|bool
     */
    protected $guarded = ['*'];

    /**
     * Indicates if all mass assignment is enabled.
     *
     * @var bool
     */
    protected static $unguarded = false;

    /**
     * The actual columns that exist on the database and can be guarded.
     *
     * @var array
     */
    protected static $guardableColumns = [];

    /**
     * Get the fillable attributes for the model.
     *
     * @return array
     */
    public function getFillable()
    {
        return $this->fillable;
    }

    /**
     * Set the fillable attributes for the model.
     *
     * @param  array  $fillable
     * @return $this
     */
    public function fillable(array $fillable)
    {
        $this->fillable = $fillable;

        return $this;
    }

    /**
     * Merge new fillable attributes with existing fillable attributes on the model.
     *
     * @param  array  $fillable
     * @return $this
     */
    public function mergeFillable(array $fillable)
    {
        $this->fillable = array_merge($this->fillable, $fillable);

        return $this;
    }

    /**
     * Get the guarded attributes for the model.
     *
     * @return array
     */
    public function getGuarded()
    {
        return $this->guarded === false
                    ? []
                    : $this->guarded;
    }

    /**
     * Set the guarded attributes for the model.
     *
     * @param  array  $guarded
     * @return $this
     */
    public function guard(array $guarded)
    {
        $this->guarded = $guarded;

        return $this;
    }

    /**
     * Merge new guarded attributes with existing guarded attributes on the model.
     *
     * @param  array  $guarded
     * @return $this
     */
    public function mergeGuarded(array $guarded)
    {
        $this->guarded = array_merge($this->guarded, $guarded);

        return $this;
    }

    /**
     * Disable all mass assignable restrictions.
     *
     * @param  bool  $state
     * @return void
     */
    public static function unguard($state = true)
    {
        static::$unguarded = $state;
    }

    /**
     * Enable the mass assignment restrictions.
     *
     * @return void
     */
    public static function reguard()
    {
        static::$unguarded = false;
    }

    /**
     * Determine if the current state is "unguarded".
     *
     * @return bool
     */
    public static function isUnguarded()
    {
        return static::$unguarded;
    }

    /**
     * Run the given callable while being unguarded.
     *
     * @param  callable  $callback
     * @return mixed
     */
    public static function unguarded(callable $callback)
    {
        if (static::$unguarded) {
            return $callback();
        }

        static::unguard();

        try {
            return $callback();
        } finally {
            static::reguard();
        }
    }

    /**
     * Determine if the given attribute may be mass assigned.
     *
     * @param  string  $key
     * @return bool
     */
    public function isFillable($key)
    {
        if (static::$unguarded) {
            return true;
        }

        // If the key is in the "fillable" array, we can of course assume that it's
        // a fillable attribute. Otherwise, we will check the guarded array when
        // we need to determine if the attribute is black-listed on the model.
        if (in_array($key, $this->getFillable())) {
            return true;
        }

        // If the attribute is explicitly listed in the "guarded" array then we can
        // return false immediately. This means this attribute is definitely not
        // fillable and there is no point in going any further in this method.
        if ($this->isGuarded($key)) {
            return false;
        }

        return empty($this->getFillable()) &&
            strpos($key, '.') === false &&
            ! Str::startsWith($key, '_');
    }

    /**
     * Determine if the given key is guarded.
     *
     * @param  string  $key
     * @return bool
     */
    public function isGuarded($key)
    {
        if (empty($this->getGuarded())) {
            return false;
        }

        return $this->getGuarded() == ['*'] ||
               ! empty(preg_grep('/^'.preg_quote($key).'$/i', $this->getGuarded())) ||
               ! $this->isGuardableColumn($key);
    }

    /**
     * Determine if the given column is a valid, guardable column.
     *
     * @param  string  $key
     * @return bool
     */
    protected function isGuardableColumn($key)
    {
        if (! isset(static::$guardableColumns[get_class($this)])) {
            static::$guardableColumns[get_class($this)] = $this->getConnection()
                        ->getSchemaBuilder()
                        ->getColumnListing($this->getTable());
        }

        return in_array($key, static::$guardableColumns[get_class($this)]);
    }

    /**
     * Determine if the model is totally guarded.
     *
     * @return bool
     */
    public function totallyGuarded()
    {
        return count($this->getFillable()) === 0 && $this->getGuarded() == ['*'];
    }

    /**
     * Get the fillable attributes of a given array.
     *
     * @param  array  $attributes
     * @return array
     */
    protected function fillableFromArray(array $attributes)
    {
        if (count($this->getFillable()) > 0 && ! static::$unguarded) {
            return array_intersect_key($attributes, array_flip($this->getFillable()));
        }

        return $attributes;
    }
}

</code>```

Some questioners ask same question and I saw that in latest version of PHP count issue the error. But i could not understood how to resolve the problem, so please tell me where and how to fix in my file.

thanks for responses!!

$fillable is declared with squared brackets, all files is added in above.
How can I modify it?

model.php (only fillable related)

```<code>    public function fill(array $attributes)
    {
        $totallyGuarded = $this->totallyGuarded();

        foreach ($this->fillableFromArray($attributes) as $key => $value) {
            // The developers may choose to place some attributes in the "fillable" array
            // which means only those attributes may be set through mass assignment to
            // the model, and all others will just get ignored for security reasons.
            if ($this->isFillable($key)) {
                $this->setAttribute($key, $value);
            } elseif ($totallyGuarded) {
                throw new MassAssignmentException(sprintf(
                    'Add [%s] to fillable property to allow mass assignment on [%s].',
                    $key, get_class($this)
                ));
            }
        }

        return $this;
    }
</code>```

app\model user.php

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    use HasFactory;
    protected $fillable = 'name';
}
</code>```

答: You can swap count() with isset()</p>

Body:
I encountered the error when I try to sign in my application mede by laravel 8.41.0 and PHP 8.0.3.

error

TypeError
count(): Argument #1 ($value) must be of type Countable|array, string given

location

vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php:235

file

<?php

namespace Illuminate\Database\Eloquent\Concerns;

use Illuminate\Support\Str;

trait GuardsAttributes
{
    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [];

    /**
     * The attributes that aren't mass assignable.
     *
     * @var string[]|bool
     */
    protected $guarded = ['*'];

    /**
     * Indicates if all mass assignment is enabled.
     *
     * @var bool
     */
    protected static $unguarded = false;

    /**
     * The actual columns that exist on the database and can be guarded.
     *
     * @var array
     */
    protected static $guardableColumns = [];

    /**
     * Get the fillable attributes for the model.
     *
     * @return array
     */
    public function getFillable()
    {
        return $this->fillable;
    }

    /**
     * Set the fillable attributes for the model.
     *
     * @param  array  $fillable
     * @return $this
     */
    public function fillable(array $fillable)
    {
        $this->fillable = $fillable;

        return $this;
    }

    /**
     * Merge new fillable attributes with existing fillable attributes on the model.
     *
     * @param  array  $fillable
     * @return $this
     */
    public function mergeFillable(array $fillable)
    {
        $this->fillable = array_merge($this->fillable, $fillable);

        return $this;
    }

    /**
     * Get the guarded attributes for the model.
     *
     * @return array
     */
    public function getGuarded()
    {
        return $this->guarded === false
                    ? []
                    : $this->guarded;
    }

    /**
     * Set the guarded attributes for the model.
     *
     * @param  array  $guarded
     * @return $this
     */
    public function guard(array $guarded)
    {
        $this->guarded = $guarded;

        return $this;
    }

    /**
     * Merge new guarded attributes with existing guarded attributes on the model.
     *
     * @param  array  $guarded
     * @return $this
     */
    public function mergeGuarded(array $guarded)
    {
        $this->guarded = array_merge($this->guarded, $guarded);

        return $this;
    }

    /**
     * Disable all mass assignable restrictions.
     *
     * @param  bool  $state
     * @return void
     */
    public static function unguard($state = true)
    {
        static::$unguarded = $state;
    }

    /**
     * Enable the mass assignment restrictions.
     *
     * @return void
     */
    public static function reguard()
    {
        static::$unguarded = false;
    }

    /**
     * Determine if the current state is "unguarded".
     *
     * @return bool
     */
    public static function isUnguarded()
    {
        return static::$unguarded;
    }

    /**
     * Run the given callable while being unguarded.
     *
     * @param  callable  $callback
     * @return mixed
     */
    public static function unguarded(callable $callback)
    {
        if (static::$unguarded) {
            return $callback();
        }

        static::unguard();

        try {
            return $callback();
        } finally {
            static::reguard();
        }
    }

    /**
     * Determine if the given attribute may be mass assigned.
     *
     * @param  string  $key
     * @return bool
     */
    public function isFillable($key)
    {
        if (static::$unguarded) {
            return true;
        }

        // If the key is in the "fillable" array, we can of course assume that it's
        // a fillable attribute. Otherwise, we will check the guarded array when
        // we need to determine if the attribute is black-listed on the model.
        if (in_array($key, $this->getFillable())) {
            return true;
        }

        // If the attribute is explicitly listed in the "guarded" array then we can
        // return false immediately. This means this attribute is definitely not
        // fillable and there is no point in going any further in this method.
        if ($this->isGuarded($key)) {
            return false;
        }

        return empty($this->getFillable()) &&
            strpos($key, '.') === false &&
            ! Str::startsWith($key, '_');
    }

    /**
     * Determine if the given key is guarded.
     *
     * @param  string  $key
     * @return bool
     */
    public function isGuarded($key)
    {
        if (empty($this->getGuarded())) {
            return false;
        }

        return $this->getGuarded() == ['*'] ||
               ! empty(preg_grep('/^'.preg_quote($key).'$/i', $this->getGuarded())) ||
               ! $this->isGuardableColumn($key);
    }

    /**
     * Determine if the given column is a valid, guardable column.
     *
     * @param  string  $key
     * @return bool
     */
    protected function isGuardableColumn($key)
    {
        if (! isset(static::$guardableColumns[get_class($this)])) {
            static::$guardableColumns[get_class($this)] = $this->getConnection()
                        ->getSchemaBuilder()
                        ->getColumnListing($this->getTable());
        }

        return in_array($key, static::$guardableColumns[get_class($this)]);
    }

    /**
     * Determine if the model is totally guarded.
     *
     * @return bool
     */
    public function totallyGuarded()
    {
        return count($this->getFillable()) === 0 && $this->getGuarded() == ['*'];
    }

    /**
     * Get the fillable attributes of a given array.
     *
     * @param  array  $attributes
     * @return array
     */
    protected function fillableFromArray(array $attributes)
    {
        if (count($this->getFillable()) > 0 && ! static::$unguarded) {
            return array_intersect_key($attributes, array_flip($this->getFillable()));
        }

        return $attributes;
    }
}

Some questioners ask same question and I saw that in latest version of PHP count issue the error. But i could not understood how to resolve the problem, so please tell me where and how to fix in my file.

thanks for responses!!

$fillable is declared with squared brackets, all files is added in above.
How can I modify it?

model.php (only fillable related)

    public function fill(array $attributes)
    {
        $totallyGuarded = $this->totallyGuarded();

        foreach ($this->fillableFromArray($attributes) as $key => $value) {
            // The developers may choose to place some attributes in the "fillable" array
            // which means only those attributes may be set through mass assignment to
            // the model, and all others will just get ignored for security reasons.
            if ($this->isFillable($key)) {
                $this->setAttribute($key, $value);
            } elseif ($totallyGuarded) {
                throw new MassAssignmentException(sprintf(
                    'Add [%s] to fillable property to allow mass assignment on [%s].',
                    $key, get_class($this)
                ));
            }
        }

        return $this;
    }

app\model user.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    use HasFactory;
    protected $fillable = 'name';
}

Body: You can swap count() with isset()


来源: stackexchange

问:
How to trigger full-screen mode on play for embedded YouTube video in React Native WebView?
I have a YouTube video embedded in a React Native WebView. I'm using the react-native-android-fullscreen-webview-video library for Android which works well in both portrait and landscape mode, but I need the video to default to fullscreen when the user presses play.

I've tried other libraries for this, including react-native-youtube, but each resulted in buggy playback either in portrait or landscape.

This is my code. Everything works well, I just need fullscreen play by default.

```<code><WebView source={{ uri: videoUrl }} />
</code>```

答:
I am a little late to answer this question but now you can use the react-native-youtube-iframe package to achieve this.</p>
```<code>import React from 'react';
import {Modal, StyleSheet, View} from 'react-native';
import YoutubePlayer from 'react-native-youtube-iframe';
import {hp, wp} from '../../helpers/Responsiveness';

const VideoModal = ({videoId, setModal, showVideoModal}) => {
return (
<Modal
  animationType="slide"
  transparent={true}
  visible={showVideoModal}
  onRequestClose={() => {
    setModal();
  }}>
  <View style={styles.centeredView}>
    <View style={styles.modalView}>
      <YoutubePlayer
        height={hp(100)}
        width={wp(100)}
        play={false}
        videoId={videoId}
        webViewProps={{
          injectedJavaScript: `
        var element = document.getElementsByClassName('container')[0];
        element.style.position = 'unset';
        element.style.paddingBottom = 'unset';
        true;
      `,
        }}
      />
    </View>
  </View>
</Modal>
 );
 };

const styles = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.3)',
},
modalView: {
backgroundColor: 'black',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: {
  width: 0,
  height: 2,
  },
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
height: '100%',
width: '100%',
justifyContent: 'center',
  },
  modalText: {
  marginBottom: 15,
  textAlign: 'center',
  },
  });

export default VideoModal;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a YouTube video embedded in a React Native WebView. I'm using the react-native-android-fullscreen-webview-video library for Android which works well in both portrait and landscape mode, but I need the video to default to fullscreen when the user presses play.

I've tried other libraries for this, including react-native-youtube, but each resulted in buggy playback either in portrait or landscape.

This is my code. Everything works well, I just need fullscreen play by default.

<WebView source={{ uri: videoUrl }} />

Body:
I am a little late to answer this question but now you can use the react-native-youtube-iframe package to achieve this.

import React from 'react';
import {Modal, StyleSheet, View} from 'react-native';
import YoutubePlayer from 'react-native-youtube-iframe';
import {hp, wp} from '../../helpers/Responsiveness';

const VideoModal = ({videoId, setModal, showVideoModal}) => {
return (
<Modal
  animationType="slide"
  transparent={true}
  visible={showVideoModal}
  onRequestClose={() => {
    setModal();
  }}>
  <View style={styles.centeredView}>
    <View style={styles.modalView}>
      <YoutubePlayer
        height={hp(100)}
        width={wp(100)}
        play={false}
        videoId={videoId}
        webViewProps={{
          injectedJavaScript: `
        var element = document.getElementsByClassName('container')[0];
        element.style.position = 'unset';
        element.style.paddingBottom = 'unset';
        true;
      `,
        }}
      />
    </View>
  </View>
</Modal>
 );
 };

const styles = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.3)',
},
modalView: {
backgroundColor: 'black',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: {
  width: 0,
  height: 2,
  },
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
height: '100%',
width: '100%',
justifyContent: 'center',
  },
  modalText: {
  marginBottom: 15,
  textAlign: 'center',
  },
  });

export default VideoModal;


问:
Updating a Backbone.js collection without wiping old models
I have an application which consists of a Backbone.js collection and real-time connection to the server.

Every time any client adds / removes / updates a model in the collection, the updated collection is broadcasted to all other clients (not the delta; the whole collection).

When handling this update event from the other clients, the only way I've found of updating the collection is a reset().  Unfortunately, this wipes the old models and creates new ones, along with all the view-related side-effects.

Is there a Backbone-sanctioned way of updating a collection that maintains and updates the original models (comparing by id), creating / deleting them only if necessary?

UPDATE Backbone has added the Collection.set method, which is capable of updating existing models.

答: You can extend collection's add method and check there for model existance

ContentLicense: CC BY-SA 3.0


问:
Refer multiple Resource Dictionaries in the UWP project
My UWP app has a resource dictionary used for localization named "Resources.resx" and now I want to add another "ResourcesXaml.resx". I want to know how to access both files like merged.

The code is below. I want to use the same Get(string key) method and access any resource in both files. Appreciate it if anyone can point out the change I need to make. Cheers!

```<code>static ResourceHandler()
    {
        const string selectedLanguage = "en";
        Context = ResourceContext.GetForCurrentView();

        var lang = new List<string> { selectedLanguage };
        Context.Languages = lang;
        ResourceStringMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
    }

    public static string Get(string key)
    {
        return ResourceStringMap.GetValue(key, Context).ValueAsString;
    }
</code>```

答:
You could create two ResourceMaps and look up the key in the second one if the lookup in the first one fails, e.g.:

```<code>public static class ResourceHandler
{
    private const string SelectedLanguage = "en";
    private static readonly ResourceContext s_resourceContext =
        new ResourceContext() { Languages = new string[1] { SelectedLanguage } };
    private static readonly ResourceMap s_resourcesMap =
        ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
    private static readonly ResourceMap s_resourcesXamlMap =
        ResourceManager.Current.MainResourceMap.GetSubtree("ResourcesXaml");

    public static string Get(string key)
    {
        string s = s_resourcesMap.GetValue(key, s_resourceContext).ValueAsString;
        if (!string.IsNullOrEmpty(s))
            return s;

        return s_resourcesXamlMap.GetValue(key, s_resourceContext).ValueAsString;
    }
}
</code>```

Body:
My UWP app has a resource dictionary used for localization named "Resources.resx" and now I want to add another "ResourcesXaml.resx". I want to know how to access both files like merged.

The code is below. I want to use the same Get(string key) method and access any resource in both files. Appreciate it if anyone can point out the change I need to make. Cheers!

static ResourceHandler()
    {
        const string selectedLanguage = "en";
        Context = ResourceContext.GetForCurrentView();

        var lang = new List<string> { selectedLanguage };
        Context.Languages = lang;
        ResourceStringMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
    }

    public static string Get(string key)
    {
        return ResourceStringMap.GetValue(key, Context).ValueAsString;
    }

Body:
You could create two ResourceMaps and look up the key in the second one if the lookup in the first one fails, e.g.:

public static class ResourceHandler
{
    private const string SelectedLanguage = "en";
    private static readonly ResourceContext s_resourceContext =
        new ResourceContext() { Languages = new string[1] { SelectedLanguage } };
    private static readonly ResourceMap s_resourcesMap =
        ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
    private static readonly ResourceMap s_resourcesXamlMap =
        ResourceManager.Current.MainResourceMap.GetSubtree("ResourcesXaml");

    public static string Get(string key)
    {
        string s = s_resourcesMap.GetValue(key, s_resourceContext).ValueAsString;
        if (!string.IsNullOrEmpty(s))
            return s;

        return s_resourcesXamlMap.GetValue(key, s_resourceContext).ValueAsString;
    }
}


问:
I have to find the file with maximum speed size in azure data factory
I created an array variable and tried to pass that to max math function in ADF but i'm getting error in it. So how to using max function there?</p>

答:
Array is one of the datatypes supported in ADF with both parameters and variables, so if you have a valid array then max will work either.  A simple example:

create a valid parameter of the Array datatype:

Create a variable and add a Set Variable activity.  Use this expression as the Value argument:

```<code>@string(max(pipeline().parameters.pInputArray))
</code>```

NB I'm using the max function directly on the array and then string as only the String, Array and Boolean datatypes are supported for variables (at this time).

Body:
Array is one of the datatypes supported in ADF with both parameters and variables, so if you have a valid array then max will work either.  A simple example:

create a valid parameter of the Array datatype:

Create a variable and add a Set Variable activity.  Use this expression as the Value argument:

@string(max(pipeline().parameters.pInputArray))

NB I'm using the max function directly on the array and then string as only the String, Array and Boolean datatypes are supported for variables (at this time).


问:
Tasks - Generate Scripts in Azure Synapse Serverless SQL
I am working with an Azure Synapse Serverless SQL instance, connected via the most recent version of SSMS. I have several external tables defined over parquet files in an Azure Data Lake (Gen2).

My question is how do I use the typical "Tasks-Generate Scripts" to generate the external table definitions similar to what I am used to in SQL Server? Or do something similar (batch export of external table definitions)...at this point, it appears that I need to go external table by external table (right-click -> script table as -> drop and create to -> File, etc.).

Any advice is appreciated, thanks!

答:
Generating Synapse Serverless scripts is available from SSMS by default. However, its not as straightforward as usual. Perform the following to generate scripts:

From the toolbar:

View > Object Explorer Details > Databases > {select your DB} > Views

Here you can select one or multiple views, right-click, then select Script View As > Create To > New Window

It will script all of the views that you selected. I'm not sure why they don't just provided the standard "Generate Scripts" option, but this is a workaround.


问:
Multiple Implementations of IHostedService
I'm trying to create background services using IHostedService. Everything works fine if I only have ONE background service. When I try to create more than one implementation of IHostedService only the one that was registered first actually runs.

```<code>services.AddSingleton<IHostedService, HostedServiceOne>();
services.AddSingleton<IHostedService, HostedServiceTwo>();
</code>```

In the above sample StartAsync on HostedServiceOne gets called but StartAsync on HostedServiceTwo never gets called. If I swap the order of registering the two implementations of IHostedService (put IHostedServiceTwo before IHostedServiceOne) then StartAsync on HostedServiceTwo gets called but never for HostedServiceOne.

EDIT:

I was directed to the following:

How to register multiple implementations of the same interface in Asp.Net Core?

However this isn't for IHostedService. To use the suggested approach I would have to make a call to serviceProvider.GetServices<IService>(); but it seems that IHostedService.StartAsync seems to be called internally. I'm not even sure where I would call that to trigger IHostedService.StartAsync.

答: Switch IHostedService to BackgroundService. Move any blocking code in StartAsync to ExecuteAsync and at the end of StartAsync return base.StartAsync(cancellationToken).</p>

Body:
I'm trying to create background services using IHostedService. Everything works fine if I only have ONE background service. When I try to create more than one implementation of IHostedService only the one that was registered first actually runs.

services.AddSingleton<IHostedService, HostedServiceOne>();
services.AddSingleton<IHostedService, HostedServiceTwo>();

In the above sample StartAsync on HostedServiceOne gets called but StartAsync on HostedServiceTwo never gets called. If I swap the order of registering the two implementations of IHostedService (put IHostedServiceTwo before IHostedServiceOne) then StartAsync on HostedServiceTwo gets called but never for HostedServiceOne.

EDIT:

I was directed to the following:

How to register multiple implementations of the same interface in Asp.Net Core?

However this isn't for IHostedService. To use the suggested approach I would have to make a call to serviceProvider.GetServices<IService>(); but it seems that IHostedService.StartAsync seems to be called internally. I'm not even sure where I would call that to trigger IHostedService.StartAsync.


问:
Convert this SQL Query to LINQ Query
I need to convert this SQL Query to LINQ Query, also I need to expose the SQL Select properties:

```<code>SELECT Problem.ProblemID, ProblemFactory.ObjectiveID, Objective.Name, ProblemFactory.Time, ProblemType.ProblemTypeName, ProblemFactory.OperationID,
                     ProblemFactory.Range1ID, ProblemFactory.Range2ID, ProblemFactory.Range3ID, ProblemFactory.Range4ID,
                     ProblemFactory.MissingNumber
FROM Problem INNER JOIN ProblemFactory ON Problem.ProblemFactoryID = ProblemFactory.ProblemFactoryID
             INNER JOIN ProblemType ON ProblemFactory.ProblemTypeID = ProblemType.ProblemTypeID
             INNER JOIN Objective ON Objective.ObjectiveID = ProblemFactory.ObjectiveID
</code>```

UPDATE 1:

This is what I have:

```<code>        var query = from problem in dc.Problem2s
                    from factory
                    in dc.ProblemFactories
                         .Where(v => v.ProblemFactoryID == problem.ProblemFactoryID)
                         .DefaultIfEmpty()
                    from ...
</code>```

And I'm using this example: What is the syntax for an inner join in LINQ to SQL?

答:
Something like this?

```<code>var query =
    from p in ctx.Problem
    join pf in ctx.ProblemFactory on p.ProblemFactoryID equals pf.ProblemFactoryID
    join pt in ctx.ProblemType on pf.ProblemTypeID equals pt.ProblemTypeID
    join o in ctx.Objective on pf.ObjectiveID equals o.ObjectiveID
    select new
    {
        p.ProblemID,
        pf.ObjectiveID,
        o.Name,
        pf.Time,
        pt.ProblemTypeName,
        pf.OperationID,
        pf.Range1ID,
        pf.Range2ID,
        pf.Range3ID,
        pf.Range4ID,
        pf.MissingNumber,
    };
</code>```

But what do you mean by the "SQL Select properties"?

Title: Convert this SQL Query to LINQ Query

Body:
I need to convert this SQL Query to LINQ Query, also I need to expose the SQL Select properties:

SELECT Problem.ProblemID, ProblemFactory.ObjectiveID, Objective.Name, ProblemFactory.Time, ProblemType.ProblemTypeName, ProblemFactory.OperationID,
                     ProblemFactory.Range1ID, ProblemFactory.Range2ID, ProblemFactory.Range3ID, ProblemFactory.Range4ID,
                     ProblemFactory.MissingNumber
FROM Problem INNER JOIN ProblemFactory ON Problem.ProblemFactoryID = ProblemFactory.ProblemFactoryID
             INNER JOIN ProblemType ON ProblemFactory.ProblemTypeID = ProblemType.ProblemTypeID
             INNER JOIN Objective ON Objective.ObjectiveID = ProblemFactory.ObjectiveID

UPDATE 1:

This is what I have:

        var query = from problem in dc.Problem2s
                    from factory
                    in dc.ProblemFactories
                         .Where(v => v.ProblemFactoryID == problem.ProblemFactoryID)
                         .DefaultIfEmpty()
                    from ...

And I'm using this example: What is the syntax for an inner join in LINQ to SQL?

Body:
Something like this?

var query =
    from p in ctx.Problem
    join pf in ctx.ProblemFactory on p.ProblemFactoryID equals pf.ProblemFactoryID
    join pt in ctx.ProblemType on pf.ProblemTypeID equals pt.ProblemTypeID
    join o in ctx.Objective on pf.ObjectiveID equals o.ObjectiveID
    select new
    {
        p.ProblemID,
        pf.ObjectiveID,
        o.Name,
        pf.Time,
        pt.ProblemTypeName,
        pf.OperationID,
        pf.Range1ID,
        pf.Range2ID,
        pf.Range3ID,
        pf.Range4ID,
        pf.MissingNumber,
    };

But what do you mean by the "SQL Select properties"?


问:
How can I make the Material UI header containing Grid Responsive to mobile screen with breakpoints
I have made the header component with grid having links for routing, I just want this grid be responsive on mobile screen by applying the material UI breakpoints. Means Instead of showing all the grid items by wrapping them under, just show the 2 items on mobile screen. thanks

**This is my code of the header.js file: **

```<code>import React from 'react'
import './Header.css'

import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import { AppBar } from '@mui/material';
import SportsEsportsIcon from '@mui/icons-material/SportsEsports';
import StorefrontIcon from '@mui/icons-material/Storefront';
import GamepadIcon from '@mui/icons-material/Gamepad';
import ChildCareIcon from '@mui/icons-material/ChildCare';
import AcUnitIcon from '@mui/icons-material/AcUnit';
import { useNavigate } from 'react-router-dom';
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme)=>({
root:{
    [theme.breakpoints.down('sm')]: {

      }
}
}))

export const Header = () => {
    const classes =useStyles()
    const navigate = useNavigate()
    return (
        // <div className='header'>
        <div>
            {/* <div className='plomxName'>PlomX</div> */}
            {/* <Box sx={{ flexGrow: 1 }}> */}
            <AppBar style={{ background: 'black', height: '109px' }}>

                    <Grid container justifyContent="center" spacing={2} className={classes.root}>
                        <div className='plomxName'><Button onClick={() => navigate('/')} sx={{ color: "white" }}>PlomX</Button></div>
                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/games')} sx={{ color: "white" }}><SportsEsportsIcon sx={{ color: 'white' }} />Games</Button></Grid>
                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/nftmarketplace')} sx={{ color: "white" }}><StorefrontIcon sx={{ color: 'white' }} />NFT Marketplace</Button></Grid>
                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/metaverse')} sx={{ color: "white" }}><AcUnitIcon sx={{ color: 'white' }} />MetaVerse</Button></Grid>
                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/getyourgameon')} sx={{ color: "white" }}><GamepadIcon sx={{ color: 'white' }} />Get your game on Blockchain</Button></Grid>
                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/careers')} sx={{ color: "white" }}><ChildCareIcon sx={{ color: 'white' }} />Careers</Button></Grid>
                    </Grid>

            </AppBar>
            {/* </Box> */}
        </div>
    )
}
</code>```

The Actual design , I want to make is like this one.

答: please check attached forked demo. as discussed one box is always visible while other is visible based on display breakpoint

Body:
I have made the header component with grid having links for routing, I just want this grid be responsive on mobile screen by applying the material UI breakpoints. Means Instead of showing all the grid items by wrapping them under, just show the 2 items on mobile screen. thanks

**This is my code of the header.js file: **

import React from 'react'
import './Header.css'

import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import { AppBar } from '@mui/material';
import SportsEsportsIcon from '@mui/icons-material/SportsEsports';
import StorefrontIcon from '@mui/icons-material/Storefront';
import GamepadIcon from '@mui/icons-material/Gamepad';
import ChildCareIcon from '@mui/icons-material/ChildCare';
import AcUnitIcon from '@mui/icons-material/AcUnit';
import { useNavigate } from 'react-router-dom';
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme)=>({
root:{
    [theme.breakpoints.down('sm')]: {

      }
}
}))

export const Header = () => {
    const classes =useStyles()
    const navigate = useNavigate()
    return (
        //

            {/*
PlomX
 */}
            {/* <Box sx={{ flexGrow: 1 }}> */}
            <AppBar style={{ background: 'black', height: '109px' }}>

                    <Grid container justifyContent="center" spacing={2} className={classes.root}>

<Button onClick={() => navigate('/')} sx={{ color: "white" }}>PlomX</Button>

                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/games')} sx={{ color: "white" }}><SportsEsportsIcon sx={{ color: 'white' }} />Games</Button></Grid>
                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/nftmarketplace')} sx={{ color: "white" }}><StorefrontIcon sx={{ color: 'white' }} />NFT Marketplace</Button></Grid>
                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/metaverse')} sx={{ color: "white" }}><AcUnitIcon sx={{ color: 'white' }} />MetaVerse</Button></Grid>
                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/getyourgameon')} sx={{ color: "white" }}><GamepadIcon sx={{ color: 'white' }} />Get your game on Blockchain</Button></Grid>
                        <Grid item sx={{ marginTop: 3 }}><Button onClick={() => navigate('/careers')} sx={{ color: "white" }}><ChildCareIcon sx={{ color: 'white' }} />Careers</Button></Grid>
                    </Grid>

            </AppBar>
            {/* </Box> */}

    )
}

The Actual design , I want to make is like this one.


问:
(node:23468) UnhandledPromiseRejectionWarning: MongoServerError: FieldPath field names may not start with '$'. Consider using $getField or $setField
I am facing an issue using node.js and mongoose, when I am trying to run the following query I get this error. I tried almost every possible solution but nothing helped out.
my mongo DB version is 5.0.6, node.js is v14.17.1 and the mongoose version is ^6.0.10

```<code>const getConversationsToJoin = async(userId) => {
    const conversations = await Conversation.find({ status: 'active' }, {
        $or: [{
                member_a_id: userId
            },
            {
                member_b_id: userId
            }
        ]
    });
    return conversations
}
</code>```

(node:23468) UnhandledPromiseRejectionWarning: MongoServerError: FieldPath field names may not start with '$'. Consider using $getField or
$setField.
at MessageStream.messageHandler (D:\laragon\www\Tuxedo_API\node_modules\mongodb\lib\cmap\connection.js:467:30)
at MessageStream.emit (events.js:375:28)
at processIncomingData (D:\laragon\www\Tuxedo_API\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (D:\laragon\www\Tuxedo_API\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at Socket.ondata (internal/streams/readable.js:726:22)
at Socket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
(Use node --trace-warnings ... to show where the warning was created)
(node:23468) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:23468) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Please help

答:
Your issue is nothing related to the version of technologies used, it's an incorrect use of find query. Find query will only take one argument, that is supposed to contain all your filters.

Moreover the syntax for $or is incorrect too. It should not be wrapped inside curly braces.

Here is what you should be doing:

```<code>const getConversationsToJoin = async (userId) => {
  const conversations = await Conversation.find({
    status: "active",
    $or: [
      {
        member_a_id: userId,
      },
      {
        member_b_id: userId,
      },
    ],
  });
  return conversations;
};
</code>```

Body:
I am facing an issue using node.js and mongoose, when I am trying to run the following query I get this error. I tried almost every possible solution but nothing helped out.
my mongo DB version is 5.0.6, node.js is v14.17.1 and the mongoose version is ^6.0.10

const getConversationsToJoin = async(userId) => {
    const conversations = await Conversation.find({ status: 'active' }, {
        $or: [{
                member_a_id: userId
            },
            {
                member_b_id: userId
            }
        ]
    });
    return conversations
}

(node:23468) UnhandledPromiseRejectionWarning: MongoServerError: FieldPath field names may not start with '$'. Consider using $getField or
$setField.
at MessageStream.messageHandler (D:\laragon\www\Tuxedo_API\node_modules\mongodb\lib\cmap\connection.js:467:30)
at MessageStream.emit (events.js:375:28)
at processIncomingData (D:\laragon\www\Tuxedo_API\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (D:\laragon\www\Tuxedo_API\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at Socket.ondata (internal/streams/readable.js:726:22)
at Socket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
(Use node --trace-warnings ... to show where the warning was created)
(node:23468) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:23468) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Please help

Body:
Your issue is nothing related to the version of technologies used, it's an incorrect use of find query. Find query will only take one argument, that is supposed to contain all your filters.

Moreover the syntax for $or is incorrect too. It should not be wrapped inside curly braces.

Here is what you should be doing:

const getConversationsToJoin = async (userId) => {
  const conversations = await Conversation.find({
    status: "active",
    $or: [
      {
        member_a_id: userId,
      },
      {
        member_b_id: userId,
      },
    ],
  });
  return conversations;
};


问:
multiple CORS values being rejected in Go gin api
In my Go API, I'm using gin, and I have one value set in my Access-Control-Allow-Origin header. If I have more than one, my react UI throws an error to the effect of The Access-Control-Allow-Origin header contains multiple values 'http://value1, http://value2', but only one is allowed.... I need to set multiple values. How do I do this?

The API is a reverse proxy, and here's the relevant code:

```<code>func proxy(c *gin.Context) {
  var remote = "myUrl"
  proxy := httputil.NewSingleHostReverseProxy(remote)
  proxy.Director = func(req *http.Request) {
        req.Header.Set("Authorization", "My Auth Values")
        req.Host = remote.Host
        req.URL.Scheme = remote.Scheme
        req.URL.Host = remote.Host
    }
    proxy.ModifyResponse = addCustomHeader
    proxy.ServeHTTP(c.Writer, c.Request)
}

func addCustomHeader(r *http.Response) error {
    r.Header["Access-Control-Allow-Origin"] = []string{"value1"}
    return nil
}
</code>```

答:
A CORS header can only contain a single value. If you want to implement your own CORS middleware, you need to work around that fact.

A simple CORS middleware will add the Access-Control-Allow-Origin header with the value of the specific address of the incoming request, usually taken from the Referer or Origin header. Typically, you match this against a list or map first, to see if it's in your allow list. If so, then the address of the request is added as allowed origin (as a single value).

A simple example could look like this

allowList := map[string]bool{
    "https://www.google.com": true,
    "https://www.yahoo.com":  true,
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    if origin := r.Header.Get("Origin"); allowList[origin] {
        w.Header().Set("Access-Control-Allow-Origin", origin)
    }
})
```
<p>Since you are using the reverse proxy, you can access the request from the response.</p>
<pre class="lang-golang prettyprint-override"><code>mod := func(allowList map[string]bool) func(r *http.Response) error {
    return func(r *http.Response) error {
        if origin := r.Request.Header.Get("Origin"); allowList[origin] {
            r.Header.Set("Access-Control-Allow-Origin", origin)
        }
        return nil
    }
}

proxy := &httputil.ReverseProxy{
    Director: func(r *http.Request) {
        r.URL.Scheme = "https"
        r.URL.Host = "go.dev"
        r.Host = r.URL.Host
    },
    ModifyResponse: mod(allowList),
}
</code>```

Body:
In my Go API, I'm using gin, and I have one value set in my Access-Control-Allow-Origin header. If I have more than one, my react UI throws an error to the effect of The Access-Control-Allow-Origin header contains multiple values 'http://value1, http://value2', but only one is allowed.... I need to set multiple values. How do I do this?

The API is a reverse proxy, and here's the relevant code:

func proxy(c *gin.Context) {
  var remote = "myUrl"
  proxy := httputil.NewSingleHostReverseProxy(remote)
  proxy.Director = func(req *http.Request) {
        req.Header.Set("Authorization", "My Auth Values")
        req.Host = remote.Host
        req.URL.Scheme = remote.Scheme
        req.URL.Host = remote.Host
    }
    proxy.ModifyResponse = addCustomHeader
    proxy.ServeHTTP(c.Writer, c.Request)
}

func addCustomHeader(r *http.Response) error {
    r.Header["Access-Control-Allow-Origin"] = []string{"value1"}
    return nil
}

Body:
A CORS header can only contain a single value. If you want to implement your own CORS middleware, you need to work around that fact.

A simple CORS middleware will add the Access-Control-Allow-Origin header with the value of the specific address of the incoming request, usually taken from the Referer or Origin header. Typically, you match this against a list or map first, to see if it's in your allow list. If so, then the address of the request is added as allowed origin (as a single value).

A simple example could look like this

allowList := map[string]bool{
    "https://www.google.com": true,
    "https://www.yahoo.com":  true,
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    if origin := r.Header.Get("Origin"); allowList[origin] {
        w.Header().Set("Access-Control-Allow-Origin", origin)
    }
})

Since you are using the reverse proxy, you can access the request from the response.

mod := func(allowList map[string]bool) func(r *http.Response) error {
    return func(r *http.Response) error {
        if origin := r.Request.Header.Get("Origin"); allowList[origin] {
            r.Header.Set("Access-Control-Allow-Origin", origin)
        }
        return nil
    }
}

proxy := &httputil.ReverseProxy{
    Director: func(r *http.Request) {
        r.URL.Scheme = "https"
        r.URL.Host = "go.dev"
        r.Host = r.URL.Host
    },
    ModifyResponse: mod(allowList),
}


问:
Make responsive image
/How to set width and height of image to be 150px and to be responsive/

/HTML/

```<code><div class="tabs__tab-image-container">
    <img src="https://pbs.twimg.com/profile_images/1208234904405757953/mT0cFOVQ_400x400.jpg" class="tabs__tab-content-img">
</div>
</code>```

/CSS/

```<code>.tabs__tab-image-container {
        max-width: 150px;
        min-height: 150px;
        height: 100%;
        width: 100%;
    }
    tabs__tab-content-img {
        border-radius: 50%;
        max-width: 150px;
        height: auto;
        display: block;
        object-fit: cover;
    }
</code>```

答:
You need to be clearer in your question.  You want an image to ALWAYS be 150px square but the DIV to be responsive? Or do you want the IMAGE to be responsive within the DIV?  As you're only showing a DIV with a single image in it, it's hard to tell what the goal is.

A responsive page is one that changes based on the viewport size; locking the image down to a fixed size kinda defeats the purpose in that case.   Your CSS also isn't using the image class as it's incorrectly formatted.

The following fixes the image class as you've specified it, but all this does is round the image corners; the content won't be responsive:

CSS:

```<code>.tabs__tab-image-container {
    max-width: 150px;
    min-height: 150px;
    height: 100%;
    width: 100%;
 }

 .tabs__tab-content img {
    border-radius: 50%;
    max-width: 150px;
    height: auto;
    display: block;
    object-fit: cover;
}
</code>```

HTML:

```<code><div class="tabs__tab-image-container">
  <div class="tabs__tab-content"><img src="https://pbs.twimg.com/profile_images/1208234904405757953/mT0cFOVQ_400x400.jpg">
  </div>
</div>
</code>```

To make the page responsive, you can add viewports in CSS for different page sizes, or if it's just the image displaying (with a line of text in the div for example) use the following:

CSS:

```<code>.tabs__tab-image-container {
    text-align:center;
    font-family: "Comic Sans MS", cursive;
    font-size: 10.0vw;
    font-weight:700;
  }
.tabs__tab-content img {
    border-radius: 50%;
    width: 100%;
 }
</code>```

HTML:

```<code><div class="tabs__tab-image-container">
  <div class="tabs__tab-content"><img src="https://pbs.twimg.com/profile_images/1208234904405757953/mT0cFOVQ_400x400.jpg">
Text Here
  </div>
</div>
</code>```

If you only need the image, you don't even need the tabs__tab-image-container class, just use the tab content class targeting the image.

Title: Make responsive image

Body:
/How to set width and height of image to be 150px and to be responsive/

/HTML/

/CSS/

.tabs__tab-image-container {
        max-width: 150px;
        min-height: 150px;
        height: 100%;
        width: 100%;
    }
    tabs__tab-content-img {
        border-radius: 50%;
        max-width: 150px;
        height: auto;
        display: block;
        object-fit: cover;
    }

Body:
You need to be clearer in your question.  You want an image to ALWAYS be 150px square but the DIV to be responsive? Or do you want the IMAGE to be responsive within the DIV?  As you're only showing a DIV with a single image in it, it's hard to tell what the goal is.

A responsive page is one that changes based on the viewport size; locking the image down to a fixed size kinda defeats the purpose in that case.   Your CSS also isn't using the image class as it's incorrectly formatted.

The following fixes the image class as you've specified it, but all this does is round the image corners; the content won't be responsive:

CSS:

.tabs__tab-image-container {
    max-width: 150px;
    min-height: 150px;
    height: 100%;
    width: 100%;
 }

 .tabs__tab-content img {
    border-radius: 50%;
    max-width: 150px;
    height: auto;
    display: block;
    object-fit: cover;
}

HTML:

<div class="tabs__tab-image-container">
  <div class="tabs__tab-content"><img src="https://pbs.twimg.com/profile_images/1208234904405757953/mT0cFOVQ_400x400.jpg">
  </div>
</div>

To make the page responsive, you can add viewports in CSS for different page sizes, or if it's just the image displaying (with a line of text in the div for example) use the following:

CSS:

.tabs__tab-image-container {
    text-align:center;
    font-family: "Comic Sans MS", cursive;
    font-size: 10.0vw;
    font-weight:700;
  }
.tabs__tab-content img {
    border-radius: 50%;
    width: 100%;
 }

HTML:

<div class="tabs__tab-image-container">
  <div class="tabs__tab-content"><img src="https://pbs.twimg.com/profile_images/1208234904405757953/mT0cFOVQ_400x400.jpg">
Text Here
  </div>
</div>

If you only need the image, you don't even need the tabs__tab-image-container class, just use the tab content class targeting the image.


问:
How to create a diagonal matrix in R?
I have an excel file which contains 250 sheets( 1st sheet contains 250 rows and 11 columns,2nd sheet contains 249 rows and 11 columns, 3rd sheet contains 248 rows and 11 columns and so on). I need only the values of 11th column from all sheets for creating diagonal matrix. I think , First I have to import 11th column values from excel file to R . Based on these values I have to create a diagonal matrix . Please help me</p>

答:
From what you are describing, you really want a triangular matrix, and I will show how to create an upper triangular matrix:

Step 1: create a matrix to receive results:

```<code>mat <- matrix(NA, ncol=250, nrow=250)
</code>```

Step 2: get a function to read n-th sheet's  the n rows in the 11-th column

```<code>require(gdata) # to get read.xls or use an equivalent that works with your unstated OS
               # you do need a Perl interpreter and a proper .pm file
</code>```

Step 3: loop over the 250 sheets and put in the matrix rows

```<code>for(idx in 1:250 ) {
   intemp <- read.xls(xlsfilename, sheet = idx )
   mat[ idx, (251-idx):250] <- intemp[1:idx, 11]
         }
</code>```

There are lots of way this could fail. The obvious one is indexing past the end of the range of data that comes in from the sheets

Title: How to create a diagonal matrix in R?

Body:
From what you are describing, you really want a triangular matrix, and I will show how to create an upper triangular matrix:

Step 1: create a matrix to receive results:

mat <- matrix(NA, ncol=250, nrow=250)

Step 2: get a function to read n-th sheet's  the n rows in the 11-th column

require(gdata) # to get read.xls or use an equivalent that works with your unstated OS
               # you do need a Perl interpreter and a proper .pm file

Step 3: loop over the 250 sheets and put in the matrix rows

for(idx in 1:250 ) {
   intemp <- read.xls(xlsfilename, sheet = idx )
   mat[ idx, (251-idx):250] <- intemp[1:idx, 11]
         }

There are lots of way this could fail. The obvious one is indexing past the end of the range of data that comes in from the sheets


问:
Trimming text files from command line (Windows)
I have a text file which contains several hundred lines e.g.

```<code>test.bin:8948549854958
</code>```

They are all styled like the above file (xxxxxxx.xxx:xxxxxxxxxxxxxx)

Is there any way I could trim all lines e.g. take :xxxxxxxxxxxxxxx of the line, so just to leave xxxxxxx.xxx ?

答:
same as margnus1 answer but no batch file
from the command line:

FOR /F "tokens=1 delims=:" %G IN (inlist.txt) DO @echo %G >> outlist.txt

which answers the question "From Command Line"

Body:
I have a text file which contains several hundred lines e.g.

test.bin:8948549854958

They are all styled like the above file (xxxxxxx.xxx:xxxxxxxxxxxxxx)

Is there any way I could trim all lines e.g. take :xxxxxxxxxxxxxxx of the line, so just to leave xxxxxxx.xxx ?


问:
Query update last record only and value from other table
I have two tables

oc_stock_hpp

```<code>id product_id stock
2  1234       0
3  5678       0
4  1234       0
6  1234       0
9  5678       0
</code>```

oc_product

```<code>id product_id quantity
1  1234       7
23 5678       9
</code>```

My purpose is to update value in the stock field table oc_stock_hpp where id=6 become 7 and id=9 become 9 as in oc_product table

I have tried

```<code>UPDATE oc_stock_hpp t1
    INNER JOIN oc_product t2
         ON t1.product_id = t2.product_id
SET t1.stock = t2.quantity
WHERE t1.id = (SELECT MAX(id) FROM oc_stock_hpp GROUP BY product_id)
</code>```

and got error Subquery returns more than 1 row

答:
```<code>UPDATE oc_stock_hpp t1                        -- this table copy will be updated
JOIN ( SELECT MAX(id) id, product_id          -- this subquery allows to define
       FROM oc_stock_hpp t2                   -- the most last row ( and this row
       GROUP BY 2 ) t3 USING (id, product_id) -- will be updated only )
JOIN oc_product t4 USING (product_id)         -- this table copy provides new value
SET t1.stock = t4.quantity;                   -- and perform the update
</code>```

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=54b5b671ada99ec44ae24a5353460320

Body:
I have two tables

oc_stock_hpp

id product_id stock
2  1234       0
3  5678       0
4  1234       0
6  1234       0
9  5678       0

oc_product

id product_id quantity
1  1234       7
23 5678       9

My purpose is to update value in the stock field table oc_stock_hpp where id=6 become 7 and id=9 become 9 as in oc_product table

I have tried

UPDATE oc_stock_hpp t1
    INNER JOIN oc_product t2
         ON t1.product_id = t2.product_id
SET t1.stock = t2.quantity
WHERE t1.id = (SELECT MAX(id) FROM oc_stock_hpp GROUP BY product_id)

and got error Subquery returns more than 1 row

Body:
UPDATE oc_stock_hpp t1                        -- this table copy will be updated
JOIN ( SELECT MAX(id) id, product_id          -- this subquery allows to define
       FROM oc_stock_hpp t2                   -- the most last row ( and this row
       GROUP BY 2 ) t3 USING (id, product_id) -- will be updated only )
JOIN oc_product t4 USING (product_id)         -- this table copy provides new value
SET t1.stock = t4.quantity;                   -- and perform the update

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=54b5b671ada99ec44ae24a5353460320


问:
MySqlConversionException when accessing DateTime field from DataReader
I have a C# application over MySql, using MySQL Connector; I'm trying to make a
DataReader request, the query executes fine, however, when trying to access a DateTime field, i'm getting MySqlConversionException {"Unable to convert MySQL date/time value to System.DateTime"}

this is the prototype

```<code>if (dr != null && !dr.Read()) return;

sesion.Id = Convert.ToInt32(dr["id"]);
sesion.Usuario = Convert.ToInt32(dr["usuario"]);
sesion.Estado = Convert.ToByte(dr["estado"]);
// doesn't work
sesion.FchCreacion = Convert.ToDateTime(dr["fch_creacion"]);
</code>```

Any suggestions?
Thanks in advance

答: There are a few potential gotchas when converting between MySQL dates/times and .NET DateTimes, but there's a useful section in the MySQL documentation with advice on how to handle the issues.</p>

OwnerDisplayName: Jhonny D. Cano -Leftware-

ContentLicense: CC BY-SA 2.5

Body:
I have a C# application over MySql, using MySQL Connector; I'm trying to make a
DataReader request, the query executes fine, however, when trying to access a DateTime field, i'm getting MySqlConversionException {"Unable to convert MySQL date/time value to System.DateTime"}

this is the prototype

if (dr != null && !dr.Read()) return;

sesion.Id = Convert.ToInt32(dr["id"]);
sesion.Usuario = Convert.ToInt32(dr["usuario"]);
sesion.Estado = Convert.ToByte(dr["estado"]);
// doesn't work
sesion.FchCreacion = Convert.ToDateTime(dr["fch_creacion"]);

Any suggestions?
Thanks in advance

OwnerDisplayName: Luke


问:
Split text in hash value into new hash using separator in Ruby
I found another question similar to the one I have, but I was not able to replicate it (probably because it doesn't deal with hashes neither have symbols).

So, given the following array of hashes:

```<code>[{:id=>1, :name=>"AA;AB;AC", :title=>"A row"},
 {:id=>2, :name=>"BA;BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]
</code>```

I would like to achieve the following result:

```<code>[{:id=>1, :name=>"AA", :title=>"A row"},
 {:id=>1, :name=>"AB", :title=>"A row"},
 {:id=>1, :name=>"AC", :title=>"A row"},
 {:id=>2, :name=>"BA", :title=>"B row"},
 {:id=>2, :name=>"BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]
</code>```

In brief, I want to fully replicate a hash, splitting it by semicolon. In this case, :name have two hashes with one or more semicolons that should be split and consist on another hash.

I hope you have understand my question. Any help is highly appreciated.

答:
Using Enumerable#each_with_object

```<code>ary =
  [
    { id: 1, name: "AA;AB;AC", title: "A row" },
    { id: 2, name: "BA;BB", title: "B row" },
    { id: 3, name: "CA", title: "C row" }
  ]

ary.each_with_object([]) do |hash, new_ary|
  hash[:name].split(";").each do |name|
    new_ary << hash.merge(name: name)
  end
end
</code>```

Body:
I found another question similar to the one I have, but I was not able to replicate it (probably because it doesn't deal with hashes neither have symbols).

So, given the following array of hashes:

[{:id=>1, :name=>"AA;AB;AC", :title=>"A row"},
 {:id=>2, :name=>"BA;BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]

I would like to achieve the following result:

[{:id=>1, :name=>"AA", :title=>"A row"},
 {:id=>1, :name=>"AB", :title=>"A row"},
 {:id=>1, :name=>"AC", :title=>"A row"},
 {:id=>2, :name=>"BA", :title=>"B row"},
 {:id=>2, :name=>"BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]

In brief, I want to fully replicate a hash, splitting it by semicolon. In this case, :name have two hashes with one or more semicolons that should be split and consist on another hash.

I hope you have understand my question. Any help is highly appreciated.

Body:
Using Enumerable#each_with_object

ary =
  [
    { id: 1, name: "AA;AB;AC", title: "A row" },
    { id: 2, name: "BA;BB", title: "B row" },
    { id: 3, name: "CA", title: "C row" }
  ]

ary.each_with_object([]) do |hash, new_ary|
  hash[:name].split(";").each do |name|
    new_ary << hash.merge(name: name)
  end
end


答:
You only need a single value for each incoming request. The usual technique is to configure trusted origins on the server, eg:

trustedOrigins: [https://www.domain1.com, https://www.domain2.com]

Then check the runtime value of the origin header, which is sent by all modern browsers. If this is a trusted origin then add CORS headers:

Access-Control-Allow-Origin: https://www.domain2.com

A wildcard could be used but that is not recommended and also will not work as intended if you are also using credentialed requests (eg those with cookies).

Title: multiple CORS values being rejected in Go gin api


问:
Multiprocessing with Multithreading? How do I make this more efficient?
I have an interesting problem on my hands. I have access to a 128 CPU ec2 instance. I need to run a program that accepts a 10 million row csv, and sends a request to a DB for each row in that csv to augment the existing data in the csv. In order to speed this up, I use:

```<code>executor = concurrent.futures.ProcessPoolExecutor(len(chunks))
futures = [executor.submit(<func_name>, chnk) for chnk in chunks]
successes = concurrent.futures.wait(futures)
</code>```

I chunk up the 10 million row csv into 128 portions and then use futures to spin up 128 processes (+1 for the main one, so total 129). Each process takes a chunk, and retrieves the records for its chunk and spits the output into a file. At the end of the process, I merge all the files together and voila.

I have a few questions about this.

is this the most efficient way to do this?

by creating 128 subprocesses, am I really using the 128 CPUs of the machine?

would multithreading be better/more efficient?

can I multithread on each CPU?

advice on what to read up on?

Thanks in advance!

答:
Is this most efficient?

Hard to tell without profiling. There's always a bottleneck somewhere. For example if you are cpu limited, and the algorithm can't be made more efficient, that's probably a hard limit. If you're storage bandwidth limited, and you're already using efficient read/write caching (typically handled by the OS or by low level drivers), that's probably a hard limit.

Are all cores of the machine actually used?

(Assuming python is running on a single physical machine, and you mean individual cores of one cpu) Yes, python's mp.Process creates a new OS level process with a single thread which is then assigned to execute for a given amount of time on a physical core by the OS's scheduler. Scheduling algorithms are typically quite good, so if you have an equal number of busy threads as logical cores, the OS will keep all the cores busy.

Would threads be better?

Not likely. Python is not thread safe, so it must only allow a single thread per process run at a time. There are specific exceptions to this when a function is written in c or c++, and calls the python macro: Py_BEGIN_ALLOW_THREADS though this is not extremely common. If most of your time is spent in such functions, threads will actually be allowed to run concurrently, and will have less overhead compared to processes. Threads also share memory, making passing results back after completion easier (threads can simply modify some global state rather than passing results via a queue or similar).

multithreading on each CPU?

Again, I think what you probably have is a single CPU with 128 cores.. The OS scheduler decides which threads should run on each core at any given time. Unless the threads are releasing the GIL, only one thread from each process can run at a time. For example running 128 processes each with 8 threads would result in 1024 threads, but still only 128 of them could ever run at a time, so the extra threads would only add overhead.

what to read up on?

When you want to make code fast, you need to be profiling. Profiling for parallel processing is more challenging, and profiling for a remote / virtualized computer can sometimes be challenging as well. It is not always obvious what is making a particular piece of code slow, and the only way to be sure is to test it. Also look into the tools you're using. I'm specifically thinking about the database you're using, because most database software has had a great deal of work put into optimization, but you must use it in the correct way to get the most speed out of it. Batched requests come to mind rather than accessing a single row at a time.

Body:
I have an interesting problem on my hands. I have access to a 128 CPU ec2 instance. I need to run a program that accepts a 10 million row csv, and sends a request to a DB for each row in that csv to augment the existing data in the csv. In order to speed this up, I use:

executor = concurrent.futures.ProcessPoolExecutor(len(chunks))
futures = [executor.submit(<func_name>, chnk) for chnk in chunks]
successes = concurrent.futures.wait(futures)

I chunk up the 10 million row csv into 128 portions and then use futures to spin up 128 processes (+1 for the main one, so total 129). Each process takes a chunk, and retrieves the records for its chunk and spits the output into a file. At the end of the process, I merge all the files together and voila.

I have a few questions about this.

is this the most efficient way to do this?

by creating 128 subprocesses, am I really using the 128 CPUs of the machine?

would multithreading be better/more efficient?

can I multithread on each CPU?

advice on what to read up on?

Thanks in advance!


问:
Unable to get response from API using Micronaut
I am trying to make a POST request using the Micronaut framework with Java. I have created a 'client' class that is called and makes the request. Here is the code:

@Singleton
public class ApiClient {
  private final HttpClient httpClient;
  private final URI uri;

  public ApiClient(@Client(URL) HttpClient httpClient) {
    this.httpClient = httpClient;
    uri = UriBuilder.of(API_URL).build();
  }

  Mono<List<ApiResponse>> fetchResponse() {
    HttpRequest<?> request = HttpRequest.POST(uri, BODY)
      .header("Authorization", API_KEY);
    return Mono.from(httpClient.retrieve(request, Argument.listOf(ApiResponse.class)));
  }
}

```

My problem is that I have no idea what the response from API is. As far as I can tell, the call is made. But because the data returns in a Flux object, I can't interrogate the object to find the response. My suspicion is that the POJO I'm trying to store the response in isn't working. I can't tell if this is the case though.

答: You need to subscribe to the publisher to actually make the request and get a response. There are several subscribe methods depending on what you want to do

Body:
I am trying to make a POST request using the Micronaut framework with Java. I have created a 'client' class that is called and makes the request. Here is the code:

@Singleton
public class ApiClient {
  private final HttpClient httpClient;
  private final URI uri;

  public ApiClient(@Client(URL) HttpClient httpClient) {
    this.httpClient = httpClient;
    uri = UriBuilder.of(API_URL).build();
  }

  Mono<List<ApiResponse>> fetchResponse() {
    HttpRequest<?> request = HttpRequest.POST(uri, BODY)
      .header("Authorization", API_KEY);
    return Mono.from(httpClient.retrieve(request, Argument.listOf(ApiResponse.class)));
  }
}

My problem is that I have no idea what the response from API is. As far as I can tell, the call is made. But because the data returns in a Flux object, I can't interrogate the object to find the response. My suspicion is that the POJO I'm trying to store the response in isn't working. I can't tell if this is the case though.


问:
SqlKata how to insert many value from a list
How can I execute an insertmany using sqlkata? I have a list and I want to perform an insertmany</p>
```<code>public async Task<TimeSpan> AddBulk(List<Transaction> transactions)
{
        var cols = new[] { "Id", "Name", "Description", "Quantity", "AddedOn", "ModifiedOn" };
        Start = DateTime.Now;

        try
        {
            var result = await _db.Query("Transaction").InsertAsync(cols, new[] { transactions });
        }
        catch(Exception ex)
        {
        }

        TimeSpan = DateTime.Now - Start;
        return TimeSpan;
}
</code>```

答:
You can convert the list of your data to List<object[]> then try to insert multiple records like this:

```<code>        var cols = new[] {
            "YourField1",
            "YourField2" ,
            "YourField3"
        };

        var data = new List<object[]>();
        foreach (var item in YourListObject)
        {
            data.Add(new object[]
            {
                item.YourField1,
                item.YourField2,
                item.YourField3
            });

        }

        var affectedRows = _db.Query(typeof(Permission).Name)
            .Insert(cols, p);
</code>```

Body:
How can I execute an insertmany using sqlkata? I have a list and I want to perform an insertmany

public async Task<TimeSpan> AddBulk(List<Transaction> transactions)
{
        var cols = new[] { "Id", "Name", "Description", "Quantity", "AddedOn", "ModifiedOn" };
        Start = DateTime.Now;

        try
        {
            var result = await _db.Query("Transaction").InsertAsync(cols, new[] { transactions });
        }
        catch(Exception ex)
        {
        }

        TimeSpan = DateTime.Now - Start;
        return TimeSpan;
}

Body:
You can convert the list of your data to List<object[]> then try to insert multiple records like this:

        var cols = new[] {
            "YourField1",
            "YourField2" ,
            "YourField3"
        };

        var data = new List<object[]>();
        foreach (var item in YourListObject)
        {
            data.Add(new object[]
            {
                item.YourField1,
                item.YourField2,
                item.YourField3
            });

        }

        var affectedRows = _db.Query(typeof(Permission).Name)
            .Insert(cols, p);


问:
NetSuite Saved Search custom field results based on Month
My Problem: I would like to show results of a custom field based on the current Month in a single saved search.

Custom Field (PM Schedule) drop down with following selections:
-Monthly
-Quarterly
-Annually
(there are more options but this gives the picture)

Essentially what I want to do is as follows:

```<code>CASE WHEN TO_CHAR({today},'MM') = '01' THEN Show results 'Monthly', 'Quarterly', 'Annually
WHEN TO_CHAR({today},'MM') = '02' THEN Show results 'Monthly'
WHEN TO_CHAR({today},'MM') = '03' THEN Show results 'Monthly'
WHEN TO_CHAR({today},'MM') = '04' THEN Show results 'Monthly', 'Quarterly'
ect....
END
</code>```

I have 5 different combinations and my current solution is to run 5 different saved searches that run on the cooresponding Months:

```<code>Formula (Numeric): CASE WHEN TO_CHAR({today},'MM') = '01' THEN 1 ELSE 0 END
PM Schedule (custom): is any of Monthly, Quarterly, Annually
</code>```

This works but I want to know if there is a way to do this in a single saved search.

答:
Formula (numeric): is 1

```<code>DECODE({custbody_pm_schedule},
    'Annually', DECODE(TO_CHAR({today},'MM'),'01',1,0),
    'Quarterly', DECODE(TO_CHAR({today},'MM'),'01',1,'04',1,'07',1,'10',1,0),
    'Monthly', 1
,0)
</code>```

PM Schedule (custom): is any of Monthly

and add PM Schedule as a filter so the user can select. In February, only 'Monthly' will return any results.

Body:
My Problem: I would like to show results of a custom field based on the current Month in a single saved search.

Custom Field (PM Schedule) drop down with following selections:
-Monthly
-Quarterly
-Annually
(there are more options but this gives the picture)

Essentially what I want to do is as follows:

CASE WHEN TO_CHAR({today},'MM') = '01' THEN Show results 'Monthly', 'Quarterly', 'Annually
WHEN TO_CHAR({today},'MM') = '02' THEN Show results 'Monthly'
WHEN TO_CHAR({today},'MM') = '03' THEN Show results 'Monthly'
WHEN TO_CHAR({today},'MM') = '04' THEN Show results 'Monthly', 'Quarterly'
ect....
END

I have 5 different combinations and my current solution is to run 5 different saved searches that run on the cooresponding Months:

Formula (Numeric): CASE WHEN TO_CHAR({today},'MM') = '01' THEN 1 ELSE 0 END
PM Schedule (custom): is any of Monthly, Quarterly, Annually

This works but I want to know if there is a way to do this in a single saved search.

Body:
Formula (numeric): is 1

DECODE({custbody_pm_schedule},
    'Annually', DECODE(TO_CHAR({today},'MM'),'01',1,0),
    'Quarterly', DECODE(TO_CHAR({today},'MM'),'01',1,'04',1,'07',1,'10',1,0),
    'Monthly', 1
,0)

PM Schedule (custom): is any of Monthly

and add PM Schedule as a filter so the user can select. In February, only 'Monthly' will return any results.


问:
Choosing DB model for an app similar to Notion, Block-based ("paragraphs") or document-based?

1. The problem

Lately, it seems that many note managers with "infinite" tree structure are choosing a block model (where each paragraph is an entry in the DB), instead of a document or file model.

Blocks
Documents

Notion
 Workflowy
 Remnote
 Dynalist
 Roam Research
Evernote
 Obsidian
 Bear app

If you find any errors in the table, please let me know.

We have been developing an app very similar to Notion for 8 months now, also using the block model, but we are considering making a radical change and switching to the document model. The structure of our blocks in MongoDB currently looks like this:

```<code>_id: "61fd3ede7f6d2cc7a53ca669"
children: Array
    0: "61fd3ee87f6d2cc7a53ca66b"
    1: "61fd3ef37f6d2cc7a53ca671"
    2: "61fd3ef77f6d2cc7a53ca673"
backlinks: Array
type: "bullet"
parentPage: Array
    _id: "61fd3ede7f6e2ccra53ca664"
    userParent: "german-jablo"
    permisionParent: "edit, comment, read"
parentParagraph: "61fd3ede7f6d2cc7a53ca668"
content: "<p>This is a paragraph</p>"
isCollapsed: false
createdAt: 2022-02-04T14:57:34.280+00:00
updatedAt: 2022-02-04T14:57:59.585+00:00
</code>```

Many pages talk about the differences of both approaches (example) although in a very vague way, so we decided to open this thread to find a more scientific answer to the question.

Features of our app

app
Blocks that can be opened as documents
Blocks that can collapse or expand their children

Notion
Page type blocks
Toggle type blocks

Workflowy
All
All

Evernote
Documents
None

Our app
Page type blocks
All others

Our app has two types of "blocks". The page type (which, like in Notion, can be inserted into any note and generate a document "inside" the current document), and the rest of the blocks, which are equivalent to the "toggle" block type in Notion (i.e. they can be collapsed or their nested children can be expanded).

2. What we have tried

In trying to answer our question (which DB model would work best for our application), we've realized that the answer is probably "it depends". Perhaps both models have strengths or weaknesses in different types of operations or situations. That is why we formulated this comparison table describing how we believe the performance of both models would be for each of these operations.

Operation
Blocks
Documents
Apparent Winner

Fetch the contents of a page
Find all paragraphs in the DB.
Search the document in the DB.
Document

Render the content of a page**
Build the tree from the paragraphs recursively. You can omit the children of paragraphs whose isCollapsed property is true
Render the document
Document

Update the content of a paragraph in the DB
Only the modified paragraph is rewritten
The whole document is rewritten
Block

Alternatives for rendering very large documents *
Blocks can be fetched or rendered as you scroll (as Workflowy does), or as you expand child paragraphs that were collapsed.
I thought that Grifds could achieve similar behavior, breaking the document into smaller chunks and bringing them in piecemeal, but it doesn't support updating an individual chunk, or even the entire document. It could also corrupt an HTML by splitting it into binary format.
Block

Import or paste content
In addition to converting the clipboard to HTML and/or sanitizing it, you must set up paragraphs with tree structure recursively. Note: Roam Research e.g. supports importing in JSON format, but generally users do not handle this format beforehand.
Only convert the clipboard to HTML and/or sanitize the clipboard
Document

Copy content**
Clipboard must be sanitized and/or transformed
Correct by default**
Document

Real-Time Collaboration
At the document level, could use some tree-based (Json) library like Automerge, or combine with some CRDT library for paragraph level.
Could use tinymce solution.
Tie? Both seem to have their advantages and disadvantages.

*Render very large documents: Most users probably do not use notes larger than 250 kb (considering that multimedia files are referenced in a separate collection). Still, in the document model, the question arises: how can we load, render or edit large documents in manageable chunks? One idea we came up with is to split HTML documents that reach large dimensions into portions of a certain size in kb, instead of splitting them into paragraphs. (It would be like a kind of Gridfs that allows you to modify the file in parts.) Could this be a good idea?

**Should the DOM be nested? In order to be able to collapse or expand nested child paragraphs, note managers with a block model structure the DOM in a nested way (paragraphs are in divs, inside their parent divs, etc.). However, an alternative in the document model could be that when the user presses tab, only that block (HTML tag such as
 or
) is assigned an attribute with a number less than or equal to 1, representing the nesting levels relative to the previous block. This way when you press tab to nest or shift-tab to un-nest, you only have to modify one attribute of an HTML element instead of many elements; and the DOM stays simple, without having nested blocks.

3. Our conclusions

We believe that for each of the rows in the comparison table, benchmarks could be done measuring the performance of both models.
Other people have done something similar here and here, comparing the performance of note managers using both models. The problem with those tests is that it is difficult to draw an accurate conclusion about the goodness of both models. Obsidian uses documents locally, so you don't have to sync notes. Roam Research is a very new and poorly optimized app. Standard Notes encrypts notes locally. In other words, it's not always apples to apples.

And even if tests could be done, we believe that the answer may even depend on how each user uses the application. Suppose user A usually organizes his notes in long documents using paragraph nesting (to collapse or expand them). On the other hand user B usually organizes his notes by creating new documents within documents. It is likely that a block model based manager would work better for user A while a document based one would work better for B.

So, we tried to push our doubt as far as we could, but we are still not sure of the answer Which of the two models do you think would offer better performance for our app and why?

4. Update

I just found some very interesting information. It seems that both TinyMCE and CKEditor (up to version 4), the view and the model converge with the HTML being based on content-editable. However, CKEditor 5 switched to MVC [source 1], [source 2].

I've done a short test pasting a large clipboard of a few MB in TinyMCE 5, CKEditor 4 and CKEditor 5, and the latter has been a bit slower. I hope soon to be able to do more tests with other things like dragging blocks or rendering large documents.

In a GitHub thread about CKEditor 5's performance when working with large documents, one of the contributors said "It works slower than the native content-editable element obviously, but the typing experience is pretty well".

答:
Love how thorough you thought about the design of your application. I just want to add some suggestions you might look:

Obsidian is using a hybrid approach. It started document-based, but now supports block links and embeds while still being super-fast. From all programs tested in my benchmark you linked above, Obsidian was the fastest.

One of the most important functions of a notetaking tool is effectively searching the probably thousands of notes. I created an amazingly simple test (the "Spaghetti Parmesan"-test) where all block-based approaches currently fail. It is about searching for two ingredients (spaghetti and parmesan) in a recipe. When both ingredients are in different blocks, all common block-based applications ultimately fail to find the recipe. You can read more about this here. I also tried to start a discussion with some of the authors on Twitter but failed to get any serious results. If you want to continue the block-based approach, you might start designing a search algorithm that can handle search terms spread about blocks (if you haven't yet). I tried to outline an algorithm in the thread linked above, but not sure if it will really work with hundreds of thousands of blocks.

Body:
1. The problem

Lately, it seems that many note managers with "infinite" tree structure are choosing a block model (where each paragraph is an entry in the DB), instead of a document or file model.

Blocks
Documents

Notion
 Workflowy
 Remnote
 Dynalist
 Roam Research
Evernote
 Obsidian
 Bear app

If you find any errors in the table, please let me know.

We have been developing an app very similar to Notion for 8 months now, also using the block model, but we are considering making a radical change and switching to the document model. The structure of our blocks in MongoDB currently looks like this:

_id: "61fd3ede7f6d2cc7a53ca669"
children: Array
    0: "61fd3ee87f6d2cc7a53ca66b"
    1: "61fd3ef37f6d2cc7a53ca671"
    2: "61fd3ef77f6d2cc7a53ca673"
backlinks: Array
type: "bullet"
parentPage: Array
    _id: "61fd3ede7f6e2ccra53ca664"
    userParent: "german-jablo"
    permisionParent: "edit, comment, read"
parentParagraph: "61fd3ede7f6d2cc7a53ca668"
content: "
This is a paragraph
"
isCollapsed: false
createdAt: 2022-02-04T14:57:34.280+00:00
updatedAt: 2022-02-04T14:57:59.585+00:00

Many pages talk about the differences of both approaches (example) although in a very vague way, so we decided to open this thread to find a more scientific answer to the question.

Features of our app

app
Blocks that can be opened as documents
Blocks that can collapse or expand their children

Notion
Page type blocks
Toggle type blocks

Workflowy
All
All

Evernote
Documents
None

Our app
Page type blocks
All others

Our app has two types of "blocks". The page type (which, like in Notion, can be inserted into any note and generate a document "inside" the current document), and the rest of the blocks, which are equivalent to the "toggle" block type in Notion (i.e. they can be collapsed or their nested children can be expanded).

2. What we have tried

In trying to answer our question (which DB model would work best for our application), we've realized that the answer is probably "it depends". Perhaps both models have strengths or weaknesses in different types of operations or situations. That is why we formulated this comparison table describing how we believe the performance of both models would be for each of these operations.

Operation
Blocks
Documents
Apparent Winner

Fetch the contents of a page
Find all paragraphs in the DB.
Search the document in the DB.
Document

Render the content of a page**
Build the tree from the paragraphs recursively. You can omit the children of paragraphs whose isCollapsed property is true
Render the document
Document

Update the content of a paragraph in the DB
Only the modified paragraph is rewritten
The whole document is rewritten
Block

Alternatives for rendering very large documents *
Blocks can be fetched or rendered as you scroll (as Workflowy does), or as you expand child paragraphs that were collapsed.
I thought that Grifds could achieve similar behavior, breaking the document into smaller chunks and bringing them in piecemeal, but it doesn't support updating an individual chunk, or even the entire document. It could also corrupt an HTML by splitting it into binary format.
Block

Import or paste content
In addition to converting the clipboard to HTML and/or sanitizing it, you must set up paragraphs with tree structure recursively. Note: Roam Research e.g. supports importing in JSON format, but generally users do not handle this format beforehand.
Only convert the clipboard to HTML and/or sanitize the clipboard
Document

Copy content**
Clipboard must be sanitized and/or transformed
Correct by default**
Document

Real-Time Collaboration
At the document level, could use some tree-based (Json) library like Automerge, or combine with some CRDT library for paragraph level.
Could use tinymce solution.
Tie? Both seem to have their advantages and disadvantages.

*Render very large documents: Most users probably do not use notes larger than 250 kb (considering that multimedia files are referenced in a separate collection). Still, in the document model, the question arises: how can we load, render or edit large documents in manageable chunks? One idea we came up with is to split HTML documents that reach large dimensions into portions of a certain size in kb, instead of splitting them into paragraphs. (It would be like a kind of Gridfs that allows you to modify the file in parts.) Could this be a good idea?

**Should the DOM be nested? In order to be able to collapse or expand nested child paragraphs, note managers with a block model structure the DOM in a nested way (paragraphs are in divs, inside their parent divs, etc.). However, an alternative in the document model could be that when the user presses tab, only that block (HTML tag such as
 or
) is assigned an attribute with a number less than or equal to 1, representing the nesting levels relative to the previous block. This way when you press tab to nest or shift-tab to un-nest, you only have to modify one attribute of an HTML element instead of many elements; and the DOM stays simple, without having nested blocks.

3. Our conclusions

We believe that for each of the rows in the comparison table, benchmarks could be done measuring the performance of both models.
Other people have done something similar here and here, comparing the performance of note managers using both models. The problem with those tests is that it is difficult to draw an accurate conclusion about the goodness of both models. Obsidian uses documents locally, so you don't have to sync notes. Roam Research is a very new and poorly optimized app. Standard Notes encrypts notes locally. In other words, it's not always apples to apples.

And even if tests could be done, we believe that the answer may even depend on how each user uses the application. Suppose user A usually organizes his notes in long documents using paragraph nesting (to collapse or expand them). On the other hand user B usually organizes his notes by creating new documents within documents. It is likely that a block model based manager would work better for user A while a document based one would work better for B.

So, we tried to push our doubt as far as we could, but we are still not sure of the answer Which of the two models do you think would offer better performance for our app and why?

4. Update

I just found some very interesting information. It seems that both TinyMCE and CKEditor (up to version 4), the view and the model converge with the HTML being based on content-editable. However, CKEditor 5 switched to MVC [source 1], [source 2].

I've done a short test pasting a large clipboard of a few MB in TinyMCE 5, CKEditor 4 and CKEditor 5, and the latter has been a bit slower. I hope soon to be able to do more tests with other things like dragging blocks or rendering large documents.

In a GitHub thread about CKEditor 5's performance when working with large documents, one of the contributors said "It works slower than the native content-editable element obviously, but the typing experience is pretty well".


问:
openxlsx conditionalFormatting doesn't work as expected when certain characters are present in the rule
I'm using openxlsx to write data from a data frame to an excel file. I need the data to be coloured given some rules (eg if the value of a cell is A1 & B1 colour the cell with red).
The problem is that this doesn't seem to work when the string representing the rule contains the following characters: &, *. I assume that there might be more characters having an unusual behaviour, but for these two I've experienced the following:

&: if & is in the rule then the Excel file gets corrupt and it doesn't even open properly

*: if * is in the rule then all the cells are getting coloured regardless of their content, which is not the expected outcome

Here's the code I'm using:

```<code>library(openxlsx)

df <- data.frame(type=c("A1 & B1","A1","B2*","A & B2","C&","C!*"))

wb <- createWorkbook("test.xlsx")
addWorksheet(wb, "Sheet1")
writeData(wb, sheet = 1, df)

style1 <- createStyle(fontColour = "white", bgFill = "red")
style2 <- createStyle(fontColour = "black", bgFill = "yellow")

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 2:nrow(df)+1,
  type = "contains",
  rule = "A1 & B1",
  style = style1

)

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 2:nrow(df)+1,
  type = "contains",
  rule = "*",
  style = style2

)

saveWorkbook(wb, file = "test.xlsx", overwrite = TRUE)
</code>```

When using rules that do not include & or *, eg if we use rule = "A1" the behaviour is the expected and A1 & B1andA1 will be coloured. To clarify using multiple rules works fine, but when a rule including & or * is used then happens what I've explained above.

答:
Following this post you have to "escape" a literal * using a tilde. The & is a bit more tricky. But I remembered that I already had a similar issue when creating a docx and voila same solution applies here: You could replace a & by its html entity &:

Note: Additionally, as I guess that you want to start the conditional formatting in row 2 ... : 2:nrow(df)+1 will add +1 to each element of the sequence 2:nrow(df). To fix that use parantheses or do 1:nrow(df)+1

```<code>library(openxlsx)

df <- data.frame(type=c("A1 & B1","A1","B2*","A & B2","C&","C!*"))

wb <- createWorkbook("test.xlsx")
addWorksheet(wb, "Sheet1")
writeData(wb, sheet = 1, df)

style1 <- createStyle(fontColour = "white", bgFill = "red")
style2 <- createStyle(fontColour = "black", bgFill = "yellow")

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 1:nrow(df)+1,
  type = "contains",
  rule = "A1 & B1",
  style = style1

)

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 1:nrow(df)+1,
  type = "contains",
  rule = "~*",
  style = style2

)

saveWorkbook(wb, file = "test.xlsx", overwrite = TRUE)
</code>```

Body:
I'm using openxlsx to write data from a data frame to an excel file. I need the data to be coloured given some rules (eg if the value of a cell is A1 & B1 colour the cell with red).
The problem is that this doesn't seem to work when the string representing the rule contains the following characters: &, *. I assume that there might be more characters having an unusual behaviour, but for these two I've experienced the following:

&: if & is in the rule then the Excel file gets corrupt and it doesn't even open properly

*: if * is in the rule then all the cells are getting coloured regardless of their content, which is not the expected outcome

Here's the code I'm using:

library(openxlsx)

df <- data.frame(type=c("A1 & B1","A1","B2*","A & B2","C&","C!*"))

wb <- createWorkbook("test.xlsx")
addWorksheet(wb, "Sheet1")
writeData(wb, sheet = 1, df)

style1 <- createStyle(fontColour = "white", bgFill = "red")
style2 <- createStyle(fontColour = "black", bgFill = "yellow")

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 2:nrow(df)+1,
  type = "contains",
  rule = "A1 & B1",
  style = style1

)

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 2:nrow(df)+1,
  type = "contains",
  rule = "*",
  style = style2

)

saveWorkbook(wb, file = "test.xlsx", overwrite = TRUE)

When using rules that do not include & or *, eg if we use rule = "A1" the behaviour is the expected and A1 & B1andA1 will be coloured. To clarify using multiple rules works fine, but when a rule including & or * is used then happens what I've explained above.

Body:
Following this post you have to "escape" a literal * using a tilde. The & is a bit more tricky. But I remembered that I already had a similar issue when creating a docx and voila same solution applies here: You could replace a & by its html entity &amp;:

Note: Additionally, as I guess that you want to start the conditional formatting in row 2 ... : 2:nrow(df)+1 will add +1 to each element of the sequence 2:nrow(df). To fix that use parantheses or do 1:nrow(df)+1

library(openxlsx)

df <- data.frame(type=c("A1 & B1","A1","B2*","A & B2","C&","C!*"))

wb <- createWorkbook("test.xlsx")
addWorksheet(wb, "Sheet1")
writeData(wb, sheet = 1, df)

style1 <- createStyle(fontColour = "white", bgFill = "red")
style2 <- createStyle(fontColour = "black", bgFill = "yellow")

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 1:nrow(df)+1,
  type = "contains",
  rule = "A1 &amp; B1",
  style = style1

)

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 1:nrow(df)+1,
  type = "contains",
  rule = "~*",
  style = style2

)

saveWorkbook(wb, file = "test.xlsx", overwrite = TRUE)