问:
Display a String in Asp.Net Core 3.0 MVC ViewModel
Currently learning Asp.Net Core. I was learning with Razor pages initially and had everything working fine, but ditched them in favour of familiarizing with MVC first.

Despite online courses etc. I've been struggling for 3 days to get a simple string to display using a ViewModel and now my mind is frazzled!

I want to inject a string into my cshtml page, so that the string can come from a strings library. I had all this all setup and working fine with Razor pages, but I cannot get a simple string to display using MVC unless I use ViewBag. I want to use ViewModel. What am I missing?

Any help would be much appreciated.

AboutViewModel.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApp.Models
{
    public class AboutViewModel
    {
        public string Title { get; set; }

        public void OnGet()
        {
            Title = "Test";
        }
    }
}
</code>```

AboutController.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using MyApp.Models;

namespace MyApp.Controllers
{
    public class AboutController : Controller
    {
        public IActionResult About()
        {
            return View();
        }
    }
}
</code>```

About.cshtml

```<code>@model AboutViewModel
    @{
        ViewData["Title"] = _loc["About Us"];
    }

<body>
    <div>
        @Model.Title
    </div>
</body>
</code>```

Error:

```<code> NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_About_About.<ExecuteAsync>b__12_2() in About.cshtml, line 22

NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_About_About.<ExecuteAsync>b__12_2() in About.cshtml
+
        @Model.Title
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
AspNetCore.Views_About_About.ExecuteAsync() in About.cshtml
+
        ViewData["Title"] = _loc["About Us"];
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
</code>```

Thoughts:

I'm pretty sure I'm crossing over with Razor pages here and my OnGet method is useless for MVC?
I have tried putting all sorts of code into my controller and nothing seems to work.

Response to Suggestion Below:

If I change my controller to:

```<code>    public IActionResult About()
    {
        var viewModel = new AboutViewModel();

        return View(viewModel);
    }
</code>```

then the error disappears but the string still doesnt display.

答:
```<code> public IActionResult About()
    {
        var viewModel = new AboutViewModel();
         viewModel .Title = "Test";
        return View(viewModel);
    }
</code>```

Body:
Currently learning Asp.Net Core. I was learning with Razor pages initially and had everything working fine, but ditched them in favour of familiarizing with MVC first.

Despite online courses etc. I've been struggling for 3 days to get a simple string to display using a ViewModel and now my mind is frazzled!

I want to inject a string into my cshtml page, so that the string can come from a strings library. I had all this all setup and working fine with Razor pages, but I cannot get a simple string to display using MVC unless I use ViewBag. I want to use ViewModel. What am I missing?

Any help would be much appreciated.

AboutViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApp.Models
{
    public class AboutViewModel
    {
        public string Title { get; set; }

        public void OnGet()
        {
            Title = "Test";
        }
    }
}

AboutController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using MyApp.Models;

namespace MyApp.Controllers
{
    public class AboutController : Controller
    {
        public IActionResult About()
        {
            return View();
        }
    }
}

About.cshtml

@model AboutViewModel
    @{
        ViewData["Title"] = _loc["About Us"];
    }

        @Model.Title

Error:

 NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_About_About.<ExecuteAsync>b__12_2() in About.cshtml, line 22

NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_About_About.<ExecuteAsync>b__12_2() in About.cshtml
+
        @Model.Title
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
AspNetCore.Views_About_About.ExecuteAsync() in About.cshtml
+
        ViewData["Title"] = _loc["About Us"];
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)

Thoughts:

I'm pretty sure I'm crossing over with Razor pages here and my OnGet method is useless for MVC?
I have tried putting all sorts of code into my controller and nothing seems to work.

Response to Suggestion Below:

If I change my controller to:

    public IActionResult About()
    {
        var viewModel = new AboutViewModel();

        return View(viewModel);
    }

then the error disappears but the string still doesnt display.


来源: stackexchange

问:
Copy . . in dockerfile
I understand that COPY can copy files from source folder to destination, but what is purpose of COPY . .?

For example:

```<code>FROM ruby:2.5.1
WORKDIR /usr/src/app
COPY Gemfile Gemfile.lock ./
RUN bundle install
COPY . .
CMD ["./your-daemon-or-script.rb"]
</code>```

答:
See the WORKDIR

This command will copy all the content of the parent directory in which your dockerfile resides(contents of your machine) to the location of the WORKDIR in your container.

ContentLicense: CC BY-SA 4.0

Title: Copy . . in dockerfile

Body:
I understand that COPY can copy files from source folder to destination, but what is purpose of COPY . .?

For example:

FROM ruby:2.5.1
WORKDIR /usr/src/app
COPY Gemfile Gemfile.lock ./
RUN bundle install
COPY . .
CMD ["./your-daemon-or-script.rb"]


问:
Read a very long line of text C#
I want to read a very long line of text using C#. The length of the line is about 100000 chars. I am using StreamReader.ReadLine() method. I also want to write this long string to a file. One of them or both are not working properly. I could only write 99328 characters to a file.
How can I read and write a very long line of text using  C#?</p>

答:
I suspect that you did not close your output buffer and it's not completing the file write.

Consider using
File.ReadAllText

http://msdn.microsoft.com/en-us/library/ms143368.aspx

and File.WriteAllText

http://msdn.microsoft.com/en-us/library/ms143375.aspx

ContentLicense: CC BY-SA 3.0

Title: Read a very long line of text C#


问:
detecting the maximum and minimum peaks of real-time pressure signal also calculating it
I am detecting in real time a pressure signal by a pressure sensor and try to plot it with pyqtgraph.
I managed to find the maxima of the signal by using the find_peaks function from scipy library.

```<code>    self.peaktimer = QtCore.QTimer()
    self.peaktimer.setInterval(5000)
    self.peaktimer.timeout.connect(self.peak_calculator)
    self.peaktimer.start()

def update_plot_data(self):

    print(self.y)

    self.x = self.x[1:]  # Remove the first y element.
    self.x.append(self.x[-1] + 1)  # Add a new value 1 higher than the last.
    #self.x.append(measure)

    self.y = self.y[1:]  # Remove the first
    self.y.append( randint(0,100))  # Add a new random value.
    #self.y.append( measuree)
    peaks.append(self.y)

    self.data_line.setData(self.x, self.y)  # Update the data.

# for finding highest peak values
def peak_calculator(self):

    global peaks

    self.indices = find_peaks(peaks, threshold=1)[0]

    print("result: ", len(self.indices))
    print("systolic", np.mean(self.indices)

    peaks = []
</code>```

Is there a possibility to also find the minima(mimimum peaks value) with find_peaks?

答:
Yes multiply peaks by -1 this will have the effect of turning your signal upside-down whilst keeping the indices intact. That is the indices of the peaks found in -peaks give you the indices of the minima in peaks eg...

```<code>def peak_calculator(self):

    global peaks
    self.indices = find_peaks(peaks, threshold=1)[0]

    peaks_min = peaks * -1
    indices_min = find_peaks(peaks_min, threshold=1)[0]
</code>```

The heights of the peaks in either case can be found if you return the properties as well as the indices from find_peaks()

eg

```<code>indices, props = find_peaks(peaks, threshold=1)
maxima_heights = props[‘peak_heights’]
</code>```

Body:
I am detecting in real time a pressure signal by a pressure sensor and try to plot it with pyqtgraph.
I managed to find the maxima of the signal by using the find_peaks function from scipy library.

    self.peaktimer = QtCore.QTimer()
    self.peaktimer.setInterval(5000)
    self.peaktimer.timeout.connect(self.peak_calculator)
    self.peaktimer.start()

def update_plot_data(self):

    print(self.y)

    self.x = self.x[1:]  # Remove the first y element.
    self.x.append(self.x[-1] + 1)  # Add a new value 1 higher than the last.
    #self.x.append(measure)

    self.y = self.y[1:]  # Remove the first
    self.y.append( randint(0,100))  # Add a new random value.
    #self.y.append( measuree)
    peaks.append(self.y)

    self.data_line.setData(self.x, self.y)  # Update the data.

# for finding highest peak values
def peak_calculator(self):

    global peaks

    self.indices = find_peaks(peaks, threshold=1)[0]

    print("result: ", len(self.indices))
    print("systolic", np.mean(self.indices)

    peaks = []

Is there a possibility to also find the minima(mimimum peaks value) with find_peaks?

Body:
Yes multiply peaks by -1 this will have the effect of turning your signal upside-down whilst keeping the indices intact. That is the indices of the peaks found in -peaks give you the indices of the minima in peaks eg...

def peak_calculator(self):

    global peaks
    self.indices = find_peaks(peaks, threshold=1)[0]

    peaks_min = peaks * -1
    indices_min = find_peaks(peaks_min, threshold=1)[0]

The heights of the peaks in either case can be found if you return the properties as well as the indices from find_peaks()

eg

indices, props = find_peaks(peaks, threshold=1)
maxima_heights = props[‘peak_heights’]


问:
Telegram API Client doesn't find group/send message
Im using TLSharp API Client for sending messages to groups, TLSharp is C#, but im trying to use it for VB.NET

C# Code:

```<code> //get user dialogs
  var dialogs = (TLDialogsSlice) await client.GetUserDialogsAsync();

  //find channel by title
  var chat = dialogs.Chats
    .Where(c => c.GetType() == typeof(TLChannel))
    .Cast<TLChannel>()
    .FirstOrDefault(c => c.Title == "<channel_title>");

  //send message
  await client.SendMessageAsync(new TLInputPeerChannel() { ChannelId = chat.Id, AccessHash = chat.AccessHash.Value }, "OUR_MESSAGE");
</code>```

My VB.NET Code:

```<code>Dim dialogs = Await ((Await client.GetUserDialogsAsync()))
            Dim chat = dialogs.Chats.lists.Where(Function(c) c.[GetType]() = GetType(TLChat)).Cast(Of TLChat)().FirstOrDefault(Function(c) c.title = "Group1")
            Dim ChatId
            Await client.SendMessageAsync(New TLInputPeerChat() {ChatId = chat.Id}, "TEST MSG")
</code>```

The error i get:

Could not find public member 'GetAwaiter' in type 'TLDialogs'.'

I know it's not practical to convert it to vb.net, but I need it to integrate it into a project written in vb

答:
I don't think that the client.GetUserDialogsAsync() method returns anything that is awaitable, so you should probably only have one Await in the line Dim dialogs = Await ((Await client.GetUserDialogsAsync())), and it may also require a cast:

```<code>Dim dialogs = DirectCast(Await client.GetUserDialogsAsync(), TLDialogsSlice)
</code>```

Body:
Im using TLSharp API Client for sending messages to groups, TLSharp is C#, but im trying to use it for VB.NET

C# Code:

 //get user dialogs
  var dialogs = (TLDialogsSlice) await client.GetUserDialogsAsync();

  //find channel by title
  var chat = dialogs.Chats
    .Where(c => c.GetType() == typeof(TLChannel))
    .Cast<TLChannel>()
    .FirstOrDefault(c => c.Title == "<channel_title>");

  //send message
  await client.SendMessageAsync(new TLInputPeerChannel() { ChannelId = chat.Id, AccessHash = chat.AccessHash.Value }, "OUR_MESSAGE");

My VB.NET Code:

Dim dialogs = Await ((Await client.GetUserDialogsAsync()))
            Dim chat = dialogs.Chats.lists.Where(Function(c) c.[GetType]() = GetType(TLChat)).Cast(Of TLChat)().FirstOrDefault(Function(c) c.title = "Group1")
            Dim ChatId
            Await client.SendMessageAsync(New TLInputPeerChat() {ChatId = chat.Id}, "TEST MSG")

The error i get:

Could not find public member 'GetAwaiter' in type 'TLDialogs'.'

I know it's not practical to convert it to vb.net, but I need it to integrate it into a project written in vb

Body:
I don't think that the client.GetUserDialogsAsync() method returns anything that is awaitable, so you should probably only have one Await in the line Dim dialogs = Await ((Await client.GetUserDialogsAsync())), and it may also require a cast:

Dim dialogs = DirectCast(Await client.GetUserDialogsAsync(), TLDialogsSlice)


问:
How to Detach Firestore SnapshotListener in Repository (MVVM)
I believe I need to detach Firestore listeners but I can't see how to do this without passing the context to my repository.  Below is one example:

Fragment

This method is called in onViewCreated and simply updates private var sitesList = ArrayList<SiteObject>() which is used to set list in my recyclerview:

    private fun setupObservers() {
        Log.d(TAG, "setupObservers()")
        businessViewModel.listenToSites().observe(viewLifecycleOwner, Observer { allSites ->
            if (sitesList != allSites && allSites != null) {
                sitesList.clear()
                sitesList.addAll(allSites)
                sitesAdapter.setList(sitesList)
                sitesAdapter.notifyDataSetChanged()
            }
        })
    }```
</div>
</div>
</p>

<p><strong>ViewModel</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    fun listenToSites(): LiveData<ArrayList<SiteObject>> {
        Log.d(TAG, "listenToSites()")
        return businessRepository.listenToSites()
    }</code>```

Repository

This is where the Firestore addSnapshotListener is created:

  fun listenToSites(): LiveData<ArrayList<SiteObject>> {

        Log.d(TAG, "listenToSites(), firebaseUser = ${firebaseUser?.uid}")
        val userId = firebaseUser?.uid

        firestore.collection(SITES).whereEqualTo("users.${userId}", true)
            .addSnapshotListener(MetadataChanges.INCLUDE, EventListener { snapshots, e ->
                if (e != null) {
                    Log.w(TAG, "listenToSites(), listen error:", e)
                    return@EventListener
                }
                val allSites = ArrayList<SiteObject>()
                if (snapshots != null) {
                    for (document in snapshots) {
                        val site = document.toObject(SiteObject::class.java)
                        site.siteID = document.id
                        allSites.add(site)
                    }

                    for (docChange in snapshots.documentChanges) {
                        when (docChange) {
                            DocumentChange.Type.ADDED -> Log.d(TAG, "New site: ${docChange.document.data}")
                            DocumentChange.Type.MODIFIED -> Log.d(TAG, "Modified site: ${docChange.document.data}")
                            DocumentChange.Type.REMOVED -> Log.d(TAG, "Removed site: ${docChange.document.data}")
                        }
                    }

                    val source = if (snapshots.metadata.isFromCache){
                        "local cache"
                    }
                    else {
                        "server"
                    }
                    Log.d(TAG, "Sites data fetched from $source")
                }
                sitesMutableLiveData.value = allSites

            })

        return sitesMutableLiveData
    }```
</div>
</div>
</p>

<p>So I guess I could pass the Fragment context by passing it up the chain as an argument like this:</p>

```businessViewModel.listenToSites(context)
```

<p>Passing this through the VM, Repository to the snapshotListener as below: </p>

```addSnapshotListener(context, MetadataChanges.INCLUDE, EventListener....
```

But was unsure if this is the recommended way to do it or how best to capture the context in the Fragment?

Quick bonus question out of interest; does the snapshots.documentChanges code create additional listeners?  I'm just using while I debug, but thought it could..

答:
Your repository layer should never include a single line of Android-related code. Your ViewModel is a common ground for the Android and the repo layer code. You can make ViewModel lifecycle aware by implementing LifeCycleObserver interface.

```<code>class YourViewModel : LifeCycleObserver {

  @OnLifecycleEvent(Lifecycle.Event.ON_STOP) //Annotate it with any lifecycle event of your choice.
  fun aMethodThatRemovesObserver() {
      //Invoked on onStop()
  }

}
</code>```

In your activity:

```<code>onCreate() {
   lifecycle.addObserver(yourViewModel)
}
</code>```

No need to worry about removing ViewModel observer manually, it will be gone in uncleared state of your ViewModel. Just keep in mind that the repository layer should remain free of Android-related code. If you need a context, you can use AndroidViewModel (scoped to application). Sometimes it's not possible to seperate out context, in that case, I would just provide it with an applicationContext but not an Activity context.

Body:
I believe I need to detach Firestore listeners but I can't see how to do this without passing the context to my repository.  Below is one example:

Fragment

This method is called in onViewCreated and simply updates private var sitesList = ArrayList<SiteObject>() which is used to set list in my recyclerview:

    private fun setupObservers() {
        Log.d(TAG, "setupObservers()")
        businessViewModel.listenToSites().observe(viewLifecycleOwner, Observer { allSites ->
            if (sitesList != allSites && allSites != null) {
                sitesList.clear()
                sitesList.addAll(allSites)
                sitesAdapter.setList(sitesList)
                sitesAdapter.notifyDataSetChanged()
            }
        })
    }

ViewModel

    fun listenToSites(): LiveData<ArrayList<SiteObject>> {
        Log.d(TAG, "listenToSites()")
        return businessRepository.listenToSites()
    }

Repository

This is where the Firestore addSnapshotListener is created:

  fun listenToSites(): LiveData<ArrayList<SiteObject>> {

        Log.d(TAG, "listenToSites(), firebaseUser = ${firebaseUser?.uid}")
        val userId = firebaseUser?.uid

        firestore.collection(SITES).whereEqualTo("users.${userId}", true)
            .addSnapshotListener(MetadataChanges.INCLUDE, EventListener { snapshots, e ->
                if (e != null) {
                    Log.w(TAG, "listenToSites(), listen error:", e)
                    return@EventListener
                }
                val allSites = ArrayList<SiteObject>()
                if (snapshots != null) {
                    for (document in snapshots) {
                        val site = document.toObject(SiteObject::class.java)
                        site.siteID = document.id
                        allSites.add(site)
                    }

                    for (docChange in snapshots.documentChanges) {
                        when (docChange) {
                            DocumentChange.Type.ADDED -> Log.d(TAG, "New site: ${docChange.document.data}")
                            DocumentChange.Type.MODIFIED -> Log.d(TAG, "Modified site: ${docChange.document.data}")
                            DocumentChange.Type.REMOVED -> Log.d(TAG, "Removed site: ${docChange.document.data}")
                        }
                    }

                    val source = if (snapshots.metadata.isFromCache){
                        "local cache"
                    }
                    else {
                        "server"
                    }
                    Log.d(TAG, "Sites data fetched from $source")
                }
                sitesMutableLiveData.value = allSites

            })

        return sitesMutableLiveData
    }

So I guess I could pass the Fragment context by passing it up the chain as an argument like this:

businessViewModel.listenToSites(context)

Passing this through the VM, Repository to the snapshotListener as below:

addSnapshotListener(context, MetadataChanges.INCLUDE, EventListener....

But was unsure if this is the recommended way to do it or how best to capture the context in the Fragment?

Quick bonus question out of interest; does the snapshots.documentChanges code create additional listeners?  I'm just using while I debug, but thought it could..

Body:
Your repository layer should never include a single line of Android-related code. Your ViewModel is a common ground for the Android and the repo layer code. You can make ViewModel lifecycle aware by implementing LifeCycleObserver interface.

class YourViewModel : LifeCycleObserver {

  @OnLifecycleEvent(Lifecycle.Event.ON_STOP) //Annotate it with any lifecycle event of your choice.
  fun aMethodThatRemovesObserver() {
      //Invoked on onStop()
  }

}

In your activity:

onCreate() {
   lifecycle.addObserver(yourViewModel)
}

No need to worry about removing ViewModel observer manually, it will be gone in uncleared state of your ViewModel. Just keep in mind that the repository layer should remain free of Android-related code. If you need a context, you can use AndroidViewModel (scoped to application). Sometimes it's not possible to seperate out context, in that case, I would just provide it with an applicationContext but not an Activity context.


问:
Use Firestore to access images stored locally in a Flutter Project

I have Images of flags stored locally within my Flutter project assets/images folder i stored name of the images in firestore by opening a collection called "Languages" then set fields two fields

Languages [Collection] with auto id documents

 1. Language_Image -> china.png [Fields]

 2. Language_Name -> Chinese [Fields]

I want to generate a GridView of the flags (CircleAvatar) of every language and name of the language (Text)

I don't know how to go about the process to iterate through each document and get Language_Image and Language_Name data and build my GridView here is my code
`

```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'Choose_Books.dart';

class ChooseLanguage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade300,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text("Choose ChooseLanguage To Learn",
          style: TextStyle(fontSize: ScreenUtil().setHeight(34)),
        ),
        centerTitle: false,
      ),
      body: ChooseLanguageBody(),
    );
  }
}

class ChooseLanguageBody extends StatefulWidget {
  @override
  _ChooseLanguageBodyState createState() => _ChooseLanguageBodyState();
}

class _ChooseLanguageBodyState extends State<ChooseLanguageBody> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Firestore.instance.collection('Language').snapshots(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (!snapshot.hasData) {
          return Center(
              child: const Text('Loading events...'));
        }return GridView.count(
          // Create a grid with 3 columns.
          crossAxisCount: 2,
          children: List.generate(24, (index) {
            return Center(
              child: CupertinoButton(
                child: Column(
                  children: <Widget>[
                    CircleAvatar(
                      maxRadius: 70.0,
                      backgroundImage: AssetImage('images/launguages/launguage${snapshot.data.documents[index]['Language_Image']}.png'),
                    ),
                      Text(snapshot.data.documents[index]['Language_Image'], style: TextStyle(fontSize: ScreenUtil().setHeight(24), fontWeight: FontWeight.bold),
                    )
                  ],
                ),
                onPressed: () {Navigator.push(context, MaterialPageRoute(builder: (context) => ChooseBook()));},
              ),
            );
          }),
        );
      }
    );
  }
}
</code>```

`
Is it the correct procedure am following or i messed up completely?

答:
I think I found the Problem.
You missed adding the .data part.

Try this

```<code>snapshot.data.documents[index].data['Language_Image']
</code>```

Hope this helps.!
(FYI-> your gig is lead to this problem)

Body:
I have Images of flags stored locally within my Flutter project assets/images folder i stored name of the images in firestore by opening a collection called "Languages" then set fields two fields

Languages [Collection] with auto id documents

 1. Language_Image -> china.png [Fields]

 2. Language_Name -> Chinese [Fields]

I want to generate a GridView of the flags (CircleAvatar) of every language and name of the language (Text)

I don't know how to go about the process to iterate through each document and get Language_Image and Language_Name data and build my GridView here is my code
`

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'Choose_Books.dart';

class ChooseLanguage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade300,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text("Choose ChooseLanguage To Learn",
          style: TextStyle(fontSize: ScreenUtil().setHeight(34)),
        ),
        centerTitle: false,
      ),
      body: ChooseLanguageBody(),
    );
  }
}

class ChooseLanguageBody extends StatefulWidget {
  @override
  _ChooseLanguageBodyState createState() => _ChooseLanguageBodyState();
}

class _ChooseLanguageBodyState extends State<ChooseLanguageBody> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Firestore.instance.collection('Language').snapshots(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (!snapshot.hasData) {
          return Center(
              child: const Text('Loading events...'));
        }return GridView.count(
          // Create a grid with 3 columns.
          crossAxisCount: 2,
          children: List.generate(24, (index) {
            return Center(
              child: CupertinoButton(
                child: Column(
                  children: <Widget>[
                    CircleAvatar(
                      maxRadius: 70.0,
                      backgroundImage: AssetImage('images/launguages/launguage${snapshot.data.documents[index]['Language_Image']}.png'),
                    ),
                      Text(snapshot.data.documents[index]['Language_Image'], style: TextStyle(fontSize: ScreenUtil().setHeight(24), fontWeight: FontWeight.bold),
                    )
                  ],
                ),
                onPressed: () {Navigator.push(context, MaterialPageRoute(builder: (context) => ChooseBook()));},
              ),
            );
          }),
        );
      }
    );
  }
}

`
Is it the correct procedure am following or i messed up completely?

Body:
I think I found the Problem.
You missed adding the .data part.

Try this

snapshot.data.documents[index].data['Language_Image']

Hope this helps.!
(FYI-> your gig is lead to this problem)


问:
How to remove or disable the slash at the end of the URL?
I don't know exactly what is the problem, but I have done a lot of research about trailing slash in PHP.

My problem is that when I visit my site I always see trailing slash and it causes all the resources to fail to load.

How do I disable trailing slash that's being added in .htaccess.
Thanks!

答:
Here is what I found:

Remove the trailing slash in url with htacess
I think this is what you are looking for.

How to find it:

Just do a search for remove ending slash of url


问:
Visual Studio 2019 New Project does not include SSIS, whcih is installed
I can open, edit and deploy existing SSIS projects in Visual Studio 2019 (16.6.0), but cannot see SQL Server Integration Services or related items in the list of available templates when I add a new project. I do not know why this is, since SQL Server Integration Services Projects is installed, and I think that is all I need. I am seeking Advice on how to make SSIS appear in the list of templates.

Edit: I also searched the following terms with no luck: SSIS, SSDT, Business, SQL, Intelligence

Demonstration that SQL Server Integration Services Projects is installed:

Demonstration that I cannot see the related templates in the list when adding a new project:

答:
Please make sure that you have the latest extension installed, which can be downloaded from here:

https://marketplace.visualstudio.com/items?itemName=SSIS.SqlServerIntegrationServicesProjects

I checked and I am able to see the template searching for both integration and ssis:


问:
How to get different factors from a list of prime numbers?
I've been trying problem 47 (of project euler), the question given below:

The first two consecutive numbers to have two distinct prime factors are:

```<code>14 = 2 × 7
15 = 3 × 5
</code>```

The first three consecutive numbers to have three distinct prime factors are:

```<code>644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.
</code>```

Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?

Here is my approach:(you might need to (pip) install sympy)

```<code>import time
import sympy

start=time.time()
a=list(sympy.primerange(1,101))

b=[]

for i in range(646,100000):
    c=[]
    for j in a:
        if i%j==0:
            c.append(j)
            if len(c)==4:
                s=[str(o) for o in c]
                res=int("".join(s))
                b.append(res)
            else:
                pass
        else:
            pass

print(b[:4])
end=time.time()
print(end-start)
</code>```

How do i implement the logic that the factors should be different?
the answer which i get now(which is obviously wrong ) is :23511
the correct answer is:134043

sympy prime numbers basic functions: https://www.geeksforgeeks.org/prime-functions-python-sympy

Thanks !

答:
Ok, lets supose you have a function that gives you the prime factors

```<code>def find_4_diff(i):
    fact_i = find_factors(i)
    fact_i_plus_1 = find_factors(i+1)
    if all([f_i not in f_i_plus_1 for i in fact_i]):
        fact_i_plus_2 = find_factors(i+2)
        if all([f_i not in f_i_plus_2 for i in fact_i]) and  all([f_i not in f_i_plus_2 for i in fact_i_plus_1]):
            fact_i_plus_3 = find_factors(i+3)
            if all([f_i not in fact_i_plus_3 for i in fact_i]) and  all([f_i not in fact_i_plus_3 for i in fact_i_plus_1]) and all([f_i not in fact_i_plus_3 for i in fact_i_plus_2]):
                return i
    return

i = 646
myval = find_4_diff(i)
while  myval is None:
    i += 1
    myval = find_4_diff(i)
print(i)
</code>```

Now you can think of ways of optimizing:
e.g. you are always calculating at least the factorss of i+1 so dont need to do it again (ccan pass it as an argument), if factors i+1 are not valid vs factorsi+2 you can skip i+1 etc etc

All you need is  afunction to return factors of a number as numbers e.g. 2 to the 3 returned as 8 etc

Body:
I've been trying problem 47 (of project euler), the question given below:

The first two consecutive numbers to have two distinct prime factors are:

14 = 2 × 7
15 = 3 × 5

The first three consecutive numbers to have three distinct prime factors are:

644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.

Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?

Here is my approach:(you might need to (pip) install sympy)

import time
import sympy

start=time.time()
a=list(sympy.primerange(1,101))

b=[]

for i in range(646,100000):
    c=[]
    for j in a:
        if i%j==0:
            c.append(j)
            if len(c)==4:
                s=[str(o) for o in c]
                res=int("".join(s))
                b.append(res)
            else:
                pass
        else:
            pass

print(b[:4])
end=time.time()
print(end-start)

How do i implement the logic that the factors should be different?
the answer which i get now(which is obviously wrong ) is :23511
the correct answer is:134043

sympy prime numbers basic functions: https://www.geeksforgeeks.org/prime-functions-python-sympy

Thanks !

Body:
Ok, lets supose you have a function that gives you the prime factors

def find_4_diff(i):
    fact_i = find_factors(i)
    fact_i_plus_1 = find_factors(i+1)
    if all([f_i not in f_i_plus_1 for i in fact_i]):
        fact_i_plus_2 = find_factors(i+2)
        if all([f_i not in f_i_plus_2 for i in fact_i]) and  all([f_i not in f_i_plus_2 for i in fact_i_plus_1]):
            fact_i_plus_3 = find_factors(i+3)
            if all([f_i not in fact_i_plus_3 for i in fact_i]) and  all([f_i not in fact_i_plus_3 for i in fact_i_plus_1]) and all([f_i not in fact_i_plus_3 for i in fact_i_plus_2]):
                return i
    return

i = 646
myval = find_4_diff(i)
while  myval is None:
    i += 1
    myval = find_4_diff(i)
print(i)

Now you can think of ways of optimizing:
e.g. you are always calculating at least the factorss of i+1 so dont need to do it again (ccan pass it as an argument), if factors i+1 are not valid vs factorsi+2 you can skip i+1 etc etc

All you need is  afunction to return factors of a number as numbers e.g. 2 to the 3 returned as 8 etc


问:
Why are the "Enter name" output got skip over and when I type "close" in the output it keeps on looping
In the input below it keeps on looping when I type close in the output and after typing something in this part:

Before proceeding to our service, you need to fill in your details first as our record(type close to End):

The "Enter name: " part got skip

```<code>#include<stdio.h>
int main(void)
{
      char name[200],gender[20],op,option, close;
      int visit_ID, phone_number,day,month,year,service_needed, change_service, needed_days;
      float service_fee,payment_made, changes, change_service_fee;

      printf("\n\n*****Welcome to the Our Repair Centre*****");
      printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
      scanf("%s", &close);

      FILE * fpointer;
      fpointer = fopen("visitdetails.txt","w");

      while(close != "close")
      {
          printf("\n\nEnter information:\n");
          printf("\nEnter name: ");
          scanf("%[^\n]s", name);
          printf("\n\nEnter your ID number(Number only): ", visit_ID);
          scanf("%d",&visit_ID);
          printf("\n\nEnter today date dd mm yy(use space) :");
          scanf("%d", &day);
          scanf("%d", &month);
          scanf("%d", &year);
          printf("\n\nEnter your gender(Male/Female): ", gender);
          scanf("%s",gender);
          printf("\n\nEnter your phone number: ",phone_number);
          scanf("%d",&phone_number);
          printf("\n\nDone registered\n\n");

          printf("*****Welcome to the Computer centre*****\n");
          printf("-------------------------------------------------\n");
          printf("No |    Service Type                                    | Needed Days | Service Fee | \n");
          printf("                                                                      |Normal|Urgent|\n");
          printf("1. | Remove virus,Malware, or Spyware                   |      2      | 30RM | 50RM |\n");
          printf("2. | Troubleshot and fix computer running slow          |      2      | 40RM | 70RM |\n");
          printf("3. | Laptop Screen Replacement                          |      3      | 330RM| 430RM|\n");
          printf("4. | Laptop Keyboard Replacement                        |      2      | 160RM| 200RM|\n");
          printf("5. | Laptop Battery Replacement                         |      1      | 180RM| 210RM|\n");
          printf("6. | Operating System Format and Installation           |      2      | 50RM | 80RM |\n");
          printf("7. | Data Backup and Recovery                           |      2      | 100RM| 150RM|\n");
          printf("8. | Internet Connectivity issues                       |      1      | 50RM | 75RM |\n");

          printf("\nWhich service type do you need(1-8)? ", service_needed);
          scanf("%d",&service_needed);

          switch(service_needed)
          {
            case 1:
            printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 2:
            printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 3:
            printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 4:
            printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 5:
            printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 6:
            printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 7:
            printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 8:
            printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            default:
            printf("Invalid option");
          }
          printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
          fprintf(fpointer, "Visit ID = %d", visit_ID);
          fprintf(fpointer, "\nCustomer name = %s", name);
          fprintf(fpointer, "\nLast visit date : %d/%d/%d",day,month,year);
          fprintf(fpointer,"\nLast Service type repaired: %d", service_needed);
          fscanf(fpointer,"%d",service_needed);
          fprintf(fpointer, "\nLast Service fee: %.2f",service_fee);
          fprintf(fpointer,"\nLast payment: %.2f",payment_made);
          fclose(fpointer);
      }
}
</code>```

答:
As @Roberts told here that YOUR CODE HAS SEVERAL ISSUES. I wanna tell you that if you are going to launch this program at your repair center, you'll surely lose your customer. Your code is so much overwhelming, that it needs AVENGER LEVEL improvement. And I want to mention that please improve your UI, user-interaction with this program is worse. Although, I fixed your code at a tiny level, please check it out.
Please tell me that what you want to achieve throught this code, so that I can help you.

Do you want to store every visitor's information who visited your repair center on a text file?
  and What after a user inputs the service fee?

Please edit your question and tell us, what's your goal?

Code:

```<code>#include <stdio.h>
#include <stdlib.h> // Added this header to use exit() function.
#include <string.h> // Added this header to use string related functions.

int main(void)
{
      char name[200], gender[20], op, option, close [6];//modified close to close[6];
      int visit_ID, phone_number, day, month, year, service_needed, change_service, needed_days;
      float service_fee, payment_made, changes, change_service_fee;

      printf("\n\n*****Welcome to the Our Repair Center*****");
      printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ");
      gets(close);

      FILE * fpointer;
      if((fpointer = fopen("visitdetails.txt", "w")) == NULL) // Checking for any error while opening the file in write mode.
      {
          perror("Write");
          exit(1);
      }

      while (strcmp(close, "close"))
      {
          printf("\n\nEnter information:\n");
          printf("\nEnter name: ");
          gets(name); //scanf("%[^\n]s", name);
          printf("\n\nEnter your ID number(Number only): ");
          scanf("%d", &visit_ID);
          printf("\n\nEnter today date dd mm yy(use space) :");
          scanf("%d %d %d", &day, &month, &year);
          fflush(stdin);
          printf("\n\nEnter your gender(Male/Female): ");
          gets(gender); //scanf("%s",gender);
          printf("\n\nEnter your phone number: ");
          scanf("%d", &phone_number);
          printf("\n\nDone registered\n\n");

          printf("*****Welcome to the Computer center*****\n");
          printf("-------------------------------------------------\n");
          printf("No |    Service Type                                    | Needed Days | Service Fee | \n");
          printf("                                                                      |Normal|Urgent|\n");
          printf("1. | Remove virus,Malware, or Spyware                   |      2      | 30RM | 50RM |\n");
          printf("2. | Troubleshot and fix computer running slow          |      2      | 40RM | 70RM |\n");
          printf("3. | Laptop Screen Replacement                          |      3      | 330RM| 430RM|\n");
          printf("4. | Laptop Keyboard Replacement                        |      2      | 160RM| 200RM|\n");
          printf("5. | Laptop Battery Replacement                         |      1      | 180RM| 210RM|\n");
          printf("6. | Operating System Format and Installation           |      2      | 50RM | 80RM |\n");
          printf("7. | Data Backup and Recovery                           |      2      | 100RM| 150RM|\n");
          printf("8. | Internet Connectivity issues                       |      1      | 50RM | 75RM |\n");

          printf("\nWhich service type do you need(1-8)? ");
          scanf("%d", &service_needed);

          switch(service_needed)
          {
            case 1:
                printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 2:
                printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 3:
                printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 4:
                printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 5:
                printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ");
                scanf("%f",&service_fee);
                break;

            case 6:
            printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 7:
            printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 8:
            printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            default:
            printf("Invalid option");
          }
          fflush(stdin);
          system("cls");
          printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
          gets(close);
          fprintf(fpointer, "Visit ID = %d", visit_ID);
          fprintf(fpointer, "\nCustomer name = %s", name);
          fprintf(fpointer, "\nLast visit date : %d/%d/%d",day,month,year);
          fprintf(fpointer,"\nLast Service type repaired: %d", service_needed);
          fscanf(fpointer,"%d",service_needed);
          fprintf(fpointer, "\nLast Service fee: %.2f",service_fee);
          fprintf(fpointer,"\nLast payment: %.2f",payment_made);
          fclose(fpointer);
      }
}
</code>```

Body:
In the input below it keeps on looping when I type close in the output and after typing something in this part:

Before proceeding to our service, you need to fill in your details first as our record(type close to End):

The "Enter name: " part got skip

#include<stdio.h>
int main(void)
{
      char name[200],gender[20],op,option, close;
      int visit_ID, phone_number,day,month,year,service_needed, change_service, needed_days;
      float service_fee,payment_made, changes, change_service_fee;

      printf("\n\n*****Welcome to the Our Repair Centre*****");
      printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
      scanf("%s", &close);

      FILE * fpointer;
      fpointer = fopen("visitdetails.txt","w");

      while(close != "close")
      {
          printf("\n\nEnter information:\n");
          printf("\nEnter name: ");
          scanf("%[^\n]s", name);
          printf("\n\nEnter your ID number(Number only): ", visit_ID);
          scanf("%d",&visit_ID);
          printf("\n\nEnter today date dd mm yy(use space) :");
          scanf("%d", &day);
          scanf("%d", &month);
          scanf("%d", &year);
          printf("\n\nEnter your gender(Male/Female): ", gender);
          scanf("%s",gender);
          printf("\n\nEnter your phone number: ",phone_number);
          scanf("%d",&phone_number);
          printf("\n\nDone registered\n\n");

          printf("*****Welcome to the Computer centre*****\n");
          printf("-------------------------------------------------\n");
          printf("No |    Service Type                                    | Needed Days | Service Fee | \n");
          printf("                                                                      |Normal|Urgent|\n");
          printf("1. | Remove virus,Malware, or Spyware                   |      2      | 30RM | 50RM |\n");
          printf("2. | Troubleshot and fix computer running slow          |      2      | 40RM | 70RM |\n");
          printf("3. | Laptop Screen Replacement                          |      3      | 330RM| 430RM|\n");
          printf("4. | Laptop Keyboard Replacement                        |      2      | 160RM| 200RM|\n");
          printf("5. | Laptop Battery Replacement                         |      1      | 180RM| 210RM|\n");
          printf("6. | Operating System Format and Installation           |      2      | 50RM | 80RM |\n");
          printf("7. | Data Backup and Recovery                           |      2      | 100RM| 150RM|\n");
          printf("8. | Internet Connectivity issues                       |      1      | 50RM | 75RM |\n");

          printf("\nWhich service type do you need(1-8)? ", service_needed);
          scanf("%d",&service_needed);

          switch(service_needed)
          {
            case 1:
            printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 2:
            printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 3:
            printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 4:
            printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 5:
            printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 6:
            printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 7:
            printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 8:
            printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            default:
            printf("Invalid option");
          }
          printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
          fprintf(fpointer, "Visit ID = %d", visit_ID);
          fprintf(fpointer, "\nCustomer name = %s", name);
          fprintf(fpointer, "\nLast visit date : %d/%d/%d",day,month,year);
          fprintf(fpointer,"\nLast Service type repaired: %d", service_needed);
          fscanf(fpointer,"%d",service_needed);
          fprintf(fpointer, "\nLast Service fee: %.2f",service_fee);
          fprintf(fpointer,"\nLast payment: %.2f",payment_made);
          fclose(fpointer);
      }
}

Body:
As @Roberts told here that YOUR CODE HAS SEVERAL ISSUES. I wanna tell you that if you are going to launch this program at your repair center, you'll surely lose your customer. Your code is so much overwhelming, that it needs AVENGER LEVEL improvement. And I want to mention that please improve your UI, user-interaction with this program is worse. Although, I fixed your code at a tiny level, please check it out.
Please tell me that what you want to achieve throught this code, so that I can help you.

Do you want to store every visitor's information who visited your repair center on a text file?
  and What after a user inputs the service fee?

Please edit your question and tell us, what's your goal?

Code:

#include <stdio.h>
#include <stdlib.h> // Added this header to use exit() function.
#include <string.h> // Added this header to use string related functions.

int main(void)
{
      char name[200], gender[20], op, option, close [6];//modified close to close[6];
      int visit_ID, phone_number, day, month, year, service_needed, change_service, needed_days;
      float service_fee, payment_made, changes, change_service_fee;

      printf("\n\n*****Welcome to the Our Repair Center*****");
      printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ");
      gets(close);

      FILE * fpointer;
      if((fpointer = fopen("visitdetails.txt", "w")) == NULL) // Checking for any error while opening the file in write mode.
      {
          perror("Write");
          exit(1);
      }

      while (strcmp(close, "close"))
      {
          printf("\n\nEnter information:\n");
          printf("\nEnter name: ");
          gets(name); //scanf("%[^\n]s", name);
          printf("\n\nEnter your ID number(Number only): ");
          scanf("%d", &visit_ID);
          printf("\n\nEnter today date dd mm yy(use space) :");
          scanf("%d %d %d", &day, &month, &year);
          fflush(stdin);
          printf("\n\nEnter your gender(Male/Female): ");
          gets(gender); //scanf("%s",gender);
          printf("\n\nEnter your phone number: ");
          scanf("%d", &phone_number);
          printf("\n\nDone registered\n\n");

          printf("*****Welcome to the Computer center*****\n");
          printf("-------------------------------------------------\n");
          printf("No |    Service Type                                    | Needed Days | Service Fee | \n");
          printf("                                                                      |Normal|Urgent|\n");
          printf("1. | Remove virus,Malware, or Spyware                   |      2      | 30RM | 50RM |\n");
          printf("2. | Troubleshot and fix computer running slow          |      2      | 40RM | 70RM |\n");
          printf("3. | Laptop Screen Replacement                          |      3      | 330RM| 430RM|\n");
          printf("4. | Laptop Keyboard Replacement                        |      2      | 160RM| 200RM|\n");
          printf("5. | Laptop Battery Replacement                         |      1      | 180RM| 210RM|\n");
          printf("6. | Operating System Format and Installation           |      2      | 50RM | 80RM |\n");
          printf("7. | Data Backup and Recovery                           |      2      | 100RM| 150RM|\n");
          printf("8. | Internet Connectivity issues                       |      1      | 50RM | 75RM |\n");

          printf("\nWhich service type do you need(1-8)? ");
          scanf("%d", &service_needed);

          switch(service_needed)
          {
            case 1:
                printf("\nThe cost of it will be 30RM for Normal and 50RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 2:
                printf("\nThe cost of it will be 40RM for Normal and 70RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 3:
                printf("\nThe cost of it will be 330RM for Normal and 430RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 4:
                printf("\nThe cost of it will be 160RM for Normal and 200RM for Urgent(type the cost): ");
                scanf("%f", &service_fee);
                break;

            case 5:
                printf("\nThe cost of it will be 180RM for Normal and 210RM for Urgent(type the cost): ");
                scanf("%f",&service_fee);
                break;

            case 6:
            printf("\nThe cost of it will be 50RM for Normal and 80RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 7:
            printf("\nThe cost of it will be 100RM for Normal and 150RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            case 8:
            printf("\nThe cost of it will be 50RM for Normal and 75RM for Urgent(type the cost): ",service_fee);
            scanf("%f",&service_fee);
            break;

            default:
            printf("Invalid option");
          }
          fflush(stdin);
          system("cls");
          printf("\n\nBefore proceeding to our service, you need to fill in your details first as our record(type close to End): ", close);
          gets(close);
          fprintf(fpointer, "Visit ID = %d", visit_ID);
          fprintf(fpointer, "\nCustomer name = %s", name);
          fprintf(fpointer, "\nLast visit date : %d/%d/%d",day,month,year);
          fprintf(fpointer,"\nLast Service type repaired: %d", service_needed);
          fscanf(fpointer,"%d",service_needed);
          fprintf(fpointer, "\nLast Service fee: %.2f",service_fee);
          fprintf(fpointer,"\nLast payment: %.2f",payment_made);
          fclose(fpointer);
      }
}


问:
PHP largest whole number from sum of unsorted array
Can someone tell me the best way to find the largest whole number summed from an unsorted array?

e.g.

```<code>{0.1, 0.2, 0.9, 0.5}

Largest whole number possible is 1 (0.1 + 0.9).

{0.9, 0.2, 0.5, 0.3, 0.9}

Largest possible is 2 (0.9 + 0.9 + 0.2)
</code>```

thanks

Update

I've accepted the method that i used but some of the below will be programmatically correct

答:
The bulk of this code is for getting the permutations of an array. I'm sure it can be optimized, but this is calculating 3 arrays with lengths of 4, 5 and 6 in 45ms on a quad core single Xeon server. Jumps to about 220ms when I add a 4th array with 7 decimals and a whopping 2 seconds if I add a 5th with 8.

Basically, all this does is get all of the permutations of the array containing the floats, adds each one together key by key, and if a the sum is a whole number larger than the current whole number, updates that number.. Eventually returning the largest possible number.

```<code>$set1 = array(0.1, 0.2, 0.9, 0.5);
$set2 = array(0.9, 0.2, 0.5, 0.3, 0.9);
$set3 = array(0.9, 0.2, 0.5, 0.3, 0.9, 0.4);

function largestWholeNumber($decimals){
    echo "Calculating largest whole number for decimal set '"
    . implode(",", $decimals)
    . "'<br />";
    $perms = perms($decimals);
    $answer = 0;
    foreach($perms as $dec_array){
        $current_guess = 0;
        foreach($dec_array as $dec){
            $current_guess += $dec;
            if (!preg_match("/[^0-9]+/", $current_guess)){
                if ($answer < $current_guess){
                    $answer = $current_guess;
                    echo "New whole number found "
                    ."'$answer'"
                    ." with permutation: <br />";
                    print_r($dec_array);
                    echo "<br />";
                }
            }
        }
    }
    echo "Result: $answer<br /><br />";
    return $answer;
}

function factorial($int){
if($int < 2) {
       return 1;
}

for($f = 2; $int-1 > 1; $f *= $int--);

return $f;
}

function perms($arr) {
    $p = array();
    for ($i=0; $i < factorial(count($arr)); $i++) {
        $p[] = perm($arr, $i);
    }
    return $p;
}

function perm($arr, $nth = null) {

    if ($nth === null) {
        return perms($arr);
    }

    $result = array();
    $length = count($arr);

    while ($length--) {
        $f = factorial($length);
        $p = floor($nth / $f);
        $result[] = $arr[$p];
        array_delete_by_key($arr, $p);
        $nth -= $p * $f;
    }

    $result = array_merge($result,$arr);
    return $result;
}
function array_delete_by_key(&$array, $delete_key, $use_old_keys = FALSE) {

    unset($array[$delete_key]);

    if(!$use_old_keys) {
        $array = array_values($array);
    }

    return TRUE;
}

largestWholeNumber($set1); // 1
largestWholeNumber($set2); // 2
largestWholeNumber($set3); // 3
</code>```

Credit to the array permutation function goes to dirk dot avery a t gmail at http://php.net/manual/en/function.shuffle.php

Body:
Can someone tell me the best way to find the largest whole number summed from an unsorted array?

e.g.

{0.1, 0.2, 0.9, 0.5}

Largest whole number possible is 1 (0.1 + 0.9).

{0.9, 0.2, 0.5, 0.3, 0.9}

Largest possible is 2 (0.9 + 0.9 + 0.2)

thanks

Update

I've accepted the method that i used but some of the below will be programmatically correct

Body:
The bulk of this code is for getting the permutations of an array. I'm sure it can be optimized, but this is calculating 3 arrays with lengths of 4, 5 and 6 in 45ms on a quad core single Xeon server. Jumps to about 220ms when I add a 4th array with 7 decimals and a whopping 2 seconds if I add a 5th with 8.

Basically, all this does is get all of the permutations of the array containing the floats, adds each one together key by key, and if a the sum is a whole number larger than the current whole number, updates that number.. Eventually returning the largest possible number.

$set1 = array(0.1, 0.2, 0.9, 0.5);
$set2 = array(0.9, 0.2, 0.5, 0.3, 0.9);
$set3 = array(0.9, 0.2, 0.5, 0.3, 0.9, 0.4);

function largestWholeNumber($decimals){
    echo "Calculating largest whole number for decimal set '"
    . implode(",", $decimals)
    . "'<br />";
    $perms = perms($decimals);
    $answer = 0;
    foreach($perms as $dec_array){
        $current_guess = 0;
        foreach($dec_array as $dec){
            $current_guess += $dec;
            if (!preg_match("/[^0-9]+/", $current_guess)){
                if ($answer < $current_guess){
                    $answer = $current_guess;
                    echo "New whole number found "
                    ."'$answer'"
                    ." with permutation: <br />";
                    print_r($dec_array);
                    echo "<br />";
                }
            }
        }
    }
    echo "Result: $answer<br /><br />";
    return $answer;
}

function factorial($int){
if($int < 2) {
       return 1;
}

for($f = 2; $int-1 > 1; $f *= $int--);

return $f;
}

function perms($arr) {
    $p = array();
    for ($i=0; $i < factorial(count($arr)); $i++) {
        $p[] = perm($arr, $i);
    }
    return $p;
}

function perm($arr, $nth = null) {

    if ($nth === null) {
        return perms($arr);
    }

    $result = array();
    $length = count($arr);

    while ($length--) {
        $f = factorial($length);
        $p = floor($nth / $f);
        $result[] = $arr[$p];
        array_delete_by_key($arr, $p);
        $nth -= $p * $f;
    }

    $result = array_merge($result,$arr);
    return $result;
}
function array_delete_by_key(&$array, $delete_key, $use_old_keys = FALSE) {

    unset($array[$delete_key]);

    if(!$use_old_keys) {
        $array = array_values($array);
    }

    return TRUE;
}

largestWholeNumber($set1); // 1
largestWholeNumber($set2); // 2
largestWholeNumber($set3); // 3

Credit to the array permutation function goes to dirk dot avery a t gmail at http://php.net/manual/en/function.shuffle.php


问:
How to open other tab of same window using a pushbutton on qt?
I have a window. In this window I have a tab. In this tab I have two pages (page 1 & page 2). I have a pushButton on page 1. I one to go on page 2 using this pushButton. How to open other tab of same window using a pushbutton on qt?

mainwindow.h

```<code>  #ifndef MAINWINDOW_H
  #define MAINWINDOW_H

  #include <QMainWindow>

 QT_BEGIN_NAMESPACE
 namespace Ui { class MainWindow; }
 QT_END_NAMESPACE

 class MainWindow : public QMainWindow
 {
    Q_OBJECT

    public:
   MainWindow(QWidget *parent = nullptr);
   ~MainWindow();

   private slots:
   void on_pushButton_clicked();

   private:
       Ui::MainWindow *ui;
   };
   #endif // MAINWINDOW_H
</code>```

main.cpp

```<code>#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
</code>```

mainwindow.cpp

```<code>    #include "mainwindow.h"
    #include "ui_mainwindow.h"

    MainWindow::MainWindow(QWidget *parent)
     : QMainWindow(parent)
     , ui(new Ui::MainWindow)
     {
         ui->setupUi(this);
      }

    MainWindow::~MainWindow()
       {
      delete ui;
       }

    void MainWindow::on_pushButton_clicked()
    {

     }
</code>```

答:
From the comments: One solution is to add an automatic slot in your main window class that executes when the button is clicked. In this slot have it change the current index of the QTabWidget.

For example the following should cycle throw the tabs every time you click the button:

```<code>void MainWindow::on_pushButton_clicked()
{
   if (ui->tabWidget->count() > 1) {
      ui->tabWidget->setCurrentIndex( (ui->tabWidget->currentIndex()+1) % ui->tabWidget->count() );
   }
}
</code>```

Body:
I have a window. In this window I have a tab. In this tab I have two pages (page 1 & page 2). I have a pushButton on page 1. I one to go on page 2 using this pushButton. How to open other tab of same window using a pushbutton on qt?

mainwindow.h

  #ifndef MAINWINDOW_H
  #define MAINWINDOW_H

  #include <QMainWindow>

 QT_BEGIN_NAMESPACE
 namespace Ui { class MainWindow; }
 QT_END_NAMESPACE

 class MainWindow : public QMainWindow
 {
    Q_OBJECT

    public:
   MainWindow(QWidget *parent = nullptr);
   ~MainWindow();

   private slots:
   void on_pushButton_clicked();

   private:
       Ui::MainWindow *ui;
   };
   #endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}

mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"

    MainWindow::MainWindow(QWidget *parent)
     : QMainWindow(parent)
     , ui(new Ui::MainWindow)
     {
         ui->setupUi(this);
      }

    MainWindow::~MainWindow()
       {
      delete ui;
       }

    void MainWindow::on_pushButton_clicked()
    {

     }

Body:
From the comments: One solution is to add an automatic slot in your main window class that executes when the button is clicked. In this slot have it change the current index of the QTabWidget.

For example the following should cycle throw the tabs every time you click the button:

void MainWindow::on_pushButton_clicked()
{
   if (ui->tabWidget->count() > 1) {
      ui->tabWidget->setCurrentIndex( (ui->tabWidget->currentIndex()+1) % ui->tabWidget->count() );
   }
}


问:
Two ways of initializing a class?
I'm having some conceptual problems about classes and I want to make sure I'm doing things in the correct way.

I'm programming in Arduino and using some libraries for my project.
Libraries implement a class that I can instantiate in my project.

For example, the Library AdafruitMotorShieldV2 implements the class Adafruit_MotorShield and in the example they instantiate the class into a variable called AFMS. Everything clear so far

```<code>#include <Adafruit_MotorShield.h>

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
</code>```

However I came up with other libraries like, DeadReckoner, where in the example the class is instantiated as:

```<code>#include <DeadReckoner.h>
DeadReckoner deadReckoner(&leftTicks, &rightTicks, TICKS_PER_REV, RADIUS, LENGTH);
</code>```

Here I'm not sure what's happening.

DeadReckoner (capital letters) is the name of the class, and of course the name of the construtor. I assume deadReckoner (underscore) is a variable where DeadReckoner is instantiated, but why the call is different than in the Adafruit library?

In other words: are this two calls equivalent?

```<code>DeadReckoner deadReckoner(&leftTicks, &rightTicks, TICKS_PER_REV, RADIUS, LENGTH);
DeadReckoner deadReckoner = DeadReckoner(&leftTicks, &rightTicks, TICKS_PER_REV, RADIUS, LENGTH);
</code>```

This is the relevant code inside DeadReckoner.h if needed

```<code>class DeadReckoner {

public:
    DeadReckoner(volatile unsigned long *, volatile unsigned long *, unsigned long, unsigned long, int, double, double);
    // other methods of the class
}
</code>```

答:
first of all you should change the label from C to C++

the first is a DeadReckoner contractor that receive some references as parameters.

the second is DeadReckoner assignment operator that receive the result of DeadReckoner contractor.
look at the h file you will find signature similar to this one:
    DeadReckoner & DeadReckoner :: operator= ( const DeadReckoner & )

the result of the two lines will be the same but the first line make a DeadReckoner object.
while the second make a DeadReckoner object the uses the assignment operator to copy it to another DeadReckoner object.

Title: Two ways of initializing a class?

Body:
I'm having some conceptual problems about classes and I want to make sure I'm doing things in the correct way.

I'm programming in Arduino and using some libraries for my project.
Libraries implement a class that I can instantiate in my project.

For example, the Library AdafruitMotorShieldV2 implements the class Adafruit_MotorShield and in the example they instantiate the class into a variable called AFMS. Everything clear so far

#include <Adafruit_MotorShield.h>

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();

However I came up with other libraries like, DeadReckoner, where in the example the class is instantiated as:

#include <DeadReckoner.h>
DeadReckoner deadReckoner(&leftTicks, &rightTicks, TICKS_PER_REV, RADIUS, LENGTH);

Here I'm not sure what's happening.

DeadReckoner (capital letters) is the name of the class, and of course the name of the construtor. I assume deadReckoner (underscore) is a variable where DeadReckoner is instantiated, but why the call is different than in the Adafruit library?

In other words: are this two calls equivalent?

DeadReckoner deadReckoner(&leftTicks, &rightTicks, TICKS_PER_REV, RADIUS, LENGTH);
DeadReckoner deadReckoner = DeadReckoner(&leftTicks, &rightTicks, TICKS_PER_REV, RADIUS, LENGTH);

This is the relevant code inside DeadReckoner.h if needed

class DeadReckoner {

public:
    DeadReckoner(volatile unsigned long *, volatile unsigned long *, unsigned long, unsigned long, int, double, double);
    // other methods of the class
}


问:
Multi-party WebRTC without SFU
Based on this article, when implementing a WebRTC solution without a server, I assume it means SFU, the bottleneck is that only 4-6 participants can work.

Is there a solution that can work around this? For example, I just want to use Firebase as the only backend, mainly signaling and no SFU. What is the general implementation strategy to achieve at least 25-50 participants in WebRTC?

Update: This Github project shares a different statement.  It states "A full mesh is great for up to ~100 connections"

答:
Your real bottleneck with MESH is that each RTCPeerConnection will do its own video encoding in the browser.

The p2p concept naturally includes the requirement that both peers should adjust encoding quality based on network conditions. So, when your browser sends two streams to peers X (good download speed) and Y (bad download speed), the encodings for X and Y will be different - Y will receive lower framerate and bitrate than X.

Sounds reasonable, right? But, unfortunately, mandates separate video encoding for each peer connection.

If multiple peer connections could re-use the same video encoding, then MESH would be much more viable. But Google didn't provide that option in the browser. Simulcast requires SFU, so that's not your case.

So, how many concurrent video encodings can browser perform on a typical machine, for 720p 30 fps video? 5-6, not more. For 640x480 15 fps? Maybe 20 encodings.

In my opinion, the encoding layer and networking layer could be separated in WebRTC design, and even getUserMedia could be extended to getEncodedUserMedia, so that you could send the same encoded content to multiple peers.

So that's the real practical reason people use SFU for multi-peer WebRTC.

Title: Multi-party WebRTC without SFU


问:
difficulty accessing root in angular 9 app
```<code>ERROR in ./src/app/app.component.ts

Module not found: Error: Can't resolve './app.component.css' in '/home/tjay/produce-market/src/app'
ERROR in ./src/app/produce/create-produce/create-produce.component.ts
Module not found: Error: Can't resolve './create-produce.component.css' in '/home/tjay/produce-market/src/app/produce/create-produce'
ERROR in ./src/app/produce/produce-item/produce-item.component.ts
Module not found: Error: Can't resolve './produce-item.component.css' in '/home/tjay/produce-market/src/app/produce/produce-item'
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
ℹ ｢wdm｣: Failed to compile.
</code>```

答: The file name (or extension such as .css, .scss) might be different in the styleUrls specified in the @Component, and the actual file.


问:
adding values to pandas dataframe columns based on another dataframe
I have a dataframe that looks like this(df):

```<code>HOUSEID    PERSONID      WHY_TRP
20000017      1            1
20000017      1            1
20000017      1            1
20000017      2            1
20000017      2            3
20000231      1            11
20000231      1            11
20000231      2            11
20000521      1            11
20000521      2            11
20000521      2            3
</code>```

Each row describes a trip made by a person. I have another dataframe of the same kind in which each row describes a person(df_p):

```<code>    HOUSEID   PERSONID
    20000017      1
    20000017      2
    20000231      1
    20000231      2
    20000521      1
    20000521      2
</code>```

I want to make three new columns in the second dataframe to show the frequency of 1, 3 and 11 for each person. basically I already have a second dataframe (df_p) with other features so I shouldn't use groupby. for some reason the first and second dataframe don't have the same number of people. that's why I needed the strategy below. This is the code I tried but took hours to complete(1 million iterations):

```<code>df_p.insert(2, 'WHY_TRP_1', 0)
df_p.insert(3, 'WHY_TRP_2', 0)
df_p.insert(4, 'WHY_TRP_3', 0)

def trip_counter(i, r):
  if r[2] == 1:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] == r[1]), ['WHY_TRP_1']] += 1
  elif r[2] == 3:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_3']] += 1
  elif r[2] == 11:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_11']] += 1

for i ,r in df.iterrows():
  trip_counter(i ,r)
</code>```

output:

```<code>     HOUSEID   PERSONID   WHY_TRP_1     WHY_TRP_3      WHY_TRP_11
    20000017      1            3            0            0
    20000017      2            1            1            0
    20000231      1            0            0            2
    20000231      2            0            0            1
    20000521      1            0            0            1
    20000521      2            0            1            1
</code>```

Is there a faster way to do this?

thank you

答:
You can get a table of the counts by doing a groupby on the first dataframe and unstacking WHY_TRP, and then you can just merge it to the second:

```<code>counts = df.groupby(["HOUSEID", "PERSONID", "WHY_TRP"]).apply(len).unstack(fill_value=0)

counts.columns = counts.columns.map(lambda x: f"WHY_TRP_{x}")

counts

WHY_TRP            WHY_TRP_1  WHY_TRP_3  WHY_TRP_11
HOUSEID  PERSONID
20000017 1                 3          0           0
         2                 1          1           0
20000231 1                 0          0           2
         2                 0          0           1
20000521 1                 0          0           1
         2                 0          1           1

df2.merge(counts, how="left", left_on=["HOUSEID", "PERSONID"], right_index=True)

    HOUSEID  PERSONID  WHY_TRP_1  WHY_TRP_3  WHY_TRP_11
0  20000017         1          3          0           0
1  20000017         2          1          1           0
2  20000231         1          0          0           2
3  20000231         2          0          0           1
4  20000521         1          0          0           1
5  20000521         2          0          1           1
</code>```

Body:
I have a dataframe that looks like this(df):

HOUSEID    PERSONID      WHY_TRP
20000017      1            1
20000017      1            1
20000017      1            1
20000017      2            1
20000017      2            3
20000231      1            11
20000231      1            11
20000231      2            11
20000521      1            11
20000521      2            11
20000521      2            3

Each row describes a trip made by a person. I have another dataframe of the same kind in which each row describes a person(df_p):

    HOUSEID   PERSONID
    20000017      1
    20000017      2
    20000231      1
    20000231      2
    20000521      1
    20000521      2

I want to make three new columns in the second dataframe to show the frequency of 1, 3 and 11 for each person. basically I already have a second dataframe (df_p) with other features so I shouldn't use groupby. for some reason the first and second dataframe don't have the same number of people. that's why I needed the strategy below. This is the code I tried but took hours to complete(1 million iterations):

df_p.insert(2, 'WHY_TRP_1', 0)
df_p.insert(3, 'WHY_TRP_2', 0)
df_p.insert(4, 'WHY_TRP_3', 0)

def trip_counter(i, r):
  if r[2] == 1:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] == r[1]), ['WHY_TRP_1']] += 1
  elif r[2] == 3:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_3']] += 1
  elif r[2] == 11:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_11']] += 1

for i ,r in df.iterrows():
  trip_counter(i ,r)

output:

     HOUSEID   PERSONID   WHY_TRP_1     WHY_TRP_3      WHY_TRP_11
    20000017      1            3            0            0
    20000017      2            1            1            0
    20000231      1            0            0            2
    20000231      2            0            0            1
    20000521      1            0            0            1
    20000521      2            0            1            1

Is there a faster way to do this?

thank you

Body:
You can get a table of the counts by doing a groupby on the first dataframe and unstacking WHY_TRP, and then you can just merge it to the second:

counts = df.groupby(["HOUSEID", "PERSONID", "WHY_TRP"]).apply(len).unstack(fill_value=0)

counts.columns = counts.columns.map(lambda x: f"WHY_TRP_{x}")

counts

WHY_TRP            WHY_TRP_1  WHY_TRP_3  WHY_TRP_11
HOUSEID  PERSONID
20000017 1                 3          0           0
         2                 1          1           0
20000231 1                 0          0           2
         2                 0          0           1
20000521 1                 0          0           1
         2                 0          1           1

df2.merge(counts, how="left", left_on=["HOUSEID", "PERSONID"], right_index=True)

    HOUSEID  PERSONID  WHY_TRP_1  WHY_TRP_3  WHY_TRP_11
0  20000017         1          3          0           0
1  20000017         2          1          1           0
2  20000231         1          0          0           2
3  20000231         2          0          0           1
4  20000521         1          0          0           1
5  20000521         2          0          1           1


答:
Your res is a concatenation of factors, not the product of 4 numbers that divided i evenly. Instead of converting the elements of c to strings and concatenating them, try just b.append(prod(c)) where you have import prod as from sympy.core.mul import prod. Doing this, [2, 3, 5, 11] -> 330 instead of 23511.

BTW, len(sympy.factorint(n)) == 4 will tell you if n has 4 distinct factors.

Title: How to get different factors from a list of prime numbers?


问:
Chrome Devtools opens as a search rather then the dev tools themselves
Trying to run a Nativescript debug session and every time I enter

chrome-devtools://devtools/bundled/inspector.html?experiments=true&ws=localhost:41000

it opens a google search rather than the debug session.

https://www.google.com/search?q=chrome-devtools%3A%2F%2Fdevtools%2Fbundled%2Finspector.html%3Fexperiments%3Dtrue%26ws%3Dlocalhost%3A41000&oq=chrome-devtools%3A%2F%2Fdevtools%2Fbundled%2Finspector.html%3Fexperiments%3Dtrue%26ws%3Dlocalhost%3A41000&aqs=chrome.0.69i59j69i60j69i61.1074j0j7&sourceid=chrome&ie=UTF-8

Any ideas how to fix this please.

答:
The URL scheme was recently changed to just devtools:// in chromium. The NativeScript CLI v7 has been rereleased to correct this minor change.

Use devtools://devtools/bundled/inspector.html?experiments=true&ws=localhost:41000.


问:
Run JavaScript code on form submission
I want to run a JavaScript code upon a form being submitted preceding other default tasks that are carried out on form submit.

Can anyone suggest some approaches?

答:
For example, here is how you can execute some JS on Drupal's contact form before it is submitted using jQuery:</p>

```<code>$('form#contact-mail-page input#edit-submit').click(function() { alert('do some stuff'); });
</code>```

Title: Run JavaScript code on form submission

Body:
For example, here is how you can execute some JS on Drupal's contact form before it is submitted using jQuery:

$('form#contact-mail-page input#edit-submit').click(function() { alert('do some stuff'); });


问:
How do I mask a div to its parent dimensions?
I have a rounded rectangle as a background and would like to place another shape on top. The overlaying shape should mask the underlying shape, preferably without any weird coloring at the edges.

I tried to make this work by matching up the shape dimensions, but the border-radius property does not align perfectly with the darker background where the rounded edges overlap.

Imperfect coloring to the left:

body {
 margin: 100px;
}

#outer-shape {
 height: 25px;
 width: 100%;
 border-radius: 12.5px;
 background-color: #191932;
}

#inner-shape {
 height: 25px;
 width: 50%;
 border-radius: 12.5px 0 0 12.5px;
 background-color: #fa6400;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Overlapping Shapes</title>
 </head>
 <body>
  <div id="outer-shape">
   <div id="inner-shape"></div>
  </div>
 </body>
</html></code>```

Is there a way to have my child div remain a rectangle and then clip the parent div? The point is to hide anything that falls outside the boundaries of the underlying shape.

Is it possible to clip the rectangle to the parent shape?

body {
 margin: 100px;
}

#outer-shape {
 height: 25px;
 width: 100%;
 border-radius: 12.5px;
 background-color: #191932;
}

#inner-shape {
 height: 25px;
 width: 50%;
 opacity: 25%;
 background-color:rgba(250, 100, 0, 0.75);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Overlapping Shapes</title>
 </head>
 <body>
  <div id="outer-shape">
   <div id="inner-shape"></div>
  </div>
 </body>
</html></code>```

Edit:

Perhaps, I should have mentioned that the point is to convert the design into a progress bar; meaning that I will need to update the width of the overlaying shape (orange). It should be possible to set a width from 0% up to 100%, while still displaying a distinct separation between the two shapes (no gradient transition).

Besides this, I seek to answer my original question: Is it possible to clip the rectangle to the parent shape?

If you look closely, shape 1) and shape 2) are slightly different at the edges. The first one has an underlying darker background color, which can be seen by looking at the somewhat rougher edge. The second image is simply the same shape, without any layers beneath. This is really nitpicking, but I cannot avoid seeing the imperfect edge in the first example where the rounding is applied.

Is there a way to keep the underlying darker color and have the smooth rounded edge as seen in the second example?

答:
Use multiple background for this where you can easily control the size using background-size

.outer-shape {
  height: 25px;
  margin: 10px;
  border-radius: 12.5px;
  background:
    linear-gradient(#fa6400, #fa6400) left/50% 100% no-repeat,
    #191932;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer-shape"></div>
<div class="outer-shape" style="background-size:20% 100%"></div>
<div class="outer-shape" style="background-size:60% 100%"></div></code>```

Body:
I have a rounded rectangle as a background and would like to place another shape on top. The overlaying shape should mask the underlying shape, preferably without any weird coloring at the edges.

I tried to make this work by matching up the shape dimensions, but the border-radius property does not align perfectly with the darker background where the rounded edges overlap.

Imperfect coloring to the left:

body {
 margin: 100px;
}

#outer-shape {
 height: 25px;
 width: 100%;
 border-radius: 12.5px;
 background-color: #191932;
}

#inner-shape {
 height: 25px;
 width: 50%;
 border-radius: 12.5px 0 0 12.5px;
 background-color: #fa6400;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Overlapping Shapes</title>

Is there a way to have my child div remain a rectangle and then clip the parent div? The point is to hide anything that falls outside the boundaries of the underlying shape.

Is it possible to clip the rectangle to the parent shape?

body {
 margin: 100px;
}

#outer-shape {
 height: 25px;
 width: 100%;
 border-radius: 12.5px;
 background-color: #191932;
}

#inner-shape {
 height: 25px;
 width: 50%;
 opacity: 25%;
 background-color:rgba(250, 100, 0, 0.75);
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Overlapping Shapes</title>

Edit:

Perhaps, I should have mentioned that the point is to convert the design into a progress bar; meaning that I will need to update the width of the overlaying shape (orange). It should be possible to set a width from 0% up to 100%, while still displaying a distinct separation between the two shapes (no gradient transition).

Besides this, I seek to answer my original question: Is it possible to clip the rectangle to the parent shape?

If you look closely, shape 1) and shape 2) are slightly different at the edges. The first one has an underlying darker background color, which can be seen by looking at the somewhat rougher edge. The second image is simply the same shape, without any layers beneath. This is really nitpicking, but I cannot avoid seeing the imperfect edge in the first example where the rounding is applied.

Is there a way to keep the underlying darker color and have the smooth rounded edge as seen in the second example?

Body:
Use multiple background for this where you can easily control the size using background-size

.outer-shape {
  height: 25px;
  margin: 10px;
  border-radius: 12.5px;
  background:
    linear-gradient(#fa6400, #fa6400) left/50% 100% no-repeat,
    #191932;
}

<div class="outer-shape"></div>
<div class="outer-shape" style="background-size:20% 100%"></div>
<div class="outer-shape" style="background-size:60% 100%"></div>


问:
Can't run a java file using javac
I've got the same problem as the user who posted this question. I am trying to run a Java file on a Windows machine using Command Prompt, but I'm having no success using any of the information I've gleaned from the linked question, nor from WikiHow, nor from this user on another site with the same problem.

Here are the steps I've taken.

I've created a Java file using Notepad, called HelloWorld.java, and saved it in a folder called "Java". The file directory is C:\Users\[myname]\Google Drive\Java. The code in the file is a simple Hello World as below:

```<code>class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
</code>```

I've downloaded Java version 8, and the latest version of the Java JDK (14.0.1) from the website. I previously had the JDK 12.x.x installed, so I uninstalled that.

I've opened System Properties > Advanced > Environment Variables, gone to the "Path" variable in "System variables", clicked "Edit" and added a new environment variable, which was the path to the JDK bin: C:\Program Files\Java\jdk-14.0.1\bin. I then clicked "Move Up" until this variable was at the top.

After clicking OK and closing this window, I've opened Command Prompt, typed set path=C:\Users\[myname]\Google Drive\Java in order to (I imagine) set the path to where my HelloWorld.java file is. I've typed in path to confirm that this has worked.

I've typed in Command Prompt javac HelloWorld.java. When I hit Enter, I get the output:

```<code>'javac' is not recognized as an internal or external command,
operable program or batch file.
</code>```

I'm honestly not sure what steps are left to take. Is there a simple fix to get this file to run?

答:
Steps

Setup the environment variables properly. In the Path System variable, you should add the path to bin directory. Something like C:\Program Files\Java\jdk-11.0.5\bin and then, you need to define a new system variable with name JAVA_HOME and point it to the java installation directory, not the bin directory. Something like C:\Program Files\Java\jdk-11.0.5

You need NOT use the Set command, as of now environment variables are set. Open up a new powershell or command prompt and type java -version. If this prints the java version, then you are good to go with the next steps.

Go to your directory where your java class resides. Open up a powershell window there, with shift + right click and open Powershell window here option. Then type javac HelloWorld.java

To run programme, java HelloWorld

Title: Can't run a java file using javac

Body:
I've got the same problem as the user who posted this question. I am trying to run a Java file on a Windows machine using Command Prompt, but I'm having no success using any of the information I've gleaned from the linked question, nor from WikiHow, nor from this user on another site with the same problem.

Here are the steps I've taken.

I've created a Java file using Notepad, called HelloWorld.java, and saved it in a folder called "Java". The file directory is C:\Users\[myname]\Google Drive\Java. The code in the file is a simple Hello World as below:

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

I've downloaded Java version 8, and the latest version of the Java JDK (14.0.1) from the website. I previously had the JDK 12.x.x installed, so I uninstalled that.

I've opened System Properties > Advanced > Environment Variables, gone to the "Path" variable in "System variables", clicked "Edit" and added a new environment variable, which was the path to the JDK bin: C:\Program Files\Java\jdk-14.0.1\bin. I then clicked "Move Up" until this variable was at the top.

After clicking OK and closing this window, I've opened Command Prompt, typed set path=C:\Users\[myname]\Google Drive\Java in order to (I imagine) set the path to where my HelloWorld.java file is. I've typed in path to confirm that this has worked.

I've typed in Command Prompt javac HelloWorld.java. When I hit Enter, I get the output:

'javac' is not recognized as an internal or external command,
operable program or batch file.

I'm honestly not sure what steps are left to take. Is there a simple fix to get this file to run?


问:
Rails Postgres - Jsonb Column Query
I have a Bundle tabel with jsonb column named 'available_quantity'. which will have sample values

[{ "denomination": "100", "quantity": "20"}, { "denomination": "1000", "quantity": "19"}]

Now, I want to query all records with quantity less than 50.

I tried this query,

Bundle.where("(available_quantity->>'quantity')::numeric < 50")

But this return empty Relation.

How can I do that?

SCHEMA

```<code>                                            Table "offer_service.bundles"
    Column         |            Type             | Collation |
Nullable |                        Default
-----------------------+-----------------------------+-----------+----
------+--------------------------------------------------------
id                    | bigint                      |           | not
null | nextval('offer_service.bundles_id_seq'::regclass)
project_id            | bigint                      |           |
|
 item_type             | character varying           |           |
|
item_id               | bigint                      |           |
|
status                | integer                     |           | not
 null | 0
 created_at            | timestamp without time zone |           | not
null |
 updated_at            | timestamp without time zone |           | not
null |
denomination_quantity | jsonb                       |           |
|
 deleted_at            | timestamp without time zone |           |
|
 available_quantity    | jsonb                       |           |
|
</code>```

Example Data:

```<code>id: 2586, project_id: 3, item_type: "GiftCard", item_id: 659, status:
"activated", created_at: "2020-05-18 09:38:54", updated_at: "2020-05-
28 13:25:29", denomination_quantity: {"100"=>200, "1000"=>200},
deleted_at: nil, available_quantity: [{"quantity"=>16,
"denomination"=>"100"}, {"quantity"=>20, "denomination"=>1000}]
</code>```

答:
Hope we have to use sub query here.

```<code> Bundle.select("*").from(Bundle.select("*, jsonb_array_elements(available_quantity) as aq")).where("(aq ->> 'quantity')::numeric <= 50").distinct
</code>```

Suggestions on refactoring the above query is welcomed!

Title: Rails Postgres - Jsonb Column Query

Body:
I have a Bundle tabel with jsonb column named 'available_quantity'. which will have sample values

[{ "denomination": "100", "quantity": "20"}, { "denomination": "1000", "quantity": "19"}]

Now, I want to query all records with quantity less than 50.

I tried this query,

Bundle.where("(available_quantity->>'quantity')::numeric < 50")

But this return empty Relation.

How can I do that?

SCHEMA

                                            Table "offer_service.bundles"
    Column         |            Type             | Collation |
Nullable |                        Default
-----------------------+-----------------------------+-----------+----
------+--------------------------------------------------------
id                    | bigint                      |           | not
null | nextval('offer_service.bundles_id_seq'::regclass)
project_id            | bigint                      |           |
|
 item_type             | character varying           |           |
|
item_id               | bigint                      |           |
|
status                | integer                     |           | not
 null | 0
 created_at            | timestamp without time zone |           | not
null |
 updated_at            | timestamp without time zone |           | not
null |
denomination_quantity | jsonb                       |           |
|
 deleted_at            | timestamp without time zone |           |
|
 available_quantity    | jsonb                       |           |
|

Example Data:

id: 2586, project_id: 3, item_type: "GiftCard", item_id: 659, status:
"activated", created_at: "2020-05-18 09:38:54", updated_at: "2020-05-
28 13:25:29", denomination_quantity: {"100"=>200, "1000"=>200},
deleted_at: nil, available_quantity: [{"quantity"=>16,
"denomination"=>"100"}, {"quantity"=>20, "denomination"=>1000}]

Body:
Hope we have to use sub query here.

 Bundle.select("*").from(Bundle.select("*, jsonb_array_elements(available_quantity) as aq")).where("(aq ->> 'quantity')::numeric <= 50").distinct

Suggestions on refactoring the above query is welcomed!