问:
Filter array of objects by nested array of object value
Suppose I have an array of objects, each of which contains a nested array of objects likes:

```<code>[
  {
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 01, username: 'mike' },
      { id: 02, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 03, username: 'steve' },
      { id: 04, username: 'mike' },
      { id: 05, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 06, username: 'brad' },
      { id: 07, username: 'cameron' },
      { id: 08, username: 'liam' }
    ]
  }
]
</code>```

How can I filter the outer array by the username value inside its items nested array? Let's say output the items that contains in its inner arrays objects with property username: 'mike'?

答:
use filter and find in likes.

const filter = (data, name) =>
  data.filter(({ likes }) => likes.find(({ username }) => username === name));

const data = [
  {
    id: 1,
    title: "Lorem",
    private: false,
    likes: [
      { id: 01, username: "mike" },
      { id: 02, username: "john" },
    ],
  },
  {
    id: 2,
    title: "Ipsum",
    private: true,
    likes: [
      { id: 03, username: "steve" },
      { id: 04, username: "mike" },
      { id: 05, username: "sara" },
    ],
  },
  {
    id: 3,
    title: "Dolor",
    private: false,
    likes: [
      { id: 06, username: "brad" },
      { id: 07, username: "cameron" },
      { id: 08, username: "liam" },
    ],
  },
];

console.log(filter(data, "mike"));
console.log(filter(data, "blah"));```

Body:
Suppose I have an array of objects, each of which contains a nested array of objects likes:

[
  {
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 01, username: 'mike' },
      { id: 02, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 03, username: 'steve' },
      { id: 04, username: 'mike' },
      { id: 05, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 06, username: 'brad' },
      { id: 07, username: 'cameron' },
      { id: 08, username: 'liam' }
    ]
  }
]

How can I filter the outer array by the username value inside its items nested array? Let's say output the items that contains in its inner arrays objects with property username: 'mike'?


来源: stackexchange

问:
TypeError at /users/login/ __init__() takes 1 positional argument but 2 were given
I am currently working on a tutorial in the "Python Crash course" Book.

The tutorial is about creating a "Learning Log" Webapp with Django. The idea of the app is to allow users to: 1. create "Topics" they have learned about 2. add "Entries" to those Topics, describing details they have learned specific to those topics

I am currently stuck at the login page and receive an Error, when I run

http://localhost:8000/users/login/

urls.py

```<code>    from django.conf.urls import url
    # Importing the default login view provided by Django
    from django.contrib.auth.views import LoginView
    from .import views
    app_name = 'users'
    urlpatterns =[
    # Login page
    url(r'^login/$', LoginView , {'template_name':'users/login.html'},name = 'login'),
                 ]
</code>```

login.html

```<code>    {% extends "learning_logs/base.html" %}

    {% block content %}
    {% if form.errors %}
    <p> Your username and password didn't match.Please try again. </p>
    {% endif %}

    <form method="post" action="{%url 'users:login' %}">
    {%csrf_token %}
    {{form.as_p}}
    <button name="submit">log in</button>
    <input type="hidden" name="next" value="{%url 'learning_logs:index' %}"/>
    </form>

   {% endblock content %}
</code>```

base.html

```<code>    <p>
      <a href="{% url 'learning_logs:index' %}">Learning Log</a> -
      <a href="{% url 'learning_logs:topics'%}">Topics</a> -
      {% if user.is_authenticated %}
        Hello,{{user.username}}.
     {% else %}
       <a href="{% url 'users:login' %}">log in</a>
     {% endif %}
   </p>

   {% block content %}{% endblock content %}
</code>```

答:
The LoginView is a class-based view, you use the .as_view(…) [Django-doc] to use it in the urls.py. You can pass the template_name as parameter in the .as_view(…):

```<code>url(r'^login/$', LoginView<b>.as_view(template_name='users/login.html')</b>, name='login'),</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am currently working on a tutorial in the "Python Crash course" Book.

The tutorial is about creating a "Learning Log" Webapp with Django. The idea of the app is to allow users to: 1. create "Topics" they have learned about 2. add "Entries" to those Topics, describing details they have learned specific to those topics

I am currently stuck at the login page and receive an Error, when I run

http://localhost:8000/users/login/

urls.py

    from django.conf.urls import url
    # Importing the default login view provided by Django
    from django.contrib.auth.views import LoginView
    from .import views
    app_name = 'users'
    urlpatterns =[
    # Login page
    url(r'^login/$', LoginView , {'template_name':'users/login.html'},name = 'login'),
                 ]

login.html

    {% extends "learning_logs/base.html" %}

    {% block content %}
    {% if form.errors %}

 Your username and password didn't match.Please try again.

    {% endif %}

    <form method="post" action="{%url 'users:login' %}">
    {%csrf_token %}
    {{form.as_p}}
    <button name="submit">log in</button>
    <input type="hidden" name="next" value="{%url 'learning_logs:index' %}"/>
    </form>

   {% endblock content %}

base.html

      Learning Log -
      Topics -
      {% if user.is_authenticated %}
        Hello,{{user.username}}.
     {% else %}
       log in
     {% endif %}

   {% block content %}{% endblock content %}

Body:
The LoginView is a class-based view, you use the .as_view(…) [Django-doc] to use it in the urls.py. You can pass the template_name as parameter in the .as_view(…):

url(r'^login/$', LoginView.as_view(template_name='users/login.html'), name='login'),


问:
Get distinct values of two columns and merge into rows
I have a table named dbo.WebsiteIP having two columns IPAddress, SiteName, and I am doing a bulk insert the values to the this table which look like below

```<code>IPAddress       SiteName
192.168.30.6    website1.domain.com
192.168.30.6    website2.domain.com
192.168.30.7    website3.domain.com
192.168.30.7    website4.domain.com
192.168.30.7    website5.domain.com
192.168.30.7    website6.domain.com
192.168.30.7    website7.domain.com
192.168.30.8    website8.domain.com
192.168.30.8    website9.domain.com
192.168.30.8    website10.domain.com
192.168.30.8    website11.domain.com
192.168.30.9    website12.domain.com
192.168.30.8    website13.domain.com
192.168.30.8    website14.domain.com
192.168.30.24   website15.domain.com
192.168.30.8    website16.domain.com
192.168.30.8    website17.domain.com
</code>```

I want to do a distinct query for the IP Address and combine the SiteName like below

```<code>IPAddress       WebsiteName
192.168.30.6    website1, website2,
192.168.30.7    website3, website4, website5, website6, website7
192.168.30.8    website8, website9, website10, website11, website13, website14
192.168.30.9    website12
192.168.30.24   website15
</code>```

I can able to combine the IPAddress using the below query but how to combine the appropriate Sitename to the IP Address.

```<code>Update Table1
Set IP= (Select IPAddress + ',' + ' '
From dbo.WebsiteIP
GROUP BY IPAddress FOR XML PATH(''))
GO
</code>```

答:
The suggestions of using stuff is a good solution. If your version is SQL server 2017 or higher you can use the much simpler syntax of de function STRING_AGG.</p>

```<code>DECLARE @T Table(
IP VARCHAR(MAX),
WEBSITE VARCHAR(MAX))

INSERT INTO @T
VALUES    ('192.168.30.6','website1.domain.com')
        , ('192.168.30.6','website2.domain.com')
        , ('192.168.30.7','website3.domain.com')
        , ('192.168.30.7','website4.domain.com')
        , ('192.168.30.7','website5.domain.com')
        , ('192.168.30.7','website6.domain.com')
        , ('192.168.30.7','website7.domain.com')
        , ('192.168.30.8','website8.domain.com')
        , ('192.168.30.8','website9.domain.com')
        , ('192.168.30.8','website10.domain.com')
        , ('192.168.30.8','website11.domain.com')
        , ('192.168.30.9','website12.domain.com')
        , ('192.168.30.8','website13.domain.com')
        , ('192.168.30.8','website14.domain.com')
        , ('192.168.30.24','website15.domain.com')
        , ('192.168.30.8',' website16.domain.com')
        , ('192.168.30.8',' website17.domain.com');

SELECT t.IP, STRING_AGG(WEBSITE, ',') AS Websites
From @T t
GROUP BY t.IP
</code>```

Body:
I have a table named dbo.WebsiteIP having two columns IPAddress, SiteName, and I am doing a bulk insert the values to the this table which look like below

IPAddress       SiteName
192.168.30.6    website1.domain.com
192.168.30.6    website2.domain.com
192.168.30.7    website3.domain.com
192.168.30.7    website4.domain.com
192.168.30.7    website5.domain.com
192.168.30.7    website6.domain.com
192.168.30.7    website7.domain.com
192.168.30.8    website8.domain.com
192.168.30.8    website9.domain.com
192.168.30.8    website10.domain.com
192.168.30.8    website11.domain.com
192.168.30.9    website12.domain.com
192.168.30.8    website13.domain.com
192.168.30.8    website14.domain.com
192.168.30.24   website15.domain.com
192.168.30.8    website16.domain.com
192.168.30.8    website17.domain.com

I want to do a distinct query for the IP Address and combine the SiteName like below

IPAddress       WebsiteName
192.168.30.6    website1, website2,
192.168.30.7    website3, website4, website5, website6, website7
192.168.30.8    website8, website9, website10, website11, website13, website14
192.168.30.9    website12
192.168.30.24   website15

I can able to combine the IPAddress using the below query but how to combine the appropriate Sitename to the IP Address.

Update Table1
Set IP= (Select IPAddress + ',' + ' '
From dbo.WebsiteIP
GROUP BY IPAddress FOR XML PATH(''))
GO

Body:
The suggestions of using stuff is a good solution. If your version is SQL server 2017 or higher you can use the much simpler syntax of de function STRING_AGG.

DECLARE @T Table(
IP VARCHAR(MAX),
WEBSITE VARCHAR(MAX))

INSERT INTO @T
VALUES    ('192.168.30.6','website1.domain.com')
        , ('192.168.30.6','website2.domain.com')
        , ('192.168.30.7','website3.domain.com')
        , ('192.168.30.7','website4.domain.com')
        , ('192.168.30.7','website5.domain.com')
        , ('192.168.30.7','website6.domain.com')
        , ('192.168.30.7','website7.domain.com')
        , ('192.168.30.8','website8.domain.com')
        , ('192.168.30.8','website9.domain.com')
        , ('192.168.30.8','website10.domain.com')
        , ('192.168.30.8','website11.domain.com')
        , ('192.168.30.9','website12.domain.com')
        , ('192.168.30.8','website13.domain.com')
        , ('192.168.30.8','website14.domain.com')
        , ('192.168.30.24','website15.domain.com')
        , ('192.168.30.8',' website16.domain.com')
        , ('192.168.30.8',' website17.domain.com');

SELECT t.IP, STRING_AGG(WEBSITE, ',') AS Websites
From @T t
GROUP BY t.IP


问:
Am I correctly splitting a range input into a separate Svelte component? Is there a better way?
I’m new to Svelte and loving it! Making a single-component app with a few pieces of UI & shared state is ridiculously fun & easy (coming in with an intermediate knowledge of HTML, CSS, & JS, and beginner knowledge of React).

Ultimately, however, I am hoping to make more-complex apps that would involve a lot of inputs & state, so obviously, I need to understand how to use state between components.

However, I am slightly confused about the best way to make a custom input component and best use the state elsewhere. Specifically, I’m look to create a custom-styled input type="range" component and use it in a parent.

In the course of writing this question, I did find an approach that seems to work, but I can’t find something in the docs or in Googling that quite matches this case, so I’m unsure of my solution. Here is what I came up with: https://github.com/arrowtype/svelte-slider/.

A summary of my solution

I started from the SvelteJS Template (https://github.com/sveltejs/template).

My App.svelte is like this:

A simple SvelteJS slider component

Slider A value is {sliderValA}

    <SimpleSlider bind:value={sliderValA} min="0" max="10" step="1"/>

Slider B value is {sliderValB}

    <SimpleSlider bind:value={sliderValB} min="0" max="30" step="5"/>

A + B is {sliderValA + sliderValB}

```

<p><strong>And <code>SimpleSlider.svelte</code> is like this:</strong></p>

<pre class="lang-html prettyprint-override"><code><script>
    export let value = 5;
    export let min = 0;
    export let max = 10;
    export let step = 1;
</script>

<div class="slider-container">
    <input type="range" bind:value={value} min={min} max={max} step={step}>
    <span>{value}</span>
</div>

<style>
    .slider-container {
        display: flex;
        align-items: center;
    }
    input {
        margin:0 0.5em 0 0;
    }
</style>
</code>```

In my testing, this seems to work. But, I found it challenging to get there, and I’m unsure of whether this is the best practice.

Should I be doing anything more, like using the svelte/store module to handle global state (if not, when might I start to need that)?

答:
Honestly, this looks really good and seems like the way to go for me. Why would you want to use the global store? Using it means having the data everywhere available and saved in your app, which sounds like overkill, when the component is only needed in one little form. Doing it this way is better for small independent components.

There are only little improvements for your SimpleSlider.svelte I can think of:

```<code><script>
  export let moreProps = {}
</script>

<div class="slider-container">
    <input type="range" bind:value {min} {max} {step} {...moreProps}>
    <span>{value}</span>
</div>
</code>```

This approach takes advantage of sveltes shorthand syntax and reduces your amount of code. moreProps would be if you decide to pass additional properties like disable for example:

```<code><SimpleSlider bind:value={sliderValA} min="0" max="10" step="1" moreProps={{disabled:true}}/>
</code>```

Body:
I’m new to Svelte and loving it! Making a single-component app with a few pieces of UI & shared state is ridiculously fun & easy (coming in with an intermediate knowledge of HTML, CSS, & JS, and beginner knowledge of React).

Ultimately, however, I am hoping to make more-complex apps that would involve a lot of inputs & state, so obviously, I need to understand how to use state between components.

However, I am slightly confused about the best way to make a custom input component and best use the state elsewhere. Specifically, I’m look to create a custom-styled input type="range" component and use it in a parent.

In the course of writing this question, I did find an approach that seems to work, but I can’t find something in the docs or in Googling that quite matches this case, so I’m unsure of my solution. Here is what I came up with: https://github.com/arrowtype/svelte-slider/.

A summary of my solution

I started from the SvelteJS Template (https://github.com/sveltejs/template).

My App.svelte is like this:

A simple SvelteJS slider component

Slider A value is {sliderValA}

    <SimpleSlider bind:value={sliderValA} min="0" max="10" step="1"/>

Slider B value is {sliderValB}

    <SimpleSlider bind:value={sliderValB} min="0" max="30" step="5"/>

A + B is {sliderValA + sliderValB}

And SimpleSlider.svelte is like this:

    <input type="range" bind:value={value} min={min} max={max} step={step}>
    {value}

In my testing, this seems to work. But, I found it challenging to get there, and I’m unsure of whether this is the best practice.

Should I be doing anything more, like using the svelte/store module to handle global state (if not, when might I start to need that)?

Body:
Honestly, this looks really good and seems like the way to go for me. Why would you want to use the global store? Using it means having the data everywhere available and saved in your app, which sounds like overkill, when the component is only needed in one little form. Doing it this way is better for small independent components.

There are only little improvements for your SimpleSlider.svelte I can think of:

<script>
  export let moreProps = {}
</script>

<div class="slider-container">
    <input type="range" bind:value {min} {max} {step} {...moreProps}>
    <span>{value}</span>
</div>

This approach takes advantage of sveltes shorthand syntax and reduces your amount of code. moreProps would be if you decide to pass additional properties like disable for example:

<SimpleSlider bind:value={sliderValA} min="0" max="10" step="1" moreProps={{disabled:true}}/>


问:
How to filter out only the selected records in a Many2many field from all the other records in the model in odoo13 using domain filter
I am making a package model in which one can make packages and use it in the sales order, my model's name is sale.package.

```<code>class Package(models.Model):
    _name = 'sale.package'
    _description = 'Package table'

    name = fields.Char(string='Name', required=True)
    width = fields.Float(string='Width')
    height = fields.Float(string='Height')
    length = fields.Float(string='Length')
    maximum_weight = fields.Float(string='Maximum weight')
</code>```

In order to use it in the sale order form, I inherited the sale.order model and added a Many2many field to the sale order which selects the previously made packages, I also created an Onchange function that updates an One2many field in a newly made page in the same sale order.

```<code>class SaleOrderPackage(models.Model):
    _inherit = 'sale.order'

    packs = fields.Many2many('sale.package', string='Package')
    package_lines = fields.One2many('sale.package.lines', 'line_name', string='Package Lines')

    @api.onchange('packs')
    def _onchange_packs(self):
        for rec in self:
            lines = [(5, 0, 0)]
            for line in self.packs:
                values = {
                    'name_on_line': line.name,
                    'line_width': line.width,
                    'line_height': line.height,
                    'line_length': line.length,
                    'line_maximum_weight': line.maximum_weight,
                }
                lines.append((0, 0, values))
            rec.package_lines = lines
</code>```

Up to this everything is going fine, my new requirement is to add a smart button to the same sale order and upon clicking it, a tree view of the selected packages in the sale order must show up. I have added the smart button and defined a function in the python file which returns not only the selected but also all the packages made with the model.

```<code>    def selected_packages(self):
        print(self.packs)
        return {
            'name': 'Selected Packages',
            'domain': [],
            'view_type': 'form',
            'res_model': 'sale.package',
            'view_id': False,
            'view_mode': 'tree,form',
            'type': 'ir.actions.act_window'
        }
</code>```

As I am only a week into learning Odoo I am unable to figure out how to use the domain filter in this context, Please help.
Thanks in advance.

答:
If you need to show only the selected packages, You have just to filter records using their id.  </p>

<p>Use self.packs.ids to return the list of actual record ids corresponding to selected packages:  </p>

```<code>'domain': [('id', 'in', self.packs.ids)],
</code>```

Body:
I am making a package model in which one can make packages and use it in the sales order, my model's name is sale.package.

class Package(models.Model):
    _name = 'sale.package'
    _description = 'Package table'

    name = fields.Char(string='Name', required=True)
    width = fields.Float(string='Width')
    height = fields.Float(string='Height')
    length = fields.Float(string='Length')
    maximum_weight = fields.Float(string='Maximum weight')

In order to use it in the sale order form, I inherited the sale.order model and added a Many2many field to the sale order which selects the previously made packages, I also created an Onchange function that updates an One2many field in a newly made page in the same sale order.

class SaleOrderPackage(models.Model):
    _inherit = 'sale.order'

    packs = fields.Many2many('sale.package', string='Package')
    package_lines = fields.One2many('sale.package.lines', 'line_name', string='Package Lines')

    @api.onchange('packs')
    def _onchange_packs(self):
        for rec in self:
            lines = [(5, 0, 0)]
            for line in self.packs:
                values = {
                    'name_on_line': line.name,
                    'line_width': line.width,
                    'line_height': line.height,
                    'line_length': line.length,
                    'line_maximum_weight': line.maximum_weight,
                }
                lines.append((0, 0, values))
            rec.package_lines = lines

Up to this everything is going fine, my new requirement is to add a smart button to the same sale order and upon clicking it, a tree view of the selected packages in the sale order must show up. I have added the smart button and defined a function in the python file which returns not only the selected but also all the packages made with the model.

    def selected_packages(self):
        print(self.packs)
        return {
            'name': 'Selected Packages',
            'domain': [],
            'view_type': 'form',
            'res_model': 'sale.package',
            'view_id': False,
            'view_mode': 'tree,form',
            'type': 'ir.actions.act_window'
        }

As I am only a week into learning Odoo I am unable to figure out how to use the domain filter in this context, Please help.
Thanks in advance.

Body:
If you need to show only the selected packages, You have just to filter records using their id.

Use self.packs.ids to return the list of actual record ids corresponding to selected packages:

'domain': [('id', 'in', self.packs.ids)],


问:
Time complexity of T(n) = T(n - 1) + (n - 1)^2
I am wondering what is the time complexity of this recurrence relation.</p>

答:
T(n) = T(n-1) + f(n)

Means

T(n) = T(0) + Sum_from_i=1_to_n_of( f(i) )

In your case, that's:

T(n) = T(0) + 02 + 12 + 22 ... (n-1)2

If you don't know immediately from discrete calculus that the sum comes out to O(n3), you can notice that there are n terms, with the largest being (n-1)2, and there more than (n/3) terms that are  >= (n/2)2.


问:
incompatible character encodings: ASCII-8BIT and UTF-8 in Ruby 1.9
I'm getting the following error with my Ruby 1.9 & Rails 2.3.4. This happens when user submits a non-ASCII standard character.

I read a lot of online resources but none seems to have a solution that worked.

I tried using (as some resources suggested)

```<code>string.force_encoding('utf-8')
</code>```

but it didn't help.

Any ideas how to resolve this? Is there a way to eliminate such characters before saving to the DB? Or, is a there a way to make them show?

答:
For ruby 1.9 and Rails 3.0.x, use the mysql2 adapter.

In  your gemfile:

```<code>gem 'mysql2', '~> 0.2.7'
</code>```

and update your database.yml to:

```<code>adapter: mysql2
</code>```

http://www.rorra.com.ar/2010/07/30/rails-3-mysql-and-utf-8/

ContentLicense: CC BY-SA 3.0

Body:
I'm getting the following error with my Ruby 1.9 & Rails 2.3.4. This happens when user submits a non-ASCII standard character.

I read a lot of online resources but none seems to have a solution that worked.

I tried using (as some resources suggested)

string.force_encoding('utf-8')

but it didn't help.

Any ideas how to resolve this? Is there a way to eliminate such characters before saving to the DB? Or, is a there a way to make them show?

Body:
For ruby 1.9 and Rails 3.0.x, use the mysql2 adapter.

In  your gemfile:

gem 'mysql2', '~> 0.2.7'

and update your database.yml to:

adapter: mysql2

http://www.rorra.com.ar/2010/07/30/rails-3-mysql-and-utf-8/


问:
Change Fragment in Navigation Drawer Activity (Kotlin)
I've just started using Fragments and ViewModels. I want to replace fragments inside my activity, how can I do that?

What is the best approach to mix Android and Fragments together?

MainActivity

```<code>class MainActivity : AppCompatActivity(),NavigationView.OnNavigationItemSelectedListener {

    lateinit var drawerLayout: DrawerLayout
    lateinit var fragmentTransaction: FragmentTransaction

    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        drawerLayout= findViewById(R.id.drawer_layout)
        val navView: NavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)

        val toggle = ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_open)
            drawerLayout.addDrawerListener(toggle)
            toggle.syncState()

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        appBarConfiguration = AppBarConfiguration(setOf(
                R.id.nav_home, R.id.nav_dersler, R.id.nav_soru,R.id.nav_socialmedia), drawerLayout)
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

        navView.setNavigationItemSelectedListener(this);

    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.nav_home -> {
                  //Toast.makeText(this,"Anasayfa",Toast.LENGTH_SHORT).show()
                }
                R.id.nav_socialmedia -> {
                    Toast.makeText(this,"Sosyal Medya Hesaplarımızı Takip Edebilirsiniz",Toast.LENGTH_SHORT).show()
                }

                R.id.nav_dersler -> {

                }
                R.id.nav_soru -> {

                }

            }
            drawerLayout.closeDrawer(GravityCompat.START)
            return true

        }

        override fun onCreateOptionsMenu(menu: Menu): Boolean {
            menuInflater.inflate(R.menu.main, menu)
            return true
        }

        override fun onOptionsItemSelected(item: MenuItem): Boolean {
             when(item.itemId){
                R.id.action_refresh -> {
                    Toast.makeText(this,"Refreshing...",Toast.LENGTH_SHORT).show()
                    val refreshActivity = intent
                    finish()
                    startActivity(refreshActivity)
                    true
                }

                else -> super.onOptionsItemSelected(item)
            }
            return true
        }

        override fun onSupportNavigateUp(): Boolean {
            val navController = findNavController(R.id.nav_host_fragment)
            return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()

        }

}
</code>```

And i have mobile_navigation.xml but i don't know what it does. Thank you for your help
enter image description here

答:
TL;DR:

Activity is your base component for making Screens in your app.
Fragment is a dynamic part of your screen which was added to support Tablets with bigger screens.

We usually combine them in these manners:

One Activity as a container and all the screens represented as Fragments

For this approach, you can either

Implement it on your own:

Add fragments to your Activity stack:

```<code>supportFragmentManager
        .beginTransaction()
        .addToBackStack(null)
        .add(containerId, fragment, fragment::class.java.simpleName)
        .commit()
</code>```

Replace fragments in your Activity:

```<code>supportFragmentManager
        .beginTransaction()
        .replace(containerId, fragment, fragment::class.java.simpleName)
        .commit()
</code>```

But Android introduces Android Navigation Component to handle all these add, replacement and back stack handling:

I suggest using this approach, as its the easier one. LINK

Use multiple activities and fragments

For each screen that uses BottomNavigation, NavigationDrawer, and ... use an Activity with multiple Fragments representing each tab inside them.

A good tutorial can be found here. LINK

Body:
I've just started using Fragments and ViewModels. I want to replace fragments inside my activity, how can I do that?

What is the best approach to mix Android and Fragments together?

MainActivity

class MainActivity : AppCompatActivity(),NavigationView.OnNavigationItemSelectedListener {

    lateinit var drawerLayout: DrawerLayout
    lateinit var fragmentTransaction: FragmentTransaction

    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        drawerLayout= findViewById(R.id.drawer_layout)
        val navView: NavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)

        val toggle = ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_open)
            drawerLayout.addDrawerListener(toggle)
            toggle.syncState()

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        appBarConfiguration = AppBarConfiguration(setOf(
                R.id.nav_home, R.id.nav_dersler, R.id.nav_soru,R.id.nav_socialmedia), drawerLayout)
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

        navView.setNavigationItemSelectedListener(this);

    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.nav_home -> {
                  //Toast.makeText(this,"Anasayfa",Toast.LENGTH_SHORT).show()
                }
                R.id.nav_socialmedia -> {
                    Toast.makeText(this,"Sosyal Medya Hesaplarımızı Takip Edebilirsiniz",Toast.LENGTH_SHORT).show()
                }

                R.id.nav_dersler -> {

                }
                R.id.nav_soru -> {

                }

            }
            drawerLayout.closeDrawer(GravityCompat.START)
            return true

        }

        override fun onCreateOptionsMenu(menu: Menu): Boolean {
            menuInflater.inflate(R.menu.main, menu)
            return true
        }

        override fun onOptionsItemSelected(item: MenuItem): Boolean {
             when(item.itemId){
                R.id.action_refresh -> {
                    Toast.makeText(this,"Refreshing...",Toast.LENGTH_SHORT).show()
                    val refreshActivity = intent
                    finish()
                    startActivity(refreshActivity)
                    true
                }

                else -> super.onOptionsItemSelected(item)
            }
            return true
        }

        override fun onSupportNavigateUp(): Boolean {
            val navController = findNavController(R.id.nav_host_fragment)
            return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()

        }

}

And i have mobile_navigation.xml but i don't know what it does. Thank you for your help
enter image description here

Body:
TL;DR:

Activity is your base component for making Screens in your app.
Fragment is a dynamic part of your screen which was added to support Tablets with bigger screens.

We usually combine them in these manners:

One Activity as a container and all the screens represented as Fragments

For this approach, you can either

Implement it on your own:

Add fragments to your Activity stack:

supportFragmentManager
        .beginTransaction()
        .addToBackStack(null)
        .add(containerId, fragment, fragment::class.java.simpleName)
        .commit()

Replace fragments in your Activity:

supportFragmentManager
        .beginTransaction()
        .replace(containerId, fragment, fragment::class.java.simpleName)
        .commit()

But Android introduces Android Navigation Component to handle all these add, replacement and back stack handling:

I suggest using this approach, as its the easier one. LINK

Use multiple activities and fragments

For each screen that uses BottomNavigation, NavigationDrawer, and ... use an Activity with multiple Fragments representing each tab inside them.

A good tutorial can be found here. LINK


问:
Setting a global currency dropdown
I would like to setup a dropdown listing some currencies on all the pages of my website (Symfony 4.4).
The value set in this dropdown will then be used to adjust/convert the prices to the user's favorite currency.
I have been playing around some sessions parameters but it's not satisfactory. I feel like I need to place a hook in of the events, but I am not sure which event I should use.
I am thinking something like this

```<code>-- Request --
-- Event catcher --
  If (currency not set in the session) then set currency to default (e.g. USD or EUR), I will probably base this on the user's locale
-- Send reply --
</code>```

The tricky bit is to change the currency. I guess I need to set a route to change the session parameter and redirect to the current route.

I also thought about adding the currency in the route (which would be my favorite option), but I already have a language prefix (_locale) and I am not sure how I can apply multiple prefixes...
Thank you for any help or direction

答: For those interested, I ended up creating a Form that I called through a separate render query containing the new currency value and a redirect path to the current page. </p>

Title: Setting a global currency dropdown

Body:
I would like to setup a dropdown listing some currencies on all the pages of my website (Symfony 4.4).
The value set in this dropdown will then be used to adjust/convert the prices to the user's favorite currency.
I have been playing around some sessions parameters but it's not satisfactory. I feel like I need to place a hook in of the events, but I am not sure which event I should use.
I am thinking something like this

-- Request --
-- Event catcher --
  If (currency not set in the session) then set currency to default (e.g. USD or EUR), I will probably base this on the user's locale
-- Send reply --

The tricky bit is to change the currency. I guess I need to set a route to change the session parameter and redirect to the current route.

I also thought about adding the currency in the route (which would be my favorite option), but I already have a language prefix (_locale) and I am not sure how I can apply multiple prefixes...
Thank you for any help or direction


问:
React TypeError: this.state.List.map is not a function

import React, { Component } from "react";
import Project from "./components/Project.js"
import Form from "./Form.js";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            myProjects: [],
            userList: [],
        };

        this.createProject = this.createProject.bind(this);
    }

    createProject(title, desc, langs, len, exp) {
        this.setState({
            projectList: this.state.projectList.push(
                {
                    title : title,
                    description : desc,
                    language : langs,
                    length : len,
                    experience : exp
                }
            )
        });
    }

    deleteProject(title) {
        const projects = this.state.projectList.filter(
            p => p.title !== title
        );
        this.setState({projects});
    }

    render() {
        return(

                <Form createProject = {this.createProject} />
                {this.state.projectList.map((params) =>
                <Project {...params}/>)}

        );
    }

}

export default App;```

Hello, when running this, createProject gets passed as a prop to another class, which calls createProject with certain parameters. However, upon trying to render, it returns this error. TypeError: this.state.projectList.map is not a function. Any advice on how to fix it?

答:
push returns the new length of the array, it doesn't return the array. So this code is replacing the array with a number:

```<code>this.setState({
     projectList: this.state.projectList.push( // <============
         {
             title : title,
             description : desc,
             language : langs,
             length : len,
             experience : exp
         }
     )
 });
</code>```

Numbers don't have a map method. :-)

You probably wanted to do this, which creates a new array with the new item added to it:

```<code>this.setState({
     projectList: [...this.state.projectList, {
         title : title,
         description : desc,
         language : langs,
         length : len,
         experience : exp
     }]
 });
</code>```

Body:
import React, { Component } from "react";
import Project from "./components/Project.js"
import Form from "./Form.js";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            myProjects: [],
            userList: [],
        };

        this.createProject = this.createProject.bind(this);
    }

    createProject(title, desc, langs, len, exp) {
        this.setState({
            projectList: this.state.projectList.push(
                {
                    title : title,
                    description : desc,
                    language : langs,
                    length : len,
                    experience : exp
                }
            )
        });
    }

    deleteProject(title) {
        const projects = this.state.projectList.filter(
            p => p.title !== title
        );
        this.setState({projects});
    }

    render() {
        return(

                <Form createProject = {this.createProject} />
                {this.state.projectList.map((params) =>
                <Project {...params}/>)}

        );
    }

}

export default App;

Hello, when running this, createProject gets passed as a prop to another class, which calls createProject with certain parameters. However, upon trying to render, it returns this error. TypeError: this.state.projectList.map is not a function. Any advice on how to fix it?

Body:
push returns the new length of the array, it doesn't return the array. So this code is replacing the array with a number:

this.setState({
     projectList: this.state.projectList.push( // <============
         {
             title : title,
             description : desc,
             language : langs,
             length : len,
             experience : exp
         }
     )
 });

Numbers don't have a map method. :-)

You probably wanted to do this, which creates a new array with the new item added to it:

this.setState({
     projectList: [...this.state.projectList, {
         title : title,
         description : desc,
         language : langs,
         length : len,
         experience : exp
     }]
 });


答:
You cannot declare state like this, you can do something like:</p>

```<code>        this.setState({
            projectList: [...this.state.projectList, (
                {
                    title : title,
                    description : desc,
                    language : langs,
                    length : len,
                    experience : exp
                }
            )]
        });
</code>```

Title: React TypeError: this.state.List.map is not a function

Body:
You cannot declare state like this, you can do something like:

        this.setState({
            projectList: [...this.state.projectList, (
                {
                    title : title,
                    description : desc,
                    language : langs,
                    length : len,
                    experience : exp
                }
            )]
        });


问:
@kolkov/angular-editor images upload Usage Guide
I am able to put Kolkov editor on my html page but it doesn't attach image on editor though it does upload file to mentioned url and I can see response params from server having a url to access uploaded file.

There is tutorial available to integrate it as compoent into angular project but couldn't find anything on how to deal with images.

 If there are pointers in this regard, please help.

答:
It uploads image using "file" paramater on upload REST API.
So, on html

```<code> <app-ngx-editor height="500px" minHeight="500px" [placeholder]="'Enter text here...'"
[spellcheck]="true"  [(ngModel)]="htmlContent" imageEndPoint="https://localhost:8500/upload">
      </app-ngx-editor>
</code>```

And on REST side,

```<code>@PostMapping(path="/upload", produces = "application/json")
    @ResponseBody
    public Map FileUpload(@RequestParam("file") MultipartFile file, Model model) {

        Map<String,String> values = new HashMap<String,String>();
        storageService.store(file);
        values.put("url", "http://localhost:8500/files/"+file.getOriginalFilename());
        return values;
    }
</code>```

Body:
It uploads image using "file" paramater on upload REST API.
So, on html

 <app-ngx-editor height="500px" minHeight="500px" [placeholder]="'Enter text here...'"
[spellcheck]="true"  [(ngModel)]="htmlContent" imageEndPoint="https://localhost:8500/upload">
      </app-ngx-editor>

And on REST side,

@PostMapping(path="/upload", produces = "application/json")
    @ResponseBody
    public Map FileUpload(@RequestParam("file") MultipartFile file, Model model) {

        Map<String,String> values = new HashMap<String,String>();
        storageService.store(file);
        values.put("url", "http://localhost:8500/files/"+file.getOriginalFilename());
        return values;
    }


问:
Trying to run a Python Script from the terminal
Following the book 'Automate the boring stuff with Python' I wrote a Python script called mclip.py.

```<code>#! python3
# mclip.py - A multi-clipboard program.

TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""}

import sys, pyperclip

if len(sys.argv) < 2:
    print('Usage: py mclip.py [keyphrase] - copy phrase text')
    sys.exit()

keyphrase = sys.argv[1] # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard.')
else:
    print('There is no text for ' + keyphrase)
</code>```

When I run this in visual studio code I get:

```<code>XXX@XXXs-MacBook-Pro Python Projects % /usr/local/bin/python3 "/Users/XXX/Desktop/Python Projects/mclip.py"
Usage: py mclip.py [keyphrase] - copy phrase text
</code>```

But following the instructions of the book when trying to run the script from the terminal typing python3 mclip.py $busy I get:

```<code>XXX@XXXs-MacBook-Pro ~ % python3 mclip.py
/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'mclip.py': [Errno 2] No such file or directory
</code>```

It should copy the value of the specific keyword but is not doing so. I am not sure what is causing this problem. Help is much appreciated!

Maybe there could be a problem with the Path VSC is set up with but I am not sure.

答:
I managed to solve the Problem by myself and wanted to say here that no one has to bother finding a solution for me or in case my solution may be helpful for other people around here. My Mistakes were:

Trying to run the program without an argument. When calling the program I need
to call it with an argument: python3 mclip.py busy

Saving my scripts in an iCloud folder. Apparently it needs to be saved local.

These are all the changes I made and now it's running smoothly.

Thanks for the help anyone.

Body:
Following the book 'Automate the boring stuff with Python' I wrote a Python script called mclip.py.

#! python3
# mclip.py - A multi-clipboard program.

TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""}

import sys, pyperclip

if len(sys.argv) < 2:
    print('Usage: py mclip.py [keyphrase] - copy phrase text')
    sys.exit()

keyphrase = sys.argv[1] # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard.')
else:
    print('There is no text for ' + keyphrase)

When I run this in visual studio code I get:

XXX@XXXs-MacBook-Pro Python Projects % /usr/local/bin/python3 "/Users/XXX/Desktop/Python Projects/mclip.py"
Usage: py mclip.py [keyphrase] - copy phrase text

But following the instructions of the book when trying to run the script from the terminal typing python3 mclip.py $busy I get:

XXX@XXXs-MacBook-Pro ~ % python3 mclip.py
/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'mclip.py': [Errno 2] No such file or directory

It should copy the value of the specific keyword but is not doing so. I am not sure what is causing this problem. Help is much appreciated!

Maybe there could be a problem with the Path VSC is set up with but I am not sure.


问:
Python while loops issues
I'm wanting this code to constantly keep spitting out the variables {actual, wb, pbactual, pbsim}, which is what I have right now but I want wb and pbsim to be different values eachtime, because right now they are just printing the same list everytime, I would like it to be random. BTW the other variables are set by me and if you need them let me know!

Python

```<code>while win == False:
    while run:
        x = random.randint(1, rwb)
        if x not in wb:
            wb.append(x)
            pbactual.sort()

        if len(wb) == nwb2:
            while npb2 > 0:
                x = random.randint(1, rpb)
                if x not in pbsim:
                    pbsim.append(x)
                    npb2 = npb2 - 1
            run = False

    print(actual, wb, pbactual, pbsim)
</code>```

Variables

```<code>nwb = 5
nwb2 = 5
rwb = 10
npb = 2
npb2 = 2
rpb = 20
ballswin = 0
pbwin = 0
actual = []
wb = []
win = False
run = True
</code>```

答:
Something like following should get you working:

```<code>import time
random.seed(time.time())
</code>```

Setup random with time seed, every time different.

Title: Python while loops issues

Body:
I'm wanting this code to constantly keep spitting out the variables {actual, wb, pbactual, pbsim}, which is what I have right now but I want wb and pbsim to be different values eachtime, because right now they are just printing the same list everytime, I would like it to be random. BTW the other variables are set by me and if you need them let me know!

Python

while win == False:
    while run:
        x = random.randint(1, rwb)
        if x not in wb:
            wb.append(x)
            pbactual.sort()

        if len(wb) == nwb2:
            while npb2 > 0:
                x = random.randint(1, rpb)
                if x not in pbsim:
                    pbsim.append(x)
                    npb2 = npb2 - 1
            run = False

    print(actual, wb, pbactual, pbsim)

Variables

nwb = 5
nwb2 = 5
rwb = 10
npb = 2
npb2 = 2
rpb = 20
ballswin = 0
pbwin = 0
actual = []
wb = []
win = False
run = True

Body:
Something like following should get you working:

import time
random.seed(time.time())

Setup random with time seed, every time different.


问:
"Value cannot be null. Parameter name: source" while add item from connected table in View
in my project i have Two table: Restaurant(RestaurantId, Name, ...., Adress) and RestaurantReviews(ReviewsId, Mark, ...., RestaurantId). In my PartialView i try show Restaurant info and calculate Average Mark, but if i try calculate Average i getting error:

```<code>ArgumentNullException: Value cannot be null. (Parameter 'source')
</code>```

RestaurantModel

```<code>public class Restaurant
  {
    [Key]
    public int RestaurantId{ get; set; }

    ....

    [Required(ErrorMessage = "Restaurant name is empty")]
    public string Name{ get; set; }

    ....

    public virtual ICollection<RestaurantReviews> RestaurantReviews{ get; set; }

</code>```

RestaurantReviewsModel

```<code>public class RestaurantReviews
  {
    [Key]
    public int RestaurantReviewsId { get; set; }

    ....

    [Required(ErrorMessage = "Restaurant mark is empty")]
    public int Mark{ get; set; }

    [ForeignKey("Restaurant")]
    public int RestaurantId { get; set; }

    public virtual  Restaurant Restaurant {get; set; }

</code>```

DbContext

```<code> public DbSet<Restaurant> Restaurant { get; set; }
 public DbSet<RestaurantReviews> RestaurantReviews{ get; set; }
</code>```

Called PartialViews

```<code>@await Html.PartialAsync("~/Views/Restaurant/RestaurantWidget.cshtml", (IEnumerable<Firma.Data.Data.CMS.Restaurant>)ViewBag.RestaurantWidget)
</code>```

RestaurantWidget.cshtml

```<code>@model IEnumerable<Firma.Data.Data.CMS.Restaurant>

@foreach (var item in Model)
{
    ...
    @item.Name
    ...

    //Without this line everything is ok
    @item.RestaurantReviews.Average(x=>x.Mark)
    //Without this line everything is ok

   ...
}
</code>```

Controller

```<code>public IActionResult Index()
  {
     ViewBag.RestaurantWidget=
        (
           from restaurant in _context.Restaurant
           select restaurant
           ).Take(5).ToList();
        return View();
  }
</code>```

Additional info: Each restaurant has at least one rating. There is no restaurant that would not have any rating

答:
I find answer to my question, in Controller i change

```<code>public IActionResult Index()
  {
     ViewBag.RestaurantWidget=
        (
           from restaurant in _context.Restaurant
           select restaurant
           ).Take(5).ToList();
        return View();
  }
</code>```

to code below

```<code>ViewBag.RestaurantWidget= _context.Restaurant.Include(p=>p.RestaurantReviews).Take(4).ToList();

</code>```

Body:
in my project i have Two table: Restaurant(RestaurantId, Name, ...., Adress) and RestaurantReviews(ReviewsId, Mark, ...., RestaurantId). In my PartialView i try show Restaurant info and calculate Average Mark, but if i try calculate Average i getting error:

ArgumentNullException: Value cannot be null. (Parameter 'source')

RestaurantModel

public class Restaurant
  {
    [Key]
    public int RestaurantId{ get; set; }

    ....

    [Required(ErrorMessage = "Restaurant name is empty")]
    public string Name{ get; set; }

    ....

    public virtual ICollection<RestaurantReviews> RestaurantReviews{ get; set; }

RestaurantReviewsModel

public class RestaurantReviews
  {
    [Key]
    public int RestaurantReviewsId { get; set; }

    ....

    [Required(ErrorMessage = "Restaurant mark is empty")]
    public int Mark{ get; set; }

    [ForeignKey("Restaurant")]
    public int RestaurantId { get; set; }

    public virtual  Restaurant Restaurant {get; set; }

DbContext

 public DbSet<Restaurant> Restaurant { get; set; }
 public DbSet<RestaurantReviews> RestaurantReviews{ get; set; }

Called PartialViews

@await Html.PartialAsync("~/Views/Restaurant/RestaurantWidget.cshtml", (IEnumerable<Firma.Data.Data.CMS.Restaurant>)ViewBag.RestaurantWidget)

RestaurantWidget.cshtml

@model IEnumerable<Firma.Data.Data.CMS.Restaurant>

@foreach (var item in Model)
{
    ...
    @item.Name
    ...

    //Without this line everything is ok
    @item.RestaurantReviews.Average(x=>x.Mark)
    //Without this line everything is ok

   ...
}

Controller

public IActionResult Index()
  {
     ViewBag.RestaurantWidget=
        (
           from restaurant in _context.Restaurant
           select restaurant
           ).Take(5).ToList();
        return View();
  }

Additional info: Each restaurant has at least one rating. There is no restaurant that would not have any rating

Body:
I find answer to my question, in Controller i change

public IActionResult Index()
  {
     ViewBag.RestaurantWidget=
        (
           from restaurant in _context.Restaurant
           select restaurant
           ).Take(5).ToList();
        return View();
  }

to code below

ViewBag.RestaurantWidget= _context.Restaurant.Include(p=>p.RestaurantReviews).Take(4).ToList();


问:
Declare a resource outside the using statement
I have a question about C# using statement. According to the docs, it is a best practice to both declare and initialize the resource (for instance, a SqlConnection object) inside the using statement. My question is: if I'll only declare the object outside the using scope (and initialize it as part of the using statement), is it completely equal to declaring it as part of the using statement? My use case is that I need to use an SqlConnection object outside the using scope. (I would like to call SqlConnection.ClearPool on it, in case I get some specific exception.

答: Both scenarios are equivalent. But when you declare a variable outside the scope of the using statement, the variable will get disposed after the completion of the using statement's scope but still remain in scope. Accidental use of the variable after the using statement's scope may lead to exception to be thrown. This is considered to be bad practice and is avoided. I have never had reason to declare the variable before the using statement.


问:
Jquery Select load back after refresh page
Well, It's a simple one and I know there are a lot of source about this thing.

I've a jquery script like:

```<code><script>
    $(document).ready(function () {
        $("#CountryId").change(function () {
            $.get("@Url.Action("GetStateList","Controllers1")", { sOId: $("#CountryId").val() }, function (data) {
                $("#StateId").empty();
                $.each(data, function (index, row) {
                    $("#StateId").append("<option value='" + row.PersonnelNumber + "'>" + row.Name + "</option>")
                });
            });
        })
    });
</script>

public JsonResult GetStateList(string sOId)
    {
        string sPositionNumber = Session["xPersonnelNumber"].ToString();

        db.Configuration.ProxyCreationEnabled = false;
        List<Employee> StateList = db.Employees.Where(x => x.OrganizationNumber == sOId && x.Name != null).OrderBy(o => o.Name).ToList();
        return Json(StateList, JsonRequestBehavior.AllowGet);
    }
</code>```

After the page refresh, the StateId option is empty. How can I keep the option list after the page is refresh? If I remove the .Empty(), it will append another option. It's cascading dropdown using MVC .NET

Really appreciated.

答:
Your problem in your country options it is been selected first option automatically while you refresh,
so you can set your desire country for the states in page loading.</p>

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

        **$('#CountryId').val('desire country');**

        $("#CountryId").change(function () {
            $.get("@Url.Action("GetStateList","Controllers1")", { sOId: $("#CountryId").val() }, function (data) {
                $("#StateId").empty();
                $.each(data, function (index, row) {
                    $("#StateId").append("<option value='" + row.PersonnelNumber + "'>" + row.Name + "</option>")
                });
            });
        })
    });
</script>
</code>```

Body:
Well, It's a simple one and I know there are a lot of source about this thing.

I've a jquery script like:

public JsonResult GetStateList(string sOId)
    {
        string sPositionNumber = Session["xPersonnelNumber"].ToString();

        db.Configuration.ProxyCreationEnabled = false;
        List<Employee> StateList = db.Employees.Where(x => x.OrganizationNumber == sOId && x.Name != null).OrderBy(o => o.Name).ToList();
        return Json(StateList, JsonRequestBehavior.AllowGet);
    }

After the page refresh, the StateId option is empty. How can I keep the option list after the page is refresh? If I remove the .Empty(), it will append another option. It's cascading dropdown using MVC .NET

Really appreciated.

Body:
Your problem in your country options it is been selected first option automatically while you refresh,
so you can set your desire country for the states in page loading.

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

        **$('#CountryId').val('desire country');**

        $("#CountryId").change(function () {
            $.get("@Url.Action("GetStateList","Controllers1")", { sOId: $("#CountryId").val() }, function (data) {
                $("#StateId").empty();
                $.each(data, function (index, row) {
                    $("#StateId").append("<option value='" + row.PersonnelNumber + "'>" + row.Name + "</option>")
                });
            });
        })
    });
</script>


问:
SQL server recovery mechanism
I have a service application in C# which queries data from one database and inserts it into another SQL database.

Sometimes, the MSSQLSERVER service crashed for unknown reason and my application will crash as well. I want to do a SQL recovery mechanism that where I check to make sure the sqlconnection state is fine before i write to the database but how i do that?

I tried stopping MSSQLSERVER service and sqlconnection.State is always open even when the MSSQLSERVER service is stopped.

答:
I think that the approach you chose is not very good.

If your application is some kind of scheduled job, let it crash. No database - no work can be done. This is ok to crash in this case. Next time it runs and db is up it will do its thing. You can also implement retries.

If your application is a windows service inside and some kind of scheduled timer, you just make sure that your service doesn't crash by handling SqlExcpetion. Retry again until server is up.

Also, you might want to use distributed transactions. To guarantee integrity of the copy procedure, but whether you need it or not, depends on the requirements.

[Edit] In response to retry question.

```<code>var attemptNumber = 0;
while (true)
{
    try
    {
        using (var connection = new SqlConnection())
        {
            connection.Open();

            // do the job
        }
        break;
    }
    catch (SqlException exception)
    {
        // log exception
        attemptNumber++;
        if (attemptNumber > 3)
            throw; // let it crash
    }
}
</code>```

Title: SQL server recovery mechanism

Body:
I think that the approach you chose is not very good.

If your application is some kind of scheduled job, let it crash. No database - no work can be done. This is ok to crash in this case. Next time it runs and db is up it will do its thing. You can also implement retries.

If your application is a windows service inside and some kind of scheduled timer, you just make sure that your service doesn't crash by handling SqlExcpetion. Retry again until server is up.

Also, you might want to use distributed transactions. To guarantee integrity of the copy procedure, but whether you need it or not, depends on the requirements.

[Edit] In response to retry question.

var attemptNumber = 0;
while (true)
{
    try
    {
        using (var connection = new SqlConnection())
        {
            connection.Open();

            // do the job
        }
        break;
    }
    catch (SqlException exception)
    {
        // log exception
        attemptNumber++;
        if (attemptNumber > 3)
            throw; // let it crash
    }
}


问:
How to add a column based on groupby and number of occurences?
I have this DataFrame which is composed of 5 columns:

```<code> print(df)
               Date     Agent   PDF  Pages    Service
        0   2019-11-07  Mery     1    520        A
        1   2019-11-07  Edward   1    569        A
        2   2019-11-07  Mery     2    718        A
        3   2019-11-08  Edward   2    980        A
        4   2019-11-09  Mery     2    717        B
        5   2019-11-09  Edward   3    118        B
        6   2019-12-10  Mery     1    356        B
        7   2019-11-10  Edward   5    248        C
        8   2019-11-11  Mery     3    828        C
        9   2019-11-11  Edward   4    497        C
</code>```

I created a variable based on groupby() and columns Service and Agent as bellow:

```<code>X = df.groupby(['Service','Agent']).sum()
print(X)
                    PDF  Pages
 Service Agent
    A    Mery        3   1238
         Edward      3   1549
    B    Mery        3   1073
         Edward      3   118
    C    Mery        3   828
         Edward      9   745
</code>```

I want to add a column in which I can find the number of occurrences of the ['Agent'] column as bellow:

```<code>                    PDF  Pages Occu
 Service Agent
    A    Mery        3   1238   2
         Edward      3   1549   2
    B    Mery        3   1073   2
         Edward      3   118    1
    C    Mery        3   828    1
         Edward      9   745    2
</code>```

Thanks for the help!

答:
IIUC:</p>

```<code>df.groupby(['Service','Agent']).agg({'Pages':sum, 'PDF':sum, 'Agent':len})
</code>```

Body:
I have this DataFrame which is composed of 5 columns:

 print(df)
               Date     Agent   PDF  Pages    Service
        0   2019-11-07  Mery     1    520        A
        1   2019-11-07  Edward   1    569        A
        2   2019-11-07  Mery     2    718        A
        3   2019-11-08  Edward   2    980        A
        4   2019-11-09  Mery     2    717        B
        5   2019-11-09  Edward   3    118        B
        6   2019-12-10  Mery     1    356        B
        7   2019-11-10  Edward   5    248        C
        8   2019-11-11  Mery     3    828        C
        9   2019-11-11  Edward   4    497        C

I created a variable based on groupby() and columns Service and Agent as bellow:

X = df.groupby(['Service','Agent']).sum()
print(X)
                    PDF  Pages
 Service Agent
    A    Mery        3   1238
         Edward      3   1549
    B    Mery        3   1073
         Edward      3   118
    C    Mery        3   828
         Edward      9   745

I want to add a column in which I can find the number of occurrences of the ['Agent'] column as bellow:

                    PDF  Pages Occu
 Service Agent
    A    Mery        3   1238   2
         Edward      3   1549   2
    B    Mery        3   1073   2
         Edward      3   118    1
    C    Mery        3   828    1
         Edward      9   745    2

Thanks for the help!

Body:
IIUC:

df.groupby(['Service','Agent']).agg({'Pages':sum, 'PDF':sum, 'Agent':len})


问:
Decreasing the space between text and underline in hyperlink
I am playing around with custom hyperlinks for my WordPress page and would like to style them so that the underline hugs the bottom of the text very closely, i.e.: I want to be able to decrease the space between the text and the underline. So far I've found one solution that involves using an image in place of the underline, but I wonder if there are other solutions available.</p>

答:
You can use the border property of a span and then line-height to create the effect you're looking for without using an image:

```<code><a href="link.html"><span>Link</span></a>
</code>```

CSS:

```<code>span {
    display:inline-block;
    border-bottom:1px solid black;
    line-height: 12px;
}

a {
  text-decoration:none;
}
</code>```

Example: https://jsfiddle.net/fraggley/Lujyowxz/2/

Body:
You can use the border property of a span and then line-height to create the effect you're looking for without using an image:

<a href="link.html"><span>Link</span></a>

CSS:

span {
    display:inline-block;
    border-bottom:1px solid black;
    line-height: 12px;
}

a {
  text-decoration:none;
}

Example: https://jsfiddle.net/fraggley/Lujyowxz/2/


问:
Accessing vector in class
If I have a vector as a private member in my class, what's the best way to access it? For example, take the following simple class

```<code>class MCL{
    private:
    std::vector my_vec;

    public:
    // Include constructor here and other member functions
}
</code>```

What's the best way to access my_vec? Specifically, I would like to use a getter function to access it.

答:
Depending on the semantics of your class, you may want to implement operator[]:

```<code>T& operator[](int i) {
  return my_vec[i];
}
</code>```

This way you can user [] to access the contents of your vector:

```<code>MCL a;
a[0] = 3;
std::cout << a[0] << std::endl;
</code>```

Note that this may be considered abuse of operator[] or bad practice, but it is up to the developer to judge if this construct fits in the class, depending on its semantics.

Also note that this solution does not provides a way to insert or delete elements from the vector, just access to the elements already there. You may want to add other methods to do these or to implement something like:

```<code>T& operator[](int i) {
  if(my_vec.size() < i)
    my_vec.resize(i+1);
  return my_vec[i];
}
</code>```

Again, it is up to the semantics of your class and your usage pattern of it. This may or may not be a good idea.

Title: Accessing vector in class

Body:
If I have a vector as a private member in my class, what's the best way to access it? For example, take the following simple class

class MCL{
    private:
    std::vector my_vec;

    public:
    // Include constructor here and other member functions
}

What's the best way to access my_vec? Specifically, I would like to use a getter function to access it.

Body:
Depending on the semantics of your class, you may want to implement operator[]:

T& operator[](int i) {
  return my_vec[i];
}

This way you can user [] to access the contents of your vector:

MCL a;
a[0] = 3;
std::cout << a[0] << std::endl;

Note that this may be considered abuse of operator[] or bad practice, but it is up to the developer to judge if this construct fits in the class, depending on its semantics.

Also note that this solution does not provides a way to insert or delete elements from the vector, just access to the elements already there. You may want to add other methods to do these or to implement something like:

T& operator[](int i) {
  if(my_vec.size() < i)
    my_vec.resize(i+1);
  return my_vec[i];
}

Again, it is up to the semantics of your class and your usage pattern of it. This may or may not be a good idea.


问:
aws lambda deployed by zappa is not able to connect to remote database
I'm deploying a django project using zappa to aws-lambda and using mongodb atlas as my database.
I'm tring to connect to the database using djongo.
I set my django_setting in the zappa_settings.json to my project's django settings.
The connection to the database with this settings works just fine in localhost. when deploying, it fails to connect to the server and I suspect that it tries to connect to a default local db (the db sent to mongo_client.py isnt valid or something and it needs to connect to default HOST).

The actual error I get is:

```<code>pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused
The above exception was the direct cause of the following exception:
djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT
</code>```

If anyone has an idea I'd would love to hear.

attaching the settings with some fields unset (but set at my settings)
Django settings (database part):
DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'db',
        'HOST': 'mongodb://<username>:<password>@<>
        'USER': 'username',
        'PASSWORD': 'password',
        }
    }

zappa_settings:
{
        "dev":
        {
            "aws_region": "eu-west-1",
            "django_settings": settings,
            "profile_name": "default",
            "project_name": name,
            "runtime": "python3.6",
            "s3_bucket": bucket,
            "timeout_seconds": 900,
            "manage_roles": false,
            "role_name": name,
            "role_arn": arn,
            "slim_handler": true
        }
    }

答:
Try this

```<code>    'default': {
    'ENGINE': 'djongo',
    'CLIENT': {
        'host': 'mongodb+srv://url',
        'username': '<username>',
        'password': '<password>',
        'name':'<db_name>'
    }
}
</code>```

Body:
I'm deploying a django project using zappa to aws-lambda and using mongodb atlas as my database.
I'm tring to connect to the database using djongo.
I set my django_setting in the zappa_settings.json to my project's django settings.
The connection to the database with this settings works just fine in localhost. when deploying, it fails to connect to the server and I suspect that it tries to connect to a default local db (the db sent to mongo_client.py isnt valid or something and it needs to connect to default HOST).

The actual error I get is:

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused
The above exception was the direct cause of the following exception:
djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT

If anyone has an idea I'd would love to hear.

attaching the settings with some fields unset (but set at my settings)
Django settings (database part):
DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'db',
        'HOST': 'mongodb://<username>:<password>@<>
        'USER': 'username',
        'PASSWORD': 'password',
        }
    }

zappa_settings:
{
        "dev":
        {
            "aws_region": "eu-west-1",
            "django_settings": settings,
            "profile_name": "default",
            "project_name": name,
            "runtime": "python3.6",
            "s3_bucket": bucket,
            "timeout_seconds": 900,
            "manage_roles": false,
            "role_name": name,
            "role_arn": arn,
            "slim_handler": true
        }
    }

Body:
Try this

    'default': {
    'ENGINE': 'djongo',
    'CLIENT': {
        'host': 'mongodb+srv://url',
        'username': '<username>',
        'password': '<password>',
        'name':'<db_name>'
    }
}


问:
How to obtain data from sub query that has self join?
my table:

```<code>friends(uid_1 int, uid_2 int)
</code>```

This is my query :

```<code>SELECT a.uid_1
     , a.uid_2 as a2
     , b.uid_1 as b1
     , b.uid_2
  from friend a
  join friend b
    on a.uid_1 = b.uid_2;
</code>```

I want to obtain a2 and b1 from query for other purposes

So this query now:

```<code>Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
      from friend a join
           friend b
           on a.uid_1=b.uid_2
     )
</code>```

does not work. How do I obtain certain data from a range of displayed data?

答:
Number 1, you are just missing with a Alias name for your sub query as below-

```<code>Select a2,b1
from (
    SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
    from friend a join
    friend b
    on a.uid_1=b.uid_2
) A -- added A as a Alias
</code>```

But number 2, not sure what you are trying to do with the JOIN as your query with implemented JOIN conditions is simply equivalent to below query-

```<code>SELECT *
FROM friend
WHERE uid_1 = uid_2
</code>```

Body:
my table:

friends(uid_1 int, uid_2 int)

This is my query :

SELECT a.uid_1
     , a.uid_2 as a2
     , b.uid_1 as b1
     , b.uid_2
  from friend a
  join friend b
    on a.uid_1 = b.uid_2;

I want to obtain a2 and b1 from query for other purposes

So this query now:

Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
      from friend a join
           friend b
           on a.uid_1=b.uid_2
     )

does not work. How do I obtain certain data from a range of displayed data?

Body:
Number 1, you are just missing with a Alias name for your sub query as below-

Select a2,b1
from (
    SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
    from friend a join
    friend b
    on a.uid_1=b.uid_2
) A -- added A as a Alias

But number 2, not sure what you are trying to do with the JOIN as your query with implemented JOIN conditions is simply equivalent to below query-

SELECT *
FROM friend
WHERE uid_1 = uid_2


问:
PySpark: select a column based on the condition another columns values match some specific values, then create the match result as a new column
I ask the similarity questions before, but for some reasons, It is sad that I have to reimplement it in PySpark.

For example,

```<code>app      col1

app1     anybody love me?
app2     I hate u
app3     this hat is good
app4     I don't like this one
app5     oh my god
app6     damn you.
app7     such nice girl
app8     xxxxx
app9     pretty prefect
app10    don't love me.
app11    xxx anybody?
</code>```

I want to match a keyword list like ['anybody', 'love', 'you', 'xxx', 'don't'] and select the matched keyword result as a new column, named keyword as follows:

```<code>app      keyword

app1     [anybody, love]
app4     [don't]
app6     [you]
app8     [xxx]
app10    [don't, love]
app11    [xxx]
</code>```

As the accepted answer the suitable way I can do is create a temporary dataframe which is converted by a string list then inner join these two dataframe together.

And select the rows of app and keyword that are matched in the condition.

```<code>-- Hiveql implementation
select t.app, k.keyword
from  mytable t
inner join (values ('anybody'), ('you'), ('xxx'), ('don''t')) as k(keyword)
    on t.col1 like conca('%', k.keyword, '%')
</code>```

But I am not familiar with PySpark and awkward to reimplement it.

Could anyone help me?

Thanks in advances.

答:
Please find below two possible approaches:

Option 1

The first option is to use the dataframe API to implement the analogous join as in your previous question. Here we convert the keywords list into a dataframe and then join it with the large dataframe (notice that we broadcast the small dataframe to ensure better performance):

from pyspark.sql.functions import broadcast

df = spark.createDataFrame([
  ["app1", "anybody love me?"],
  ["app4", "I don't like this one"],
  ["app5", "oh my god"],
  ["app6", "damn you."],
  ["app7", "such nice girl"],
  ["app8", "xxxxx"],
  ["app10", "don't love me."]
]).toDF("app", "col1")

# create keywords dataframe
kdf = spark.createDataFrame([(k,) for k in keywords], "key string")

# +-----+
# |  key|
# +-----+
# |  xxx|
# |don't|
# +-----+

df.join(broadcast(kdf), df["col1"].contains(kdf["key"]), "inner")

# +-----+---------------------+-----+
# |app  |col1                 |key  |
# +-----+---------------------+-----+
# |app4 |I don't like this one|don't|
# |app8 |xxxxx                |xxx  |
# |app10|don't love me.       |don't|
# +-----+---------------------+-----+
```

<p>The join condition is based on contains function of the Column class.</p>

<p><strong>Option 2</strong></p>

<p>You also can use PySpark high-order function filter in combination with rlike within an expr:</p>

<pre class="lang-py prettyprint-override"><code>from pyspark.sql.functions import lit, expr, array

df = spark.createDataFrame([
  ["app1", "anybody love me?"],
  ["app4", "I don't like this one"],
  ["app5", "oh my god"],
  ["app6", "damn you."],
  ["app7", "such nice girl"],
  ["app8", "xxxxx"],
  ["app10", "don't love me."]
]).toDF("app", "col1")

keywords = ["xxx", "don't"]

df.withColumn("keywords", array([lit(k) for k in keywords])) \
  .withColumn("keywords", expr("filter(keywords, k -> col1 rlike k)")) \
  .where("size(keywords) > 0") \
  .show(10, False)

# +-----+---------------------+--------+
# |app  |col1                 |keywords|
# +-----+---------------------+--------+
# |app4 |I don't like this one|[don't] |
# |app8 |xxxxx                |[xxx]   |
# |app10|don't love me.       |[don't] |
# +-----+---------------------+--------+
</code>```

Explanation

with array([lit(k) for k in keywords]) we generate an array which contains the keywords that our search will be based on and then we append it to the existing dataframe using withColumn.

next with expr("size(filter(keywords, k -> col1 rlike k)) > 0") we go through the items of keywords trying to figure out if any of them is present in col1 text. If that is true filter will return one or more items and size will be greater than 0 which consists our where condition for retrieving the records.

Body:
I ask the similarity questions before, but for some reasons, It is sad that I have to reimplement it in PySpark.

For example,

app      col1

app1     anybody love me?
app2     I hate u
app3     this hat is good
app4     I don't like this one
app5     oh my god
app6     damn you.
app7     such nice girl
app8     xxxxx
app9     pretty prefect
app10    don't love me.
app11    xxx anybody?

I want to match a keyword list like ['anybody', 'love', 'you', 'xxx', 'don't'] and select the matched keyword result as a new column, named keyword as follows:

app      keyword

app1     [anybody, love]
app4     [don't]
app6     [you]
app8     [xxx]
app10    [don't, love]
app11    [xxx]

As the accepted answer the suitable way I can do is create a temporary dataframe which is converted by a string list then inner join these two dataframe together.

And select the rows of app and keyword that are matched in the condition.

-- Hiveql implementation
select t.app, k.keyword
from  mytable t
inner join (values ('anybody'), ('you'), ('xxx'), ('don''t')) as k(keyword)
    on t.col1 like conca('%', k.keyword, '%')

But I am not familiar with PySpark and awkward to reimplement it.

Could anyone help me?

Thanks in advances.

Body:
Please find below two possible approaches:

Option 1

The first option is to use the dataframe API to implement the analogous join as in your previous question. Here we convert the keywords list into a dataframe and then join it with the large dataframe (notice that we broadcast the small dataframe to ensure better performance):

from pyspark.sql.functions import broadcast

df = spark.createDataFrame([
  ["app1", "anybody love me?"],
  ["app4", "I don't like this one"],
  ["app5", "oh my god"],
  ["app6", "damn you."],
  ["app7", "such nice girl"],
  ["app8", "xxxxx"],
  ["app10", "don't love me."]
]).toDF("app", "col1")

# create keywords dataframe
kdf = spark.createDataFrame([(k,) for k in keywords], "key string")

# +-----+
# |  key|
# +-----+
# |  xxx|
# |don't|
# +-----+

df.join(broadcast(kdf), df["col1"].contains(kdf["key"]), "inner")

# +-----+---------------------+-----+
# |app  |col1                 |key  |
# +-----+---------------------+-----+
# |app4 |I don't like this one|don't|
# |app8 |xxxxx                |xxx  |
# |app10|don't love me.       |don't|
# +-----+---------------------+-----+

The join condition is based on contains function of the Column class.

Option 2

You also can use PySpark high-order function filter in combination with rlike within an expr:

from pyspark.sql.functions import lit, expr, array

df = spark.createDataFrame([
  ["app1", "anybody love me?"],
  ["app4", "I don't like this one"],
  ["app5", "oh my god"],
  ["app6", "damn you."],
  ["app7", "such nice girl"],
  ["app8", "xxxxx"],
  ["app10", "don't love me."]
]).toDF("app", "col1")

keywords = ["xxx", "don't"]

df.withColumn("keywords", array([lit(k) for k in keywords])) \
  .withColumn("keywords", expr("filter(keywords, k -> col1 rlike k)")) \
  .where("size(keywords) > 0") \
  .show(10, False)

# +-----+---------------------+--------+
# |app  |col1                 |keywords|
# +-----+---------------------+--------+
# |app4 |I don't like this one|[don't] |
# |app8 |xxxxx                |[xxx]   |
# |app10|don't love me.       |[don't] |
# +-----+---------------------+--------+

Explanation

with array([lit(k) for k in keywords]) we generate an array which contains the keywords that our search will be based on and then we append it to the existing dataframe using withColumn.

next with expr("size(filter(keywords, k -> col1 rlike k)) > 0") we go through the items of keywords trying to figure out if any of them is present in col1 text. If that is true filter will return one or more items and size will be greater than 0 which consists our where condition for retrieving the records.


问:
How to find duration of a webm (opus) audio file in seconds (in a js program)?
On a javascript web page I generate an audio message, using HTML5 Media API, and I send it through socketio to a nodejs server that save the file on disk. It all works.

Javascript chunk, client side:

```<code>navigator.mediaDevices
  .getUserMedia({ audio: true })
    .then(stream => {

      const mediaRecorder = new MediaRecorder(stream)
      ...
      }
</code>```

Server side I succesfully save the webm/opus file:

```<code>$ ll audiofiles/audiofile.webm
-rw-rw-r-- 1 username 180K May 29 21:04 audiofiles/audiofile.webm
</code>```

Using vlc player, I see that the duration in seconds is almost 28 seconds.

let's check with mediainfo / ffmpeg:

Using mediainfo:

```<code>$ mediainfo audiofiles/audiofile.webm
General
Complete name                            : audiofiles/audiofile.webm
Format                                   : WebM
Format version                           : Version 4 / Version 2
File size                                : 180 KiB
Writing application                      : Chrome
Writing library                          : Chrome
IsTruncated                              : Yes

Audio
ID                                       : 1
Format                                   : Opus
Codec ID                                 : A_OPUS
Channel(s)                               : 1 channel
Channel positions                        : Front: C
Sampling rate                            : 48.0 kHz
Bit depth                                : 32 bits
Compression mode                         : Lossy
Language                                 : English
Default                                  : Yes
Forced                                   : No
</code>```

Using ffmpeg:

```<code>$ ffmpeg -hide_banner -i audiofiles/audiofile.webm
Input #0, matroska,webm, from 'audiofiles/audiofile.webm':
  Metadata:
    encoder         : Chrome
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0(eng): Audio: opus, 48000 Hz, mono, fltp (default)
At least one output file must be specified
</code>```

My question is:

How can I trace, server side, on the node server log file, the length in seconds of the webm audio file?

I need to have the approssimative time duration (in seconds) of the file. Possibly using a nodejs function.

A bad/rough solution in runtime could be to empirically map the length in bytes of the file with the length in seconds...By example for the specific encoding/format: 1000 bytes ~= 1 sec.

Any better idea to measure the duration of the audio file, possibly in the nodejs code?

答:
Here a solution, starting from Tgrif proposal.
The bash script below convert the input webm file to a intermediate/temporary wav file.

```<code>$ cat com/duration
#!/bin/bash

#
# calculate duration in seconds of a webm file
# converting it in a wav temporary file
#
# usage: com/duration audiofiles/audiofile.webm
#

INPUT_FILE=$1
TMP_FILE=$1.wav

ffmpeg -loglevel panic -i $INPUT_FILE -y $TMP_FILE
ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $TMP_FILE
rm $TMP_FILE
</code>```

usage:

```<code>$ com/duration audiofiles/audiofile.webm
28.380000

$ time com/duration audiofiles/audiofile.webm
28.380000

real    0m0.182s
user    0m0.151s
sys 0m0.031s
</code>```

My script appears to me more a workaround and I still ask a better (faster) solution

UPGRADE

An alternative solution / workaround I adopted is to just measure on the browser js program the elapsed in msecs with a timer (Performance.now()) from the MediaRecorder.start() to the MediaRecorder.stop()

Body:
On a javascript web page I generate an audio message, using HTML5 Media API, and I send it through socketio to a nodejs server that save the file on disk. It all works.

Javascript chunk, client side:

navigator.mediaDevices
  .getUserMedia({ audio: true })
    .then(stream => {

      const mediaRecorder = new MediaRecorder(stream)
      ...
      }

Server side I succesfully save the webm/opus file:

$ ll audiofiles/audiofile.webm
-rw-rw-r-- 1 username 180K May 29 21:04 audiofiles/audiofile.webm

Using vlc player, I see that the duration in seconds is almost 28 seconds.

let's check with mediainfo / ffmpeg:

Using mediainfo:

$ mediainfo audiofiles/audiofile.webm
General
Complete name                            : audiofiles/audiofile.webm
Format                                   : WebM
Format version                           : Version 4 / Version 2
File size                                : 180 KiB
Writing application                      : Chrome
Writing library                          : Chrome
IsTruncated                              : Yes

Audio
ID                                       : 1
Format                                   : Opus
Codec ID                                 : A_OPUS
Channel(s)                               : 1 channel
Channel positions                        : Front: C
Sampling rate                            : 48.0 kHz
Bit depth                                : 32 bits
Compression mode                         : Lossy
Language                                 : English
Default                                  : Yes
Forced                                   : No

Using ffmpeg:

$ ffmpeg -hide_banner -i audiofiles/audiofile.webm
Input #0, matroska,webm, from 'audiofiles/audiofile.webm':
  Metadata:
    encoder         : Chrome
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0(eng): Audio: opus, 48000 Hz, mono, fltp (default)
At least one output file must be specified

My question is:

How can I trace, server side, on the node server log file, the length in seconds of the webm audio file?

I need to have the approssimative time duration (in seconds) of the file. Possibly using a nodejs function.

A bad/rough solution in runtime could be to empirically map the length in bytes of the file with the length in seconds...By example for the specific encoding/format: 1000 bytes ~= 1 sec.

Any better idea to measure the duration of the audio file, possibly in the nodejs code?

Body:
Here a solution, starting from Tgrif proposal.
The bash script below convert the input webm file to a intermediate/temporary wav file.

$ cat com/duration
#!/bin/bash

#
# calculate duration in seconds of a webm file
# converting it in a wav temporary file
#
# usage: com/duration audiofiles/audiofile.webm
#

INPUT_FILE=$1
TMP_FILE=$1.wav

ffmpeg -loglevel panic -i $INPUT_FILE -y $TMP_FILE
ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $TMP_FILE
rm $TMP_FILE

usage:

$ com/duration audiofiles/audiofile.webm
28.380000

$ time com/duration audiofiles/audiofile.webm
28.380000

real    0m0.182s
user    0m0.151s
sys 0m0.031s

My script appears to me more a workaround and I still ask a better (faster) solution

UPGRADE

An alternative solution / workaround I adopted is to just measure on the browser js program the elapsed in msecs with a timer (Performance.now()) from the MediaRecorder.start() to the MediaRecorder.stop()