问:
A failure occurred while executing com.android.build.gradle.internal.tasks
I am getting this error while I am building APK.

```<code>Cause 1: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
    at org.gradle.workers.internal.DefaultWorkerExecutor$WorkerExecution.waitForCompletion(DefaultWorkerExecutor.java:285)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:115)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForCompletion(DefaultAsyncWorkTracker.java:87)
    at org.gradle.workers.internal.DefaultWorkerExecutor.await(DefaultWorkerExecutor.java:150)
    at com.android.build.gradle.internal.tasks.Workers$WorkerExecutorAdapter.await(Workers.kt:282)
    at com.android.ide.common.resources.MergeWriter.end(MergeWriter.java:48)
    at com.android.ide.common.resources.MergedResourceWriter.end(MergedResourceWriter.java:242)
    at com.android.ide.common.resources.DataMerger.mergeData(DataMerger.java:292)
    at com.android.ide.common.resources.ResourceMerger.mergeData(ResourceMerger.java:384)
    at com.android.build.gradle.tasks.MergeResources.lambda$doFullTaskAction$1(MergeResources.java:261)
    at com.android.build.gradle.internal.tasks.Blocks.recordSpan(Blocks.java:58)
</code>```

Tried to invalidate cache and restart android studio.Rebuild project but none of them works for me.

答:
Working on android studio: 3.6.3 and gradle version:

```<code>classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"
</code>```

Adding this line in

gradle.properties file

```<code>org.gradle.jvmargs=-Xmx512m
</code>```

Body:
I am getting this error while I am building APK.

Cause 1: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
    at org.gradle.workers.internal.DefaultWorkerExecutor$WorkerExecution.waitForCompletion(DefaultWorkerExecutor.java:285)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:115)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForCompletion(DefaultAsyncWorkTracker.java:87)
    at org.gradle.workers.internal.DefaultWorkerExecutor.await(DefaultWorkerExecutor.java:150)
    at com.android.build.gradle.internal.tasks.Workers$WorkerExecutorAdapter.await(Workers.kt:282)
    at com.android.ide.common.resources.MergeWriter.end(MergeWriter.java:48)
    at com.android.ide.common.resources.MergedResourceWriter.end(MergedResourceWriter.java:242)
    at com.android.ide.common.resources.DataMerger.mergeData(DataMerger.java:292)
    at com.android.ide.common.resources.ResourceMerger.mergeData(ResourceMerger.java:384)
    at com.android.build.gradle.tasks.MergeResources.lambda$doFullTaskAction$1(MergeResources.java:261)
    at com.android.build.gradle.internal.tasks.Blocks.recordSpan(Blocks.java:58)

Tried to invalidate cache and restart android studio.Rebuild project but none of them works for me.

Body:
Working on android studio: 3.6.3 and gradle version:

classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"

Adding this line in

gradle.properties file

org.gradle.jvmargs=-Xmx512m


来源: stackexchange

问:
Vue.js: Search through nested arrays
I have been working on a FAQ page that has categories and once you have selected a category, it shows questions users have asked. You can then select a question to display the answer. There are 7 categories and each has an array named "questionList" that has various amounts of questions. I am creating a search bar that will filter through ALL questions in each category and display the question and answer that matches the search. Right now the filtered list only displays the first categories questions....

Here is an example of how my data is setup

```<code>categoryList : [
           {
             category: 'Category Title',
             questionList: [
                      {
                         question: 'Question',
                         answer: '<p>copy goes here</p>'
                       }, ...
                     ]
            },
            {
               category: 'Next Title',
               questionList: [
                       {
                         question: 'Question',
                         answer: '<p>copy goes here</p>'
                       },
                     ]
             }, ...
</code>```

I was looking at another stackoverflow solution and I really could not figure out how to have it function with my multiple nested arrays. Here is the html:

```<code><div class="filtered" v-for="qa in filteredList">
     <div class="filter-container">
          <h3>{{ qa.question }}</h3>
          <div v-html="qa.answer"></div>
     </div>
</div>
</code>```

and my computed function:

```<code>filteredList() {
      for (i = 0; i < this.categoryList.length; i++) {

            var list =  this.categoryList[i];

            for (j = 0; j < list.questionList.length; j++ ) {

                    return list.questionList.filter(qa => {
                                 return qa.question.toLowerCase().includes(this.search.toLowerCase());
                        })
                   }
              }
          }
</code>```

I'm not sure if I am even close to the correct solution or waaaay off here... please help!

答:
Right now the filtered list only displays the first categories questions....

That's because you return the filtered array of first category in the for-loop.

Note that computed properties are functions. They are done when they return something.

What you should do is to iterate all QAs and create a new array whose elements have question text including keywords.

JSFiddle DEMO

Additional Info: Array.prototype.forEach() is a kind of functional way of for-loop without break (cf. Array.prototype.some()).

ContentLicense: CC BY-SA 4.0

Title: Vue.js: Search through nested arrays

Body:
I have been working on a FAQ page that has categories and once you have selected a category, it shows questions users have asked. You can then select a question to display the answer. There are 7 categories and each has an array named "questionList" that has various amounts of questions. I am creating a search bar that will filter through ALL questions in each category and display the question and answer that matches the search. Right now the filtered list only displays the first categories questions....

Here is an example of how my data is setup

categoryList : [
           {
             category: 'Category Title',
             questionList: [
                      {
                         question: 'Question',
                         answer: '
copy goes here
'
                       }, ...
                     ]
            },
            {
               category: 'Next Title',
               questionList: [
                       {
                         question: 'Question',
                         answer: '
copy goes here
'
                       },
                     ]
             }, ...

I was looking at another stackoverflow solution and I really could not figure out how to have it function with my multiple nested arrays. Here is the html:

{{ qa.question }}

and my computed function:

filteredList() {
      for (i = 0; i < this.categoryList.length; i++) {

            var list =  this.categoryList[i];

            for (j = 0; j < list.questionList.length; j++ ) {

                    return list.questionList.filter(qa => {
                                 return qa.question.toLowerCase().includes(this.search.toLowerCase());
                        })
                   }
              }
          }

I'm not sure if I am even close to the correct solution or waaaay off here... please help!


问:
How to get 0 as a Count-output?
```<code>SELECT Country.NAME, COUNT(City.NAME) as Number_of_cities
FROM City
JOIN Country ON City.COUNTRY = Country.CODE
WHERE City.LONGITUDE IS NULL AND City.LATITUDE IS NULL
GROUP BY Country.NAME, City.COUNTRY;
</code>```

As the code is now, countries which only got cities with a longtidude and latitade value arent shown. How do i have to change the code, so that countries where all cities have longtitude and latidude values show 0 as coun?

答:
You want a left join, with the filtering in the on clauses:

```<code>SELECT co.NAME, COUNT(ci.country) as Number_of_cities
FROM country co left join
     City ci
     ON ci.COUNTRY = co.CODE and
        ci.LONGITUDE IS NULL and
        ci.LATITUDE IS NULL
GROUP BY co.NAME;
</code>```

Title: How to get 0 as a Count-output?

Body:
SELECT Country.NAME, COUNT(City.NAME) as Number_of_cities
FROM City
JOIN Country ON City.COUNTRY = Country.CODE
WHERE City.LONGITUDE IS NULL AND City.LATITUDE IS NULL
GROUP BY Country.NAME, City.COUNTRY;

As the code is now, countries which only got cities with a longtidude and latitade value arent shown. How do i have to change the code, so that countries where all cities have longtitude and latidude values show 0 as coun?

Body:
You want a left join, with the filtering in the on clauses:

SELECT co.NAME, COUNT(ci.country) as Number_of_cities
FROM country co left join
     City ci
     ON ci.COUNTRY = co.CODE and
        ci.LONGITUDE IS NULL and
        ci.LATITUDE IS NULL
GROUP BY co.NAME;


问:
NHibernate mapping not adding ON DELETE CASCADE option to foreign key reference
Here's my NHibernate mapping.

```<code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="HelloNHibernate" namespace="HelloNHibernate">
  <class name="Showing" table="showing">
    <id name="Id" column="showing_id">
      <generator class="identity"/>
    </id>
    <many-to-one class="Theater" name="Theater" column="theater_id" foreign-key="fk_showing_theater_theater_id" cascade="delete" lazy="false" fetch="join"/>
    <many-to-one class="Movie" name="Movie" column="movie_id" foreign-key="fk_showing_movie_movie_id" cascade="delete" lazy="false" fetch="join" />
  </class>
</hibernate-mapping>
</code>```

Here's the SQL (PostgreSQL) generated by the SchemaExport tool:

```<code>CREATE TABLE showing
(
  showing_id serial NOT NULL,
  theater_id integer,
  movie_id integer,
  CONSTRAINT showing_pkey PRIMARY KEY (showing_id),
  CONSTRAINT fk_showing_movie_movie_id FOREIGN KEY (movie_id)
      REFERENCES movie (movie_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_showing_theater_theater_id FOREIGN KEY (theater_id)
      REFERENCES theater (theater_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
</code>```

What am I doing wrong? Thanks!

答:
To supplement the accepted answer, here's how you'd do it with Fluent NHibernate:</p>

```<code>public class MovieMap : ClassMap<Movie>
{
     public MovieMap()
     {
         ...
         HasMany(c => c.Showings)
              .Inverse()
              .KeyColumn("Foo")
              .Cascade.All()
              .ForeignKeyCascadeOnDelete() // here's the magic
              .ForeignKeyConstraintName("FK_Movie_Showing"); // this is optional - name is autogenerated otherwise
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here's my NHibernate mapping.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="HelloNHibernate" namespace="HelloNHibernate">
  <class name="Showing" table="showing">
    <id name="Id" column="showing_id">
      <generator class="identity"/>
    </id>
    <many-to-one class="Theater" name="Theater" column="theater_id" foreign-key="fk_showing_theater_theater_id" cascade="delete" lazy="false" fetch="join"/>
    <many-to-one class="Movie" name="Movie" column="movie_id" foreign-key="fk_showing_movie_movie_id" cascade="delete" lazy="false" fetch="join" />
  </class>
</hibernate-mapping>

Here's the SQL (PostgreSQL) generated by the SchemaExport tool:

CREATE TABLE showing
(
  showing_id serial NOT NULL,
  theater_id integer,
  movie_id integer,
  CONSTRAINT showing_pkey PRIMARY KEY (showing_id),
  CONSTRAINT fk_showing_movie_movie_id FOREIGN KEY (movie_id)
      REFERENCES movie (movie_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_showing_theater_theater_id FOREIGN KEY (theater_id)
      REFERENCES theater (theater_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

What am I doing wrong? Thanks!

Body:
To supplement the accepted answer, here's how you'd do it with Fluent NHibernate:

public class MovieMap : ClassMap<Movie>
{
     public MovieMap()
     {
         ...
         HasMany(c => c.Showings)
              .Inverse()
              .KeyColumn("Foo")
              .Cascade.All()
              .ForeignKeyCascadeOnDelete() // here's the magic
              .ForeignKeyConstraintName("FK_Movie_Showing"); // this is optional - name is autogenerated otherwise

ContentLicense: CC BY-SA 3.0


问:
Is the class object returned by getClass() method an instance of the class?
I understand how the object returned by the method contains  getClass() metadata of the object it is called on, but is the class object being returned an instance of the class of the object it is called upon? This method can be called on any object in Java, so any instance or array. Does it differ for instances and arrays since arrays are in a way special objects?</p>

答: let's assume a class Dog. if you write new Dog().getClass() or just Dog.class you'll get an instance of Class<Dog>. More in the official docs: https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html


问:
How to generate url changing wrt date?
I need to extract, unzip & read data from this url (https://www1.ukp.com/content/historical/2020/MAY/cm29MAY2020bhav.csv.zip

) on every working day. I manually edit the url  everyday . Is there any way to automate it in python

```<code>!wget https://www.ukp.com/content/historical/2020/MAY/cm29MAY2020bhav.csv.zip

!unzip cm29MAY2020bhav.csv.zip

cm3a = pd.read_csv('cm29MAY2020bhav.csv.zip',engine='python')
</code>```

答:
Use date.strftime to generate the URL.

```<code>>>> from datetime import date
>>> date.today().strftime("https://www1.ukp.com/content/historical/%Y/%B/cm%d%B%Ybhav.csv.zip")
'https://www1.ukp.com/content/historical/2020/June/cm01June2020bhav.csv.zip'
</code>```

If case sensitivity matters, you'll have to break it up into a few pieces. For example:

```<code>>>> year, month, day = date.today().strftime("%Y-%B-%d").split("-")
>>> month = month.upper()
>>> f'https://www1.ukp.com/content/historical/{year}/{month}/cm{day}{month}{year}bhav.csv.zip'
'https://www1.ukp.com/content/historical/2020/JUNE/cm01JUNE2020bhav.csv.zip'
</code>```

Title: How to generate url changing wrt date?

Body:
I need to extract, unzip & read data from this url (https://www1.ukp.com/content/historical/2020/MAY/cm29MAY2020bhav.csv.zip

) on every working day. I manually edit the url  everyday . Is there any way to automate it in python

!wget https://www.ukp.com/content/historical/2020/MAY/cm29MAY2020bhav.csv.zip

!unzip cm29MAY2020bhav.csv.zip

cm3a = pd.read_csv('cm29MAY2020bhav.csv.zip',engine='python')

Body:
Use date.strftime to generate the URL.

>>> from datetime import date
>>> date.today().strftime("https://www1.ukp.com/content/historical/%Y/%B/cm%d%B%Ybhav.csv.zip")
'https://www1.ukp.com/content/historical/2020/June/cm01June2020bhav.csv.zip'

If case sensitivity matters, you'll have to break it up into a few pieces. For example:

>>> year, month, day = date.today().strftime("%Y-%B-%d").split("-")
>>> month = month.upper()
>>> f'https://www1.ukp.com/content/historical/{year}/{month}/cm{day}{month}{year}bhav.csv.zip'
'https://www1.ukp.com/content/historical/2020/JUNE/cm01JUNE2020bhav.csv.zip'


问:
Flutter: get default context? or load assets without context?
I'm trying to load a json file in a class extending SearchDelegate to search through its content.

I have a method to load this file:

```<code>Future<void> loadCountryData() async {
    try {
      String data = await DefaultAssetBundle
          .of(context)
          .loadString("assets/data/countries.json");
      _countries = json.decode(data);
    } catch (e) {
      print(e);
    }
}
</code>```

Unfortunately this requires a Buildcontext (context) that seems only to be available in the SearchDelegate build methods (like buildActions, buildLeadings, etc), but no outside like for example in the constructor.

https://docs.flutter.io/flutter/material/SearchDelegate-class.html

As the @override xy build methods in SearchDelegate are called with every change in the search field, I would load my file over and over again, which is of course not ideal.
I want to load my file once at the beginning only.

Is there a way to get some sort of get default context that I could use for example in the constructor of SearchDelegate. Like in android (if I remmeber correctly)?

Or can I load an assets file without .of(context)?

答:
There is an option to get builtin AssetBundle without specifying a reference to BuildContext. Here is an example of how it could be done:

```<code>import 'package:flutter/services.dart'; // is required

Future<void> loadCountryData() async {
    try {
        // we can access builtin asset bundle with rootBundle
        final data = await rootBundle.loadString("assets/data/countries.json");
        _countries = json.decode(data);
    } catch (e) {
      print(e);
    }
}
</code>```

Body:
I'm trying to load a json file in a class extending SearchDelegate to search through its content.

I have a method to load this file:

Future<void> loadCountryData() async {
    try {
      String data = await DefaultAssetBundle
          .of(context)
          .loadString("assets/data/countries.json");
      _countries = json.decode(data);
    } catch (e) {
      print(e);
    }
}

Unfortunately this requires a Buildcontext (context) that seems only to be available in the SearchDelegate build methods (like buildActions, buildLeadings, etc), but no outside like for example in the constructor.

https://docs.flutter.io/flutter/material/SearchDelegate-class.html

As the @override xy build methods in SearchDelegate are called with every change in the search field, I would load my file over and over again, which is of course not ideal.
I want to load my file once at the beginning only.

Is there a way to get some sort of get default context that I could use for example in the constructor of SearchDelegate. Like in android (if I remmeber correctly)?

Or can I load an assets file without .of(context)?

Body:
There is an option to get builtin AssetBundle without specifying a reference to BuildContext. Here is an example of how it could be done:

import 'package:flutter/services.dart'; // is required

Future<void> loadCountryData() async {
    try {
        // we can access builtin asset bundle with rootBundle
        final data = await rootBundle.loadString("assets/data/countries.json");
        _countries = json.decode(data);
    } catch (e) {
      print(e);
    }
}


问:
My Mortgage Calculator program on Java cannot produce output
I am trying to create a simple mortgage calculator program, but it seems like after asking for inputs, the program can't execute output. Would you guys please take a look at my code and let me know where did it go wrong? Thank you very much for your help!</p>

```<code>package com.ntrinh;
import java.text.NumberFormat;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        System.out.print("Principle: ");
        Scanner scanner1 = new Scanner(System.in);

        int principle = (int) scanner1.nextInt();

        System.out.print("Annual Interest: ");
        float interest = (float) scanner1.nextFloat();
        float result_interest = interest/100/12;

        System.out.print("Period (years): ");
        float period = (float) scanner1.nextFloat();
        float result_period = period * 12;

        double mortgage = (double) scanner1.nextDouble();
        double result_mortgage = principle
                * (result_interest * Math.pow(1 + result_interest, result_period))
                / (Math.pow(1 + result_interest, result_period) - 1);

        String mortgageFormatted = NumberFormat.getCurrencyInstance().format(result_mortgage);
        System.out.println("Mortgage: " + mortgageFormatted);
    }
}
</code>```

答:
You wait for another value at double mortgage = (double) scanner1.nextDouble();

Add a print before this line so that user knows that one more value is needed for the calculation.

Once you enter it and hit Enter, the app continues execution.

Body:
I am trying to create a simple mortgage calculator program, but it seems like after asking for inputs, the program can't execute output. Would you guys please take a look at my code and let me know where did it go wrong? Thank you very much for your help!

package com.ntrinh;
import java.text.NumberFormat;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        System.out.print("Principle: ");
        Scanner scanner1 = new Scanner(System.in);

        int principle = (int) scanner1.nextInt();

        System.out.print("Annual Interest: ");
        float interest = (float) scanner1.nextFloat();
        float result_interest = interest/100/12;

        System.out.print("Period (years): ");
        float period = (float) scanner1.nextFloat();
        float result_period = period * 12;

        double mortgage = (double) scanner1.nextDouble();
        double result_mortgage = principle
                * (result_interest * Math.pow(1 + result_interest, result_period))
                / (Math.pow(1 + result_interest, result_period) - 1);

        String mortgageFormatted = NumberFormat.getCurrencyInstance().format(result_mortgage);
        System.out.println("Mortgage: " + mortgageFormatted);
    }
}


问:
CMake can't find Boost_LIBRARIES variable
Final Edit: Solved.
Guys the problem occured because of the "WinSock32".
I've added

```<code>target_link_libraries(modernC__ -lws2_32)
</code>```

and the code has been builded.

I have been using the Boost library on CLion in Ubuntu for about 1 year. But this week I also decided to install it on the Windows operating system.
so I downloaded the Boost library on GitHub and installed the Boost library using Find.Boost first and then "Find.Boost".

After writing the necessary commands in CMake settings section in CLion, I noticed that the variable $ {Boost_LIBRARIES} is empty.

When I don't use the message () function, the "CMake" part of the project does not give an error, but I get the error "undefined reference" after "build". Below are the CMake commands I wrote on CLion and the errors I received.

```<code>cmake_minimum_required(VERSION 3.16)
project(modernC__)

set(CMAKE_CXX_STANDARD 17)
find_package(Boost 1.66.0)

message(${Boost_INCLUDE_DIR})
message(${Boost_FOUND})
message(${Boost_LIBRARY_DIRS})

IF (Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIR})
add_executable(modernC__

        main.cpp

        #concurrencyExampleOne.cpp

        #adapterExampleOne.cpp
        )
target_link_libraries(modernC__ ${Boost_LIBRARIES})
    message(${Boost_LIBRARIES})
endif()
</code>```

My output is:

```<code>"C:\Program Files\JetBrains\CLion 2020.1.1\bin\cmake\win\bin\cmake.exe" -DCMAKE_BUILD_TYPE=Debug -G "CodeBlocks - MinGW Makefiles" C:\Users\Berke\CLionProjects\modernC++
C:/boost/include/boost-1_66
TRUE
C:/boost/lib
CMake Error at CMakeLists.txt:22 (message):
  message called with incorrect number of arguments

-- Configuring incomplete, errors occurred!
</code>```

In this case, obviously Cmake is currently unable to find the .lib files that should link to my code.
My question is; How can I permanently drop .lib files into this variable, or is there any other way to do this?

If I do not use "message(${Boost_LIBRARIES}" so the compiler gives me this error;

```<code>[ 50%] Linking CXX executable modernC__.exe
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZNK5boost6system14error_category12std_category10equivalentEiRKSt15error_condition':
C:/boost/include/boost-1_66/boost/system/error_code.hpp:676: undefined reference to `boost::system::generic_category()'
C:/boost/include/boost-1_66/boost/system/error_code.hpp:679: undefined reference to `boost::system::generic_category()'
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZNK5boost6system14error_category12std_category10equivalentERKSt10error_codei':
C:/boost/include/boost-1_66/boost/system/error_code.hpp:706: undefined reference to `boost::system::generic_category()'
C:/boost/include/boost-1_66/boost/system/error_code.hpp:709: undefined reference to `boost::system::generic_category()'
C:/boost/include/boost-1_66/boost/system/error_code.hpp:721: undefined reference to `boost::system::generic_category()'
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZN5boost4asio5error19get_system_categoryEv':
C:/boost/include/boost-1_66/boost/asio/error.hpp:230: undefined reference to `boost::system::system_category()'
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZN5boost4asio6detail17winsock_init_base7startupERNS2_4dataEhh':
C:/boost/include/boost-1_66/boost/asio/detail/impl/winsock_init.ipp:39: undefined reference to `_imp__WSAStartup@8'
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZN5boost4asio6detail17winsock_init_base7cleanupERNS2_4dataE':
C:/boost/include/boost-1_66/boost/asio/detail/impl/winsock_init.ipp:56: undefined reference to `_imp__WSACleanup@0'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\modernC__.dir\build.make:86: modernC__.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:75: CMakeFiles/modernC__.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:82: CMakeFiles/modernC__.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: modernC__] Error 2
</code>```

答:
I think, you should specify boost libraries (as components) explicitly.
And you should add libraries to target.

Like this:

```<code>find_package(Boost COMPONENTS filesystem system locale context REQUIRED)

...

target_link_libraries(${PROJECT_NAME}
  ...
  ${Boost_FILESYSTEM_LIBRARY}
  ${Boost_SYSTEM_LIBRARY}
  ${Boost_LOCALE_LIBRARY}
  ${Boost_CONTEXT_LIBRARY}
  ...
  )

</code>```

Body:
Final Edit: Solved.
Guys the problem occured because of the "WinSock32".
I've added

target_link_libraries(modernC__ -lws2_32)

and the code has been builded.

I have been using the Boost library on CLion in Ubuntu for about 1 year. But this week I also decided to install it on the Windows operating system.
so I downloaded the Boost library on GitHub and installed the Boost library using Find.Boost first and then "Find.Boost".

After writing the necessary commands in CMake settings section in CLion, I noticed that the variable $ {Boost_LIBRARIES} is empty.

When I don't use the message () function, the "CMake" part of the project does not give an error, but I get the error "undefined reference" after "build". Below are the CMake commands I wrote on CLion and the errors I received.

cmake_minimum_required(VERSION 3.16)
project(modernC__)

set(CMAKE_CXX_STANDARD 17)
find_package(Boost 1.66.0)

message(${Boost_INCLUDE_DIR})
message(${Boost_FOUND})
message(${Boost_LIBRARY_DIRS})

IF (Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIR})
add_executable(modernC__

        main.cpp

        #concurrencyExampleOne.cpp

        #adapterExampleOne.cpp
        )
target_link_libraries(modernC__ ${Boost_LIBRARIES})
    message(${Boost_LIBRARIES})
endif()

My output is:

"C:\Program Files\JetBrains\CLion 2020.1.1\bin\cmake\win\bin\cmake.exe" -DCMAKE_BUILD_TYPE=Debug -G "CodeBlocks - MinGW Makefiles" C:\Users\Berke\CLionProjects\modernC++
C:/boost/include/boost-1_66
TRUE
C:/boost/lib
CMake Error at CMakeLists.txt:22 (message):
  message called with incorrect number of arguments

-- Configuring incomplete, errors occurred!

In this case, obviously Cmake is currently unable to find the .lib files that should link to my code.
My question is; How can I permanently drop .lib files into this variable, or is there any other way to do this?

If I do not use "message(${Boost_LIBRARIES}" so the compiler gives me this error;

[ 50%] Linking CXX executable modernC__.exe
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZNK5boost6system14error_category12std_category10equivalentEiRKSt15error_condition':
C:/boost/include/boost-1_66/boost/system/error_code.hpp:676: undefined reference to `boost::system::generic_category()'
C:/boost/include/boost-1_66/boost/system/error_code.hpp:679: undefined reference to `boost::system::generic_category()'
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZNK5boost6system14error_category12std_category10equivalentERKSt10error_codei':
C:/boost/include/boost-1_66/boost/system/error_code.hpp:706: undefined reference to `boost::system::generic_category()'
C:/boost/include/boost-1_66/boost/system/error_code.hpp:709: undefined reference to `boost::system::generic_category()'
C:/boost/include/boost-1_66/boost/system/error_code.hpp:721: undefined reference to `boost::system::generic_category()'
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZN5boost4asio5error19get_system_categoryEv':
C:/boost/include/boost-1_66/boost/asio/error.hpp:230: undefined reference to `boost::system::system_category()'
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZN5boost4asio6detail17winsock_init_base7startupERNS2_4dataEhh':
C:/boost/include/boost-1_66/boost/asio/detail/impl/winsock_init.ipp:39: undefined reference to `_imp__WSAStartup@8'
CMakeFiles\modernC__.dir/objects.a(main.cpp.obj): In function `ZN5boost4asio6detail17winsock_init_base7cleanupERNS2_4dataE':
C:/boost/include/boost-1_66/boost/asio/detail/impl/winsock_init.ipp:56: undefined reference to `_imp__WSACleanup@0'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\modernC__.dir\build.make:86: modernC__.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:75: CMakeFiles/modernC__.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:82: CMakeFiles/modernC__.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: modernC__] Error 2

Body:
I think, you should specify boost libraries (as components) explicitly.
And you should add libraries to target.

Like this:

find_package(Boost COMPONENTS filesystem system locale context REQUIRED)

...

target_link_libraries(${PROJECT_NAME}
  ...
  ${Boost_FILESYSTEM_LIBRARY}
  ${Boost_SYSTEM_LIBRARY}
  ${Boost_LOCALE_LIBRARY}
  ${Boost_CONTEXT_LIBRARY}
  ...
  )


问:
LINQ Querying list in list
I have this situation:

My ModelView:

```<code>public class Subject
{
   public int ID { get; set; }
   public string Name { get; set; }
   public int ProfessorID { get; set; }
   public string ProfessorFullName{ get; set; }
   public IList<Assistant> Assistants { get; set; }
}

public class Assistant
{
   public string AssistantFullName{ get; set; }
}
</code>```

My query:

```<code>var subjects = from subject in Entities.Subjects
                            from professor in subject.Lecturers
                            where professor.Professor == true
                            select new SSVN.ModelView.Subject()
                            {
                                ID = subject.ID,
                                Name= subject.Name,
                                ProfessorFullName= professor.LastName+ " " + professor.Name,
                                Assistants= (from subject1 in Entities.Subjects
                                            from assistant in subject1.Lecturers
                                            where assistant.Professor == false
                                            select new SSVN.ModelView.Assistant()
                                            {
                                                AssistantFullName = assistant.LastName+ " " + assistant.Name
                                            }).ToList()
                            };
</code>```

And when I call:

subjects.ToList(); I get exception:

```<code>LINQ to Entities does not recognize the method
'System.Collections.Generic.List`1[SSVN.ModelView.Assistant] ToList[Assistant]
(System.Collections.Generic.IEnumerable`1[SSVN.ModelView.Assistant])' method, and this
method cannot be translated into a store expression.
</code>```

答:
You cannot call ToList inside linq-to-entities query. Linq-to-entities query will always project to IEnumerable<T> so if you want IList<T> you must call it in linq-to-objects.

Try this:

```<code>var subjects = (from subject in Entities.Subjects
                from professor in subject.Lecturers
                where professor.Professor == true
                select new
                    {
                        ID = subject.ID,
                        Name= subject.Name,
                        ProfessorFullName= professor.LastName+ " " + professor.Name,
                        Assistants= (from subject1 in Entities.Subjects
                                     from assistant in subject1.Lecturers
                                     where assistant.Professor == false
                                     select new SSVN.ModelView.Assistant()
                                         {
                                             AssistantFullName = assistant.LastName+ " " + assistant.Name
                                         })
                    }).AsEnumerable().Select(x => new SSVN.ModelView.Subject
                         {
                            ID = x.ID,
                            Name = x.Name,
                            ProfessorFullName = X.ProffesorFullName,
                            Assistants = x.Assistants.ToList()
                         });
</code>```

Title: LINQ Querying list in list

Body:
I have this situation:

My ModelView:

public class Subject
{
   public int ID { get; set; }
   public string Name { get; set; }
   public int ProfessorID { get; set; }
   public string ProfessorFullName{ get; set; }
   public IList<Assistant> Assistants { get; set; }
}

public class Assistant
{
   public string AssistantFullName{ get; set; }
}

My query:

var subjects = from subject in Entities.Subjects
                            from professor in subject.Lecturers
                            where professor.Professor == true
                            select new SSVN.ModelView.Subject()
                            {
                                ID = subject.ID,
                                Name= subject.Name,
                                ProfessorFullName= professor.LastName+ " " + professor.Name,
                                Assistants= (from subject1 in Entities.Subjects
                                            from assistant in subject1.Lecturers
                                            where assistant.Professor == false
                                            select new SSVN.ModelView.Assistant()
                                            {
                                                AssistantFullName = assistant.LastName+ " " + assistant.Name
                                            }).ToList()
                            };

And when I call:

subjects.ToList(); I get exception:

LINQ to Entities does not recognize the method
'System.Collections.Generic.List`1[SSVN.ModelView.Assistant] ToList[Assistant]
(System.Collections.Generic.IEnumerable`1[SSVN.ModelView.Assistant])' method, and this
method cannot be translated into a store expression.

Body:
You cannot call ToList inside linq-to-entities query. Linq-to-entities query will always project to IEnumerable<T> so if you want IList<T> you must call it in linq-to-objects.

Try this:

var subjects = (from subject in Entities.Subjects
                from professor in subject.Lecturers
                where professor.Professor == true
                select new
                    {
                        ID = subject.ID,
                        Name= subject.Name,
                        ProfessorFullName= professor.LastName+ " " + professor.Name,
                        Assistants= (from subject1 in Entities.Subjects
                                     from assistant in subject1.Lecturers
                                     where assistant.Professor == false
                                     select new SSVN.ModelView.Assistant()
                                         {
                                             AssistantFullName = assistant.LastName+ " " + assistant.Name
                                         })
                    }).AsEnumerable().Select(x => new SSVN.ModelView.Subject
                         {
                            ID = x.ID,
                            Name = x.Name,
                            ProfessorFullName = X.ProffesorFullName,
                            Assistants = x.Assistants.ToList()
                         });


问:
Visual Studio Code does not suggest any Node.js syntax
I am new to visual studio code and Node.js and also install Node and npm to my computer.
My problem is VS code does not suggest any node syantax.
I watch youtube tutorials to learn node and in the video, instructors VS code suggest node js syntax.</p>

答:
Based on: https://code.visualstudio.com/docs/editor/intellisense it should have intellisense come right out of the box within VS code. I would recommend uninstalling and reinstalling VS code.

Some other gotcha's or things which may help:

Intellisense for javascript only works within files that are labeled with the .js extension

The hotkey Ctrl+Shift+brings up a terminal which contains aProblems` in there you can see the problems of the Workspace which may show some additional information regarding what is failing.


问:
Pandas Groupby: How to use two lambda functions?
I can currently do the following in Pandas, but I get a stern finger wagging from FutureWarning:

```<code>grpd = df.groupby("rank").agg({
    "mean": np.mean, "meian": np.median, "min": np.min, "max": np.max,
    "25th percentile": lambda x: np.percentile(x, 25),
    "75th percentile": lambda x: np.percentile(x, 75)
})
</code>```

The following throws an error because I have two lambda functions:

```<code>percentile_25 = lambda x: np.percentile(x, 25)
percentile_75 = lambda x: np.percentile(x, 75)

df = diffs[["User Installs", "rank"]].dropna()
grpd = df.groupby("shopping_rank").agg([
    np.mean, np.median, np.min, np.max,
    percentile_25, percentile_75
])
</code>```

This throws:

```<code>SpecificationError: Function names must be unique, found multiple named <lambda>
</code>```

The only way I can seem to make this work (without ignoring the warning, which I should probably just do) is with an elaborate process like the following

Define my DF with one lambda function (25th percentile), and everything else I need (min, max, etc.)

rename the cols to get rid of the MultiIndex

Create ANOTHER DF, do ANOTHER grouping, this time with the other column I want (75th percentile)

Rename cols again (thanks MultiIndex!)

Join back to the original DF on the index

Is there something I'm missing here? Surely there's a better way to do what I imagine is a pretty common thing (using two aggregations that aren't directly importable from numpy).

答:
The problem is a result column name.

An alternative:

```<code>percentile_25 = lambda x: np.percentile(x, 25)
percentile_75 = lambda x: np.percentile(x, 75)

grouped = df.groupby("field1")
grouped.agg({
    'field2': {'percentile_25': percentile_25, 'percentile_75': percentile_75}
})
</code>```

Body:
I can currently do the following in Pandas, but I get a stern finger wagging from FutureWarning:

grpd = df.groupby("rank").agg({
    "mean": np.mean, "meian": np.median, "min": np.min, "max": np.max,
    "25th percentile": lambda x: np.percentile(x, 25),
    "75th percentile": lambda x: np.percentile(x, 75)
})

The following throws an error because I have two lambda functions:

percentile_25 = lambda x: np.percentile(x, 25)
percentile_75 = lambda x: np.percentile(x, 75)

df = diffs[["User Installs", "rank"]].dropna()
grpd = df.groupby("shopping_rank").agg([
    np.mean, np.median, np.min, np.max,
    percentile_25, percentile_75
])

This throws:

SpecificationError: Function names must be unique, found multiple named <lambda>

The only way I can seem to make this work (without ignoring the warning, which I should probably just do) is with an elaborate process like the following

Define my DF with one lambda function (25th percentile), and everything else I need (min, max, etc.)

rename the cols to get rid of the MultiIndex

Create ANOTHER DF, do ANOTHER grouping, this time with the other column I want (75th percentile)

Rename cols again (thanks MultiIndex!)

Join back to the original DF on the index

Is there something I'm missing here? Surely there's a better way to do what I imagine is a pretty common thing (using two aggregations that aren't directly importable from numpy).

Body:
The problem is a result column name.

An alternative:

percentile_25 = lambda x: np.percentile(x, 25)
percentile_75 = lambda x: np.percentile(x, 75)

grouped = df.groupby("field1")
grouped.agg({
    'field2': {'percentile_25': percentile_25, 'percentile_75': percentile_75}
})


问:
Why is unittest coverage disabled for Python 3.8.3?
I have this version of Python:

```<code>3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]
</code>```

running on Windows 10 in PyCharm CE 2020.1.1. Using a very simple unittest:

# test_simple.py

from unittest import TestCase

class Simple(TestCase):
    def test_one(self):
        self.assertTrue(True)
```

I can run python -m coverage run -m unittest, which completes and generates a .coverage SQLite file; and I can run the test from the IDE which produces a Test Results tree; but Run / Run with Coverage is grayed out with no explanation.

I have followed the (fairly scattered) PyCharm documentation to do Settings / Build, Execution, Deployment, Activate Coverage View enabled, Show options before applying coverage to the editor and this has not helped.

Why is coverage grayed out and how can I fix it?

答:
Unfortunately, IDE coverage support is not available in the Community Edition of PyCharm, as can be seen in the edition features.

You have to run coverage on the command line as usual, as shown for example in this answer.

You could also use some wrapper that creates and opens a HTML report. An example for such a wrapper that uses pytest with coverage can be found in this blog post. Here is the script used in that blog (note that I changed the coverage path to work with current versions):

```<code>import os
import subprocess
import webbrowser

def main():
    subprocess.call(['coverage', 'erase'])
    subprocess.call(['coverage', 'run', '--module', 'pytest'])
    subprocess.call(['coverage', 'html'])
    webbrowser.open("file://" + os.getcwd() + "/htmlcov/index.html", new=2)

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

Body:
I have this version of Python:

3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]

running on Windows 10 in PyCharm CE 2020.1.1. Using a very simple unittest:

# test_simple.py

from unittest import TestCase

class Simple(TestCase):
    def test_one(self):
        self.assertTrue(True)

I can run python -m coverage run -m unittest, which completes and generates a .coverage SQLite file; and I can run the test from the IDE which produces a Test Results tree; but Run / Run with Coverage is grayed out with no explanation.

I have followed the (fairly scattered) PyCharm documentation to do Settings / Build, Execution, Deployment, Activate Coverage View enabled, Show options before applying coverage to the editor and this has not helped.

Why is coverage grayed out and how can I fix it?

Body:
Unfortunately, IDE coverage support is not available in the Community Edition of PyCharm, as can be seen in the edition features.

You have to run coverage on the command line as usual, as shown for example in this answer.

You could also use some wrapper that creates and opens a HTML report. An example for such a wrapper that uses pytest with coverage can be found in this blog post. Here is the script used in that blog (note that I changed the coverage path to work with current versions):

import os
import subprocess
import webbrowser

def main():
    subprocess.call(['coverage', 'erase'])
    subprocess.call(['coverage', 'run', '--module', 'pytest'])
    subprocess.call(['coverage', 'html'])
    webbrowser.open("file://" + os.getcwd() + "/htmlcov/index.html", new=2)

if __name__ == '__main__':
    main()


问:
Does NltkNet the NLTK wrapper class support .NET core web applications or only console applications?
When I try to Initialize the NltkNet object in my dotnet core web application I receive an error saying an assembly is not found or has a different manifest definition than its assembly reference.

The code is fairly simple, it does nothing at all except initialize an NltkNet object when a button is clicked.

```<code>public IActionResult Upload()
{
    Nltk.Init(new List<string>()
    {
        @"C:\IronPython27\Lib",
        @"C:\IronPython27\Lib\site-packages",
    });

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

I was able to get the exact same code to work in my console application without issue.

Is this a configuration issue on my end or is ASP.NET core MVC web application support not available for NltkNet?

答: I have discovered that NltkNet does not support dotnet core.</p>

Body:
When I try to Initialize the NltkNet object in my dotnet core web application I receive an error saying an assembly is not found or has a different manifest definition than its assembly reference.

The code is fairly simple, it does nothing at all except initialize an NltkNet object when a button is clicked.

public IActionResult Upload()
{
    Nltk.Init(new List<string>()
    {
        @"C:\IronPython27\Lib",
        @"C:\IronPython27\Lib\site-packages",
    });

            return View();
        }

I was able to get the exact same code to work in my console application without issue.

Is this a configuration issue on my end or is ASP.NET core MVC web application support not available for NltkNet?


问:
How to mock a custom hook inside of a React component you want to test?
If you have a React component that calls a custom hook that fetches data, what is the best way to mock that internal custom hook result when testing the React component? I see 2 main approaches:

1) Jest.mock the custom hook. This seems to be the most recommended approach, but it seems like it requires the test to have more knowledge of internal implementation details and what it might need to mock than what the props interface of the component might suggest (assuming use of prop-types or TypeScript)

2) Use a dependency injection approach. Declare the hook as a prop, but default it to the real hook so you don't have to set it everywhere you render the component, but allow overriding with a mock for tests. Here is a contrived codesandbox example with a test that mocks a custom hook:

https://codesandbox.io/s/dependency-inject-custom-hook-for-testing-mjqlf?fontsize=14&module=%2Fsrc%2FApp.js

2 requires more typing, but seems easier to work with for testing. However, tests already have to have knowledge of internal implementation details of component to test any conditional logic for rendered output, so maybe that's not important and 1 is the best approach. Is 1 the way to go? What tradeoffs do you see? Am I missing another approach altogether?

答:
To mock your custom hook using jest.</p>

```<code>import * as useCustomHook from '../hooks/useCustomHooks'

const spy = jest.spyOn(useCustomHook, 'default')
spy.mockReturnValue({
name: 'test'
})
</code>```

Body:
To mock your custom hook using jest.

import * as useCustomHook from '../hooks/useCustomHooks'

const spy = jest.spyOn(useCustomHook, 'default')
spy.mockReturnValue({
name: 'test'
})


问:
How to manage multiple currencies in the database
If I have different multiple payroll disbursements based on the company location, the employee contract type and other criteria:
So

Some have their salaries divided into parts the first in USD and the second in Local cur.

```<code>Ex: Employee 343 receive his salary as following: 200 USD & 3000 EGP (The local currency).
EX: Employee 672 receive his salary as following: 200 USD & 200 EUR (The local currency).
</code>```

Some have their salaries just in one currency (the local).

```<code>Ex: Employee 532 receive his salary as following: 5000 EGP.
</code>```

So We have multiple currencies for the salaries of the company based on the location and other business rules.

What 's the most proper way to save the salaries of the employees with these variations in DB so that It's easy to retrieve, process and scale.

If I use one table so I will have many columns and I have to add new columns every time a new branch for the company is initiated.
Like this:

```<code>Sal_USD  | Sal_EGP | Sal_Eur
</code>```

Is there an elegant way to handle this?

答: Create a column CurrencyCode and use 2 rows for an employee that has salary paid in 2 currencies. </p>

Body:
If I have different multiple payroll disbursements based on the company location, the employee contract type and other criteria:
So

Some have their salaries divided into parts the first in USD and the second in Local cur.

Ex: Employee 343 receive his salary as following: 200 USD & 3000 EGP (The local currency).
EX: Employee 672 receive his salary as following: 200 USD & 200 EUR (The local currency).

Some have their salaries just in one currency (the local).

Ex: Employee 532 receive his salary as following: 5000 EGP.

So We have multiple currencies for the salaries of the company based on the location and other business rules.

What 's the most proper way to save the salaries of the employees with these variations in DB so that It's easy to retrieve, process and scale.

If I use one table so I will have many columns and I have to add new columns every time a new branch for the company is initiated.
Like this:

Sal_USD  | Sal_EGP | Sal_Eur

Is there an elegant way to handle this?


问:
SonarCloud - No scan results appearing for Javascript for maven / bitbucket project
I might be missing something obvious, but I can't seem to get scan results for javascript to appear in SonarCloud. The repository is 95% an angular app with 5% java code. The java code scan is appearing in SonarCloud, but really I only need to scan the javascript in the angular application.

So clearly we are connected to SonarCloud, but nothing appears for the javascript.

I added <sonar.language>js</sonar.language> to the pom.xml file, which has had the effect that no scan information at all appears in SonarCloud, presumably because this property cancels scanning any language other than javascript, and the javascript scan isn't configured correctly.

I just want to scan the angular project and report results in SonarCloud. Either by scanning the dist/portal directory where the angular project is built, or by scanning the underlying Typescript files in src/app.

It's fine if the java code is also scanned.

Thanks for any help or pointers you can provide.

ALM used: Bitbucket with Maven

Languages of the repository: java, javascript (only need to scan the javascript)

Error observed: No scan results for javascript appearing in SonarCloud

The directory structure of the repository is:

```<code>    - src
        - app
        - [rest of angular code]
    - e2e
        - [testing files]
    - deploy
        - pom.xml
        - [java code for the deploy]
    - bitbucket-pipelines.yml
</code>```

This is the pipeline.yml, and the step that uses maven to run sonarcloud:

```<code>          caches:
            sonar: ~/.sonar/cache
          steps:
            - step: &buildArtifacts
                name: Build and test
                image:
                  name: [[NAME]]
                  aws:
                    access-key: $AWS_ACCESS_KEY
                    secret-key: $AWS_SECRET_KEY
                caches:
                - maven
                - sonar
                script:
                - source prepare_environment.sh
                - mvn -e clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
                artifacts:
                - artifact/**
</code>```

And this is the properties inside the pom.xml in the deploy/directory:

```<code>    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <sonar.language>js</sonar.language>
        <sonar.sources>${project.basedir}/../dist/portal</sonar.sources>
    </properties>
</code>```

答:
Best option for scanning JS/TS is a custom Pipe.

If you don’t care about the Java code and just need to scan the Javascript and Typescript, then using the scanner for CLI is probably the best bet, and even more specifically, using the scan pipe is easiest to configure on Bitbucket Cloud. You don't need to use Maven at all.

In your bitbucket-pipelines YAML file, remove (or comment out) the reference to org.sonarsource.scanner in your &buildArtifacts step:

```<code>mvn -e clean verify # org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
</code>```

Then create a new step to run the pipe:

```<code>    - step: &buildAndTestSonarCloud
        name: Analyze with SonarCloud
        caches:
          - node
          - sonar
        script:
          - npm update && npm install
          - pipe: sonarsource/sonarcloud-scan:0.1.5
            variables:
              SONAR_TOKEN: ${SONAR_TOKEN}
              EXTRA_ARGS: '-Dsonar.sources=src/app'
              SONAR_SCANNER_OPTS: -Xmx512m
              DEBUG: "false"
</code>```

You might also need to expand memory available for the step with something like this:

```<code>definitions:
  services:
    docker:
      memory: 2048
</code>```

Finally, call your step:

```<code>pipelines:
  default:
    - step: *buildAndTestSonarCloud
    - step: *buildArtifacts
</code>```

That should work. You should be up and running there on the JS/TS.

If you also want to run unit tests and have sonarcloud track your test coverage, add this below your npm update line:

```<code>- npm run test -- --code-coverage --no-watch --no-progress --browsers=ChromeHeadlessNoSandbox
</code>```

And these EXTRA_ARGS configured for your file structure:

```<code>'-Dsonar.tests=src -Dsonar.test.inclusions="**/testing/**,**/*.spec.ts" -Dsonar.typescript.lcov.reportPaths=coverage/lcov.info'
</code>```

That worked for me and should handle the full configuration.

Note: This is not going to look at Java code in your repository. If you do need Java code also scanned, a more complex Maven implementation is what you will need.

Body:
I might be missing something obvious, but I can't seem to get scan results for javascript to appear in SonarCloud. The repository is 95% an angular app with 5% java code. The java code scan is appearing in SonarCloud, but really I only need to scan the javascript in the angular application.

So clearly we are connected to SonarCloud, but nothing appears for the javascript.

I added <sonar.language>js</sonar.language> to the pom.xml file, which has had the effect that no scan information at all appears in SonarCloud, presumably because this property cancels scanning any language other than javascript, and the javascript scan isn't configured correctly.

I just want to scan the angular project and report results in SonarCloud. Either by scanning the dist/portal directory where the angular project is built, or by scanning the underlying Typescript files in src/app.

It's fine if the java code is also scanned.

Thanks for any help or pointers you can provide.

ALM used: Bitbucket with Maven

Languages of the repository: java, javascript (only need to scan the javascript)

Error observed: No scan results for javascript appearing in SonarCloud

The directory structure of the repository is:

    - src
        - app
        - [rest of angular code]
    - e2e
        - [testing files]
    - deploy
        - pom.xml
        - [java code for the deploy]
    - bitbucket-pipelines.yml

This is the pipeline.yml, and the step that uses maven to run sonarcloud:

          caches:
            sonar: ~/.sonar/cache
          steps:
            - step: &buildArtifacts
                name: Build and test
                image:
                  name: [[NAME]]
                  aws:
                    access-key: $AWS_ACCESS_KEY
                    secret-key: $AWS_SECRET_KEY
                caches:
                - maven
                - sonar
                script:
                - source prepare_environment.sh
                - mvn -e clean verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
                artifacts:
                - artifact/**

And this is the properties inside the pom.xml in the deploy/directory:

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <sonar.language>js</sonar.language>
        <sonar.sources>${project.basedir}/../dist/portal</sonar.sources>
    </properties>

Body:
Best option for scanning JS/TS is a custom Pipe.

If you don’t care about the Java code and just need to scan the Javascript and Typescript, then using the scanner for CLI is probably the best bet, and even more specifically, using the scan pipe is easiest to configure on Bitbucket Cloud. You don't need to use Maven at all.

In your bitbucket-pipelines YAML file, remove (or comment out) the reference to org.sonarsource.scanner in your &buildArtifacts step:

mvn -e clean verify # org.sonarsource.scanner.maven:sonar-maven-plugin:sonar

Then create a new step to run the pipe:

    - step: &buildAndTestSonarCloud
        name: Analyze with SonarCloud
        caches:
          - node
          - sonar
        script:
          - npm update && npm install
          - pipe: sonarsource/sonarcloud-scan:0.1.5
            variables:
              SONAR_TOKEN: ${SONAR_TOKEN}
              EXTRA_ARGS: '-Dsonar.sources=src/app'
              SONAR_SCANNER_OPTS: -Xmx512m
              DEBUG: "false"

You might also need to expand memory available for the step with something like this:

definitions:
  services:
    docker:
      memory: 2048

Finally, call your step:

pipelines:
  default:
    - step: *buildAndTestSonarCloud
    - step: *buildArtifacts

That should work. You should be up and running there on the JS/TS.

If you also want to run unit tests and have sonarcloud track your test coverage, add this below your npm update line:

- npm run test -- --code-coverage --no-watch --no-progress --browsers=ChromeHeadlessNoSandbox

And these EXTRA_ARGS configured for your file structure:

'-Dsonar.tests=src -Dsonar.test.inclusions="**/testing/**,**/*.spec.ts" -Dsonar.typescript.lcov.reportPaths=coverage/lcov.info'

That worked for me and should handle the full configuration.

Note: This is not going to look at Java code in your repository. If you do need Java code also scanned, a more complex Maven implementation is what you will need.


问:
applying css class dynamically to table td not working in firefox
I want to add css class to td which is created dynamically and this is portion of my code

```<code>var newTD = document.createElement("td");
</code>```

td is created but border is not coming.
td is added into table properly when user clicks on plus button.css is not applied.

css class is

```<code>table.ms_grid td, table.ms_grid table td
{
padding: 3px 5px;
border: 1px #D3E4F5 solid;
cursor: pointer;
}
</code>```

this code is part of my project

please suggest solution.

答:
Most table cell borders won't display unless there's something within.

The old method was to add a   inside however I believe there's a CSS property to always show borders. Will edit if I find it.

There it is, empty-cells, supported in everything (current) except IE7 and below

Body:
I want to add css class to td which is created dynamically and this is portion of my code

var newTD = document.createElement("td");

td is created but border is not coming.
td is added into table properly when user clicks on plus button.css is not applied.

css class is

table.ms_grid td, table.ms_grid table td
{
padding: 3px 5px;
border: 1px #D3E4F5 solid;
cursor: pointer;
}

this code is part of my project

please suggest solution.

Body:
Most table cell borders won't display unless there's something within.

The old method was to add a &nbsp; inside however I believe there's a CSS property to always show borders. Will edit if I find it.

There it is, empty-cells, supported in everything (current) except IE7 and below


问:
When is implicit type declaration ever good?
I have a colleague who writes Fortran, generally following the F77 standard. I have had to work with some of their source code and I find the use of implicit type declarations (not using implicit none) really confusing and frustrating. Their reason for doing so is to "eliminate all of those type declarations at the beginning of my program(s)." In my opinion, this is a poor trade off for ruining readability and comprehension of the program and its many subroutines. Are there any other, more valid, reasons for not including implicit none in Fortran programs and subroutines?

答: Well, I used punch cards but I usually use implicit none in my Fortran codes as well. Much of my Fortran coding now, however, is just to write a pre-processor or post-processor of data. Things that people use python for now. I know python but my programming skills in python are not that good. So when you're writing 100-300 lines of code only the implicit none can be a pain. I use it so people won't make fun of me but for short utility codes, implicit none buys you little. imho!</p>


问:
Auth token in URL path
I'm using Django REST Framework TokenAuthentication.

For a few URLs I'm constrained to having to include the token in the URL path:

https://example.com/api/<auth_token>/something

So the urlpatterns are:

```<code>urlpatterns = [
    path('api/<auth_token>/something', views.SomeView.as_view()),
]
</code>```

And the view is:

```<code>class SomeView(APIView):
    authentication_classes = (TokenAuthentication)
    permission_classes = (IsAuthenticated, )

    def get(self, request, auth_token):
    ...

</code>```

But TokenAuthentication does not work here because the token is in the URL path, not in the header. I'd like to extend TokenAuthentication to handle in-URL tokens too, if possible.

答:
First of all, putting auth tokens in the url is insecure and not recommended (urls end up in server logs and stuff).

If it was a matter of life or death, what I would do is extend the TokenAuthentication class from Django rest, overriding only the authenticate method. If you look at the source code, it obtains the token from the header, runs some validations and calls self.authenticate_credentials(token). So I'd do something like:

```<code>class UrlTokenAuthentication(TokenAuthentication):
    def authenticate(self, request):
        token = # get the token from the url path and check that has proper format, etc.
        return self.authenticate_credentials(token)
</code>```

Title: Auth token in URL path

Body:
I'm using Django REST Framework TokenAuthentication.

For a few URLs I'm constrained to having to include the token in the URL path:

https://example.com/api/<auth_token>/something

So the urlpatterns are:

urlpatterns = [
    path('api/<auth_token>/something', views.SomeView.as_view()),
]

And the view is:

class SomeView(APIView):
    authentication_classes = (TokenAuthentication)
    permission_classes = (IsAuthenticated, )

    def get(self, request, auth_token):
    ...

But TokenAuthentication does not work here because the token is in the URL path, not in the header. I'd like to extend TokenAuthentication to handle in-URL tokens too, if possible.

Body:
First of all, putting auth tokens in the url is insecure and not recommended (urls end up in server logs and stuff).

If it was a matter of life or death, what I would do is extend the TokenAuthentication class from Django rest, overriding only the authenticate method. If you look at the source code, it obtains the token from the header, runs some validations and calls self.authenticate_credentials(token). So I'd do something like:

class UrlTokenAuthentication(TokenAuthentication):
    def authenticate(self, request):
        token = # get the token from the url path and check that has proper format, etc.
        return self.authenticate_credentials(token)


问:
Issues when trying to space XMLHttpRequest() API calls every 5 seconds with setTimeout()
I am working on the initial data pull for a project. It will be cached and further requests will be much less.  I am attempting to space out my API requests every 5 seconds to avoid overloading the server and hitting the rate limit per their rules.  It does not seem that my setTimeout() function is actually working as desired. I logged time stamps to see and all iterations seem to be happening at the exact same time.  I think this somehow due to the asynchronous nature of javascript, but I'm not sure how to remedy it.  Any help would be greatly appreciated.

Code Excerpt:

```<code>var leagues;
function getLeagues(){

    var reqURL = "url";
    var data = new XMLHttpRequest();
    data.open("GET", reqURL);
    data.responseType = "text";
    data.send();

    // parse data on load
    data.onload = function() {
        // League IDs
        leagues = JSON.parse(data.response)

        for (i = 0; i < 5; i++) {
            delay(i); // iterate every 5 secs
        }
    };
}

function delay(i) {
  setTimeout(() => {
    var d = new Date();
    console.log(d.getSeconds())
  }, 5000);
}
</code>```

答:
```<code>function delay(i) {
  setTimeout(() => {
    var d = new Date();
    console.log(d.getSeconds())
  }, i * 5000);
}
</code>```

The process of setting up the timeout i.e. the calls to setTimeout() — takes almost no time at all. If a succession of timeout requests is made, the delay value is the same for each one, then once that amount of time has elapsed.. all the timer handlers will be called consecutively rapidly. If you need the handlers to be called at intervals, you can either use setInterval(), which is called exactly like setTimeout() but will fire more than once after repeated delays of 5000, or instead, you can establish the timeouts and multiply the time value by your iteration counter i.e. 'i' in this case. The value of i is multiplied by the original delay value, so calling that 5 times in a loop will result in delays of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds.

Body:
I am working on the initial data pull for a project. It will be cached and further requests will be much less.  I am attempting to space out my API requests every 5 seconds to avoid overloading the server and hitting the rate limit per their rules.  It does not seem that my setTimeout() function is actually working as desired. I logged time stamps to see and all iterations seem to be happening at the exact same time.  I think this somehow due to the asynchronous nature of javascript, but I'm not sure how to remedy it.  Any help would be greatly appreciated.

Code Excerpt:

var leagues;
function getLeagues(){

    var reqURL = "url";
    var data = new XMLHttpRequest();
    data.open("GET", reqURL);
    data.responseType = "text";
    data.send();

    // parse data on load
    data.onload = function() {
        // League IDs
        leagues = JSON.parse(data.response)

        for (i = 0; i < 5; i++) {
            delay(i); // iterate every 5 secs
        }
    };
}

function delay(i) {
  setTimeout(() => {
    var d = new Date();
    console.log(d.getSeconds())
  }, 5000);
}

Body:
function delay(i) {
  setTimeout(() => {
    var d = new Date();
    console.log(d.getSeconds())
  }, i * 5000);
}

The process of setting up the timeout i.e. the calls to setTimeout() — takes almost no time at all. If a succession of timeout requests is made, the delay value is the same for each one, then once that amount of time has elapsed.. all the timer handlers will be called consecutively rapidly. If you need the handlers to be called at intervals, you can either use setInterval(), which is called exactly like setTimeout() but will fire more than once after repeated delays of 5000, or instead, you can establish the timeouts and multiply the time value by your iteration counter i.e. 'i' in this case. The value of i is multiplied by the original delay value, so calling that 5 times in a loop will result in delays of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds.


问:
Unable to get output in Verilog simulation of digital clock
I want to design a seconds counter, which will count from 0 to 59, using Mod10COunter and Mod6Counter. I am trying to test the output using a testbench. The clock generated is perfect. However, the output is always 'X'. This is the code for the seconds counter.

```<code>module generateSec(clk, reset, s1, s2, min_en);
input wire clk, reset;
 output reg [3:0] s1, s2;
 output reg min_en;

 wire enable;
 Mod10Counter sec1 (.clk(clk), .out(s1), .en_out(enable), .rst(reset));
 Mod6Counter sec2 (.clk(enable), .out(s2), .en_out(min_en), .rst(reset));
endmodule
</code>```

I have written the modules used as below.

```<code>module Mod10Counter(clk, out, en_out, rst);
input clk, rst;
output reg [3:0] out;
output reg en_out;

always @(posedge clk or rst) begin

    if (rst) begin
        out<=4'b0000;
        en_out<=1'b0;
        end
    else if (out == 4'b1001) begin
        out <= 4'b0000;
        en_out <= 1'b1;
       end
    else begin
    out <= out+1;
    en_out <= 1'b0;
       end
end
endmodule

module Mod6Counter(clk, out, en_out, rst);
input clk, rst;
 output reg [3:0] out;
 output reg en_out;

always @(posedge clk or rst) begin

    if (rst) out<=4'b0000;
    else if (out == 4'b0101) begin
        out <= 4'b0000;
        en_out <= 1'b1;
    end
    else begin
    out <= out+1;
    en_out <= 1'b0;
    end
end
endmodule
</code>```

The test-bench for the generateSec is as follows:

```<code>`timescale 1ms / 1ps

 module generateSec_test;

// Inputs
reg clk;
reg reset;

// Outputs
wire [3:0] s1;
wire [3:0] s2;
wire min_en;

// Instantiate the Unit Under Test (UUT)
generateSec uut (
    .clk(clk),
    .reset(reset),
    .s1(s1),
    .s2(s2),
    .min_en(min_en)
);

initial begin
    clk = 0;
    forever #500 clk=~clk;
end

initial begin
    reset = 1;
    #550;
    reset =0;
end
endmodule
</code>```

I am pasting the screenshot of the output here for the problem mentioned above.
Output of Verilog simulation of generateSec-testbench

答:
With Verilog, a module port cannot drive a reg. SystemVerilog does allow this.

To stay with Verilog, in generateSec, change:

```<code> output reg [3:0] s1, s2;
 output reg min_en;
</code>```

To:

```<code> output [3:0] s1, s2;
 output min_en;
</code>```

Alternatively, if your tool-set supports SystemVerilog, then you can change the file extension from .v to .sv and you can leave it as output reg (output or output logic would be preferred). To the best of my knowledge, Xilinx's ISE only supports up to Verilog 2001. Xilinx's Vivado does.

As Serge metioned, @(posedge clk or rst) should be @(posedge clk or posedge rst).

Also en_out should be reset in Mod6Counter.

Body:
I want to design a seconds counter, which will count from 0 to 59, using Mod10COunter and Mod6Counter. I am trying to test the output using a testbench. The clock generated is perfect. However, the output is always 'X'. This is the code for the seconds counter.

module generateSec(clk, reset, s1, s2, min_en);
input wire clk, reset;
 output reg [3:0] s1, s2;
 output reg min_en;

 wire enable;
 Mod10Counter sec1 (.clk(clk), .out(s1), .en_out(enable), .rst(reset));
 Mod6Counter sec2 (.clk(enable), .out(s2), .en_out(min_en), .rst(reset));
endmodule

I have written the modules used as below.

module Mod10Counter(clk, out, en_out, rst);
input clk, rst;
output reg [3:0] out;
output reg en_out;

always @(posedge clk or rst) begin

    if (rst) begin
        out<=4'b0000;
        en_out<=1'b0;
        end
    else if (out == 4'b1001) begin
        out <= 4'b0000;
        en_out <= 1'b1;
       end
    else begin
    out <= out+1;
    en_out <= 1'b0;
       end
end
endmodule

module Mod6Counter(clk, out, en_out, rst);
input clk, rst;
 output reg [3:0] out;
 output reg en_out;

always @(posedge clk or rst) begin

    if (rst) out<=4'b0000;
    else if (out == 4'b0101) begin
        out <= 4'b0000;
        en_out <= 1'b1;
    end
    else begin
    out <= out+1;
    en_out <= 1'b0;
    end
end
endmodule

The test-bench for the generateSec is as follows:

`timescale 1ms / 1ps

 module generateSec_test;

// Inputs
reg clk;
reg reset;

// Outputs
wire [3:0] s1;
wire [3:0] s2;
wire min_en;

// Instantiate the Unit Under Test (UUT)
generateSec uut (
    .clk(clk),
    .reset(reset),
    .s1(s1),
    .s2(s2),
    .min_en(min_en)
);

initial begin
    clk = 0;
    forever #500 clk=~clk;
end

initial begin
    reset = 1;
    #550;
    reset =0;
end
endmodule

I am pasting the screenshot of the output here for the problem mentioned above.
Output of Verilog simulation of generateSec-testbench

Body:
With Verilog, a module port cannot drive a reg. SystemVerilog does allow this.

To stay with Verilog, in generateSec, change:

 output reg [3:0] s1, s2;
 output reg min_en;

To:

 output [3:0] s1, s2;
 output min_en;

Alternatively, if your tool-set supports SystemVerilog, then you can change the file extension from .v to .sv and you can leave it as output reg (output or output logic would be preferred). To the best of my knowledge, Xilinx's ISE only supports up to Verilog 2001. Xilinx's Vivado does.

As Serge metioned, @(posedge clk or rst) should be @(posedge clk or posedge rst).

Also en_out should be reset in Mod6Counter.


问:
Render razor page with RazorViewToStringRenderer and ServiceStack
I'm trying to render a razor page to send it as an email template. I'm adding the views on a Razor library and trying to render these from a ServiceStack project using this class. I'm getting the following error:

```<code>Application startup exception: System.AggregateException: One or more errors occurred. (Unable to find view '/Test.cshtml'. The following locations were searched:
/Test.cshtml)
---> System.InvalidOperationException: Unable to find view '/Test.cshtml'. The following locations were searched:
/Test.cshtml
 at web.RazorTemplates.RazorViewToStringRenderer.FindView(ActionContext actionContext, String viewName) in /Users/herber/Documents/repos/tests/web/web.RazorTemplates/RazorViewToStringRenderer.cs:line 86
 at web.RazorTemplates.RazorViewToStringRenderer.RenderViewToStringAsync[TModel](String viewName, TModel model) in /Users/herber/Documents/repos/tests/web/web.RazorTemplates/RazorViewToStringRenderer.cs:line 39
 --- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at web.AppHost.Configure(Container container) in /Users/herber/Documents/repos/tests/ss-razor-library/web/web/Startup.cs:line 65
at ServiceStack.ServiceStackHost.Init() in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\ServiceStackHost.cs:line 282
at ServiceStack.NetCoreAppHostExtensions.UseServiceStack(IApplicationBuilder app, AppHostBase appHost) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\AppHostBase.NetCore.cs:line 333
at web.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in /Users/herber/Documents/repos/tests/ss-razor-library/web/web/Startup.cs:line 44
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication()
    crit: Microsoft.AspNetCore.Hosting.WebHost[6]
    Application startup exception
    System.AggregateException: One or more errors occurred. (Unable to find view '/Test.cshtml'. The following locations were searched:
    /Test.cshtml)
    ---> System.InvalidOperationException: Unable to find view '/Test.cshtml'. The following locations were searched:
    /Test.cshtml
</code>```

The repo can be found here. Just for testing purpose I'm trying to render the template form the app Startup class.

I can render the template from a regular .net core app but not from a ServiceStack app. The repo for a working example on a regular .net core app can be found here. The render is performed on index page

答:
These examples are not the same, you're rendering it from an MVC Controller:

```<code>public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    private readonly IRazorViewToStringRenderer _razorRenderer;

    public IndexModel(ILogger<IndexModel> logger, IRazorViewToStringRenderer razorRenderer)
    {
        _logger = logger;
        _razorRenderer = razorRenderer;
    }

    public void OnGet()
    {
        var body =  _razorRenderer.RenderViewToStringAsync("/Test.cshtml",new TestModel{Message = "World"}).Result;
        Console.WriteLine(body);
    }
}
</code>```

vs On Startup before the App has been initialized:

```<code>public override void Configure(Container container)
{
    SetConfig(new HostConfig
    {
        DefaultRedirectPath = "/metadata",
        DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)
    });

    var razorRenderer = container.Resolve<IRazorViewToStringRenderer>();
    var body =  razorRenderer.RenderViewToStringAsync("/Test.cshtml",new TestModel()).Result;
    Console.WriteLine(body);
}
</code>```

Since you're trying to use MVC's Razor implementation instead of ServiceStack.Razor you should be rendering it inside an MVC Controller or Razor page, not a ServiceStack AppHost or Service which has its own Razor implementation for usage in ServiceStack Services that uses its own stand-alone Razor APIs. If you're interested in using ServiceStack.Razor refer to the razor project template for a valid configuration.

Although since it's simpler, cleaner & more flexible than Razor & actually designed to be used in a stand-alone Sandbox, you should also consider ServiceStack #Script for rendering stand-alone templates, here's a rendering Email template example.

Body:
I'm trying to render a razor page to send it as an email template. I'm adding the views on a Razor library and trying to render these from a ServiceStack project using this class. I'm getting the following error:

Application startup exception: System.AggregateException: One or more errors occurred. (Unable to find view '/Test.cshtml'. The following locations were searched:
/Test.cshtml)
---> System.InvalidOperationException: Unable to find view '/Test.cshtml'. The following locations were searched:
/Test.cshtml
 at web.RazorTemplates.RazorViewToStringRenderer.FindView(ActionContext actionContext, String viewName) in /Users/herber/Documents/repos/tests/web/web.RazorTemplates/RazorViewToStringRenderer.cs:line 86
 at web.RazorTemplates.RazorViewToStringRenderer.RenderViewToStringAsync[TModel](String viewName, TModel model) in /Users/herber/Documents/repos/tests/web/web.RazorTemplates/RazorViewToStringRenderer.cs:line 39
 --- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at web.AppHost.Configure(Container container) in /Users/herber/Documents/repos/tests/ss-razor-library/web/web/Startup.cs:line 65
at ServiceStack.ServiceStackHost.Init() in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\ServiceStackHost.cs:line 282
at ServiceStack.NetCoreAppHostExtensions.UseServiceStack(IApplicationBuilder app, AppHostBase appHost) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\AppHostBase.NetCore.cs:line 333
at web.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in /Users/herber/Documents/repos/tests/ss-razor-library/web/web/Startup.cs:line 44
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication()
    crit: Microsoft.AspNetCore.Hosting.WebHost[6]
    Application startup exception
    System.AggregateException: One or more errors occurred. (Unable to find view '/Test.cshtml'. The following locations were searched:
    /Test.cshtml)
    ---> System.InvalidOperationException: Unable to find view '/Test.cshtml'. The following locations were searched:
    /Test.cshtml

The repo can be found here. Just for testing purpose I'm trying to render the template form the app Startup class.

I can render the template from a regular .net core app but not from a ServiceStack app. The repo for a working example on a regular .net core app can be found here. The render is performed on index page

Body:
These examples are not the same, you're rendering it from an MVC Controller:

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    private readonly IRazorViewToStringRenderer _razorRenderer;

    public IndexModel(ILogger<IndexModel> logger, IRazorViewToStringRenderer razorRenderer)
    {
        _logger = logger;
        _razorRenderer = razorRenderer;
    }

    public void OnGet()
    {
        var body =  _razorRenderer.RenderViewToStringAsync("/Test.cshtml",new TestModel{Message = "World"}).Result;
        Console.WriteLine(body);
    }
}

vs On Startup before the App has been initialized:

public override void Configure(Container container)
{
    SetConfig(new HostConfig
    {
        DefaultRedirectPath = "/metadata",
        DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)
    });

    var razorRenderer = container.Resolve<IRazorViewToStringRenderer>();
    var body =  razorRenderer.RenderViewToStringAsync("/Test.cshtml",new TestModel()).Result;
    Console.WriteLine(body);
}

Since you're trying to use MVC's Razor implementation instead of ServiceStack.Razor you should be rendering it inside an MVC Controller or Razor page, not a ServiceStack AppHost or Service which has its own Razor implementation for usage in ServiceStack Services that uses its own stand-alone Razor APIs. If you're interested in using ServiceStack.Razor refer to the razor project template for a valid configuration.

Although since it's simpler, cleaner & more flexible than Razor & actually designed to be used in a stand-alone Sandbox, you should also consider ServiceStack #Script for rendering stand-alone templates, here's a rendering Email template example.


问:
Mono in linux & windows
Is there any difference in performance when running two executables with mono in linux, if:

1) the one executable has been compiled from c# source code previously in windows (e.g.VS).

2) the other executable has been compiled from the same source with gmcs in linux.

答: I don't think there is any direct performance difference when running same application on Mono in Linux and Windows. There is an indirect performance difference is possible. By indirect I mean performance difference of mono on Linux and Windows.</p>

OwnerDisplayName: wilsonlarg

Title: Mono in linux & windows

LastEditorDisplayName: wilsonlarg

OwnerDisplayName: Sharique


问:
Why isn't the link between CSS and HTML working?
I'm using flask on atom editor to create a website. In the link I'm referring to the right path where the CSS file is placed, and still when I try loading the page I get it without CSS. I tried changing paths several times it still wouldn't work. After inspecting the web page I noticed an Error 404 file not found referring the CSS file, any ideas? Below is the code:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Flask App</title>
    <link rel="stylesheet"  href="/app4/css/main.css">
  </head>
  <body>
    <header>
      <div class="container">
        <h1 class="logo">Ardit's web app </h1>
        <strong><nav>
          <ul class="menu">
            <li><a href="{{ url_for('home') }}" > Home</a></li>
            <li><a href="{{ url_for('about') }}" > About</a></li>
          </ul>
        </nav></strong>
      </div>
    </header>
    <div class ="container">
      {%block content%}
      {%endblock%}
    </div>
  </body>
  </html>
</code>```

答:
While I don't know which directory is the root of the web server you are running this on (which has made it somewhat harder for me to give a specific answer with confidence that it is correct), you could try a relative path, like:

```<code><link rel="stylesheet"  href="./app4/css/main.css"> <!-- '/' changed to './' -->
</code>```

If the root of your server is the "app4" directory, then you could try

```<code><link rel="stylesheet"  href="/css/main.css"> <!-- '/app4' removed -->
</code>```

I hope this helps.

Body:
I'm using flask on atom editor to create a website. In the link I'm referring to the right path where the CSS file is placed, and still when I try loading the page I get it without CSS. I tried changing paths several times it still wouldn't work. After inspecting the web page I noticed an Error 404 file not found referring the CSS file, any ideas? Below is the code:

<!DOCTYPE html>

    <title>Flask App</title>
    <link rel="stylesheet"  href="/app4/css/main.css">

Ardit's web app

 Home

 About

      {%block content%}
      {%endblock%}

Body:
While I don't know which directory is the root of the web server you are running this on (which has made it somewhat harder for me to give a specific answer with confidence that it is correct), you could try a relative path, like:

<link rel="stylesheet"  href="./app4/css/main.css"> <!-- '/' changed to './' -->

If the root of your server is the "app4" directory, then you could try

<link rel="stylesheet"  href="/css/main.css"> <!-- '/app4' removed -->

I hope this helps.


问:
AWS DynamoDb - Updating a specific map in list (.NET)
I have an attribute called "Categories" which contains a list of maps. I would like to be able to update just a single one of these maps using its unique id. I have structured my data as follows:

```<code>"EstablishmentID": "12345abc",
"Categories": [
{
  "408eec12-2415-45d3-b703-b8ba0d55261c": {
    "CategoryName": "Cat11",
    "CategoryVisible": true
  }
},
{
  "586a95ab-e39d-4711-8770-f60dedcf6059": {
    "CategoryName": "Cat2",
    "CategoryVisible": true
  }
}
]
</code>```

When I want to update one of these categories, I use a SET update expression and (to my knowledge) I am inputting the document path correctly. Here is my code for the update expression:

```<code>UpdateItemRequest request = new UpdateItemRequest
        {
            TableName = "Menu",
            Key = new Dictionary<string, AttributeValue> { { "EstablishmentID", new AttributeValue { S = establishmentID.ToString() } } },
            ExpressionAttributeNames = new Dictionary<string, string>
            {
                {"#C", "Categories"},
                {"#I", category.CategoryID.ToString()}
            },
            ExpressionAttributeValues = new Dictionary<string, AttributeValue>
            {
                {":CategoryToUpdate", new AttributeValue{M=values } }
            },
            UpdateExpression = "SET #C.#I = :CategoryToUpdate"

        };
</code>```

When I try to run my update I get the following error:

The document path provided in the update expression is invalid for update

To me this seems that is not able to find the object Categories => [categoryID]. Does anyone know what I might be missing with regards to being able to find my specific category in the list.

Thanks in advance.
Lee

答:
You can't use a list and query like this. #C.#I would be referencing Categories.408eec12-2415-45d3-b703-b8ba0d55261c. Change your format to this:

```<code>"EstablishmentID": "12345abc",
"Categories": {
  "408eec12-2415-45d3-b703-b8ba0d55261c": {
    "CategoryName": "Cat11",
    "CategoryVisible": true
  },
  "586a95ab-e39d-4711-8770-f60dedcf6059": {
    "CategoryName": "Cat2",
    "CategoryVisible": true
  }
}
</code>```

Then your query should work.

Body:
I have an attribute called "Categories" which contains a list of maps. I would like to be able to update just a single one of these maps using its unique id. I have structured my data as follows:

"EstablishmentID": "12345abc",
"Categories": [
{
  "408eec12-2415-45d3-b703-b8ba0d55261c": {
    "CategoryName": "Cat11",
    "CategoryVisible": true
  }
},
{
  "586a95ab-e39d-4711-8770-f60dedcf6059": {
    "CategoryName": "Cat2",
    "CategoryVisible": true
  }
}
]

When I want to update one of these categories, I use a SET update expression and (to my knowledge) I am inputting the document path correctly. Here is my code for the update expression:

UpdateItemRequest request = new UpdateItemRequest
        {
            TableName = "Menu",
            Key = new Dictionary<string, AttributeValue> { { "EstablishmentID", new AttributeValue { S = establishmentID.ToString() } } },
            ExpressionAttributeNames = new Dictionary<string, string>
            {
                {"#C", "Categories"},
                {"#I", category.CategoryID.ToString()}
            },
            ExpressionAttributeValues = new Dictionary<string, AttributeValue>
            {
                {":CategoryToUpdate", new AttributeValue{M=values } }
            },
            UpdateExpression = "SET #C.#I = :CategoryToUpdate"

        };

When I try to run my update I get the following error:

The document path provided in the update expression is invalid for update

To me this seems that is not able to find the object Categories => [categoryID]. Does anyone know what I might be missing with regards to being able to find my specific category in the list.

Thanks in advance.
Lee

Body:
You can't use a list and query like this. #C.#I would be referencing Categories.408eec12-2415-45d3-b703-b8ba0d55261c. Change your format to this:

"EstablishmentID": "12345abc",
"Categories": {
  "408eec12-2415-45d3-b703-b8ba0d55261c": {
    "CategoryName": "Cat11",
    "CategoryVisible": true
  },
  "586a95ab-e39d-4711-8770-f60dedcf6059": {
    "CategoryName": "Cat2",
    "CategoryVisible": true
  }
}

Then your query should work.


问:
React Popover 3rd-Party Out-Of-Window-View Problem
I'm looking for some accommodating a large 3rd-party software for a 1st-party concern.

I have a Popover,

With 3rd-party GUI that is along the window's right-side,

That throws Warning: findDOMNode is deprecated in StrictMode.

I'd fix it if I could.

Normally, the Popover opening accommodates the window-view,

But this Popover extends past the right-side.

But-the-but, when I resize the window then the Popover fits itself back inside.

What is going on here?

Because, I can't figure out how to: window.location.reload() or id.hide().show() without wiping the React.Function.Component.

Which the Popover needs because I've been told that React.Class.Component doesn't work with React-Hooks.

Again - what is going on here? So I can fix it.

答:
So I think I know what's going on now.

The 3rd-party's React component isn't loaded yet until the Functional Popover Component presents it. This causes the findDOMNode warning to trigger because this component isn't hydrated on-the-reference yet and because the Popover is a Functional Component which does not work with findDomNode.

But, the real reason the React component falls-outside-the-window seems caused by placement before React hydration. And as I understand it, the 3rd-party component is server-side rendered which is why it has to be hydrated by them.

Thanks everyone for looking at this.


问:
How to match the exact number of digits with regular expression in Javascript
In Javascript, what I have done is the following:

var matched = searched.match(/\d{7}/)

It works great if searched is 1234567 or XYZ1234567. Both return 1234567, which is good. 123 and XYZ123 return null, which is expected.

But one condition fails when searched is 12345678 or XYZ12345678. I would like both to return null because I look for an exact 7 digit match. They both return 2345678 instead.

/\d{7}$/ does not work either.

Can someone please advise?

Thank you

答:
You may use a lookaround based regex. Lookbehind adoption in browsers is gaining momentum, Firefox supports lookbehinds in regexps since June 30, 2020.

Use

```<code> /(?<!\d)\d{7}(?!\d)/
</code>```

Or, to find all occurrences,

```<code>/(?<!\d)\d{7}(?!\d)/g
</code>```

See the regex demo

The (?<!\d) negative lookbehind matches any position not immediately preceded with a digit, \d{7} matches seven digits and (?!\d) negative lookahead requires no digit immediately on the right.

const values = ['1234567A', 'XYZ1234567A', '12345678', 'XYZ12345678'];
const regex = /(?<!\d)\d{7}(?!\d)/g;
for (let val of values) {
  console.log(val, '\nMatch found:',
       /(?<!\d)\d{7}(?!\d)/.test(val), '\nMatch value: ',
       Array.from(val.matchAll(regex), m => m[0])
  )
}```
</div>
</div>
</p>
<p>Output:</p>
```1234567A
Match found: true
Match value:  [
  "1234567"
]
XYZ1234567A
Match found: true
Match value:  [
  "1234567"
]
12345678
Match found: false
Match value:  []
XYZ12345678
Match found: false
Match value:  []
```

Body:
You may use a lookaround based regex. Lookbehind adoption in browsers is gaining momentum, Firefox supports lookbehinds in regexps since June 30, 2020.

Use

 /(?<!\d)\d{7}(?!\d)/

Or, to find all occurrences,

/(?<!\d)\d{7}(?!\d)/g

See the regex demo

The (?<!\d) negative lookbehind matches any position not immediately preceded with a digit, \d{7} matches seven digits and (?!\d) negative lookahead requires no digit immediately on the right.

const values = ['1234567A', 'XYZ1234567A', '12345678', 'XYZ12345678'];
const regex = /(?<!\d)\d{7}(?!\d)/g;
for (let val of values) {
  console.log(val, '\nMatch found:',
       /(?<!\d)\d{7}(?!\d)/.test(val), '\nMatch value: ',
       Array.from(val.matchAll(regex), m => m[0])
  )
}

Output:

1234567A
Match found: true
Match value:  [
  "1234567"
]
XYZ1234567A
Match found: true
Match value:  [
  "1234567"
]
12345678
Match found: false
Match value:  []
XYZ12345678
Match found: false
Match value:  []