问:
How to solve CORS policy for HTTP status not ok?
I'm getting the following error :

```<code>Access to fetch at 'http://localhost:8080/users/find-all/0' from origin 'http://localhost:3000/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
</code>```

I know that there are a lot of questions of this type but I just can't solve the problem.
The backend is built with spring boot and the frontend is based on ReactJS.

```<code>@GetMapping("/find-all/{page}")
public PaginatedResultDto<UserDto> findAllPaginated(@PathVariable("page") int page, @RequestParam(defaultValue = NUMBER_OF_ELEMENTS) int numberOfElements) {
    Pageable pageable = PageRequest.of(page, numberOfElements);
    return getBaseFacade().findAllPaginated(pageable);
}
</code>```

And

```<code>getPaginatedResults = (pageIndex, resultsPerPage, endpoint, jwt) => {
    const resultsPerPagePath = resultsPerPage !== undefined ? "?numberOfElements=" + resultsPerPage : "";
    const endpointPath = BASE_URL + "/" + endpoint + "/find-all/" + pageIndex + resultsPerPagePath;
    return fetch(endpointPath, {
        method: "GET",
        headers: new Headers({
            "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
            "Authorization": "Bearer " + jwt
        })
    }).then( .. some error handling here )
</code>```

I've configured WebSecurityConfigurerAdapter in this way:

```<code>protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();

    http.authorizeRequests()
            .antMatchers("/users/login").permitAll()
            .antMatchers("/users/find-all/*").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
</code>```

And I have a WebMvcConfigurer too :

```<code>public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedMethods("*")
            .allowedHeaders("Authorization", "Content-Type");
}
</code>```

But I just can't solve this problem.. I've tried every solution from stack overflow but it didn't worked.

答:
You have to create CorsConfigurationSource bean, example is as below:

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(
                "http://localhost:8080",
                "http://localhost:4200",
                "https://localhost:4200"
                )
        );
        configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT", "OPTIONS"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(
                Arrays.asList(
                        "Access-Control-Allow-Headers",
                        "Access-Control-Allow-Origin",
                        "Access-Control-Request-Method",
                        "Access-Control-Request-Headers",
                        "Origin", "Cache-Control",
                        "Content-Type",
                        "Authorization"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
```

<p>Later in <code>*[Web/Resource]ServerConfigurerAdapter</code> add following code</p>

<pre class="lang-java prettyprint-override"><code>    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(corsConfigurationSource())
                .and()
         ...// Please complete this line to compile
    }
</code>```

Body:
I'm getting the following error :

Access to fetch at 'http://localhost:8080/users/find-all/0' from origin 'http://localhost:3000/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I know that there are a lot of questions of this type but I just can't solve the problem.
The backend is built with spring boot and the frontend is based on ReactJS.

@GetMapping("/find-all/{page}")
public PaginatedResultDto<UserDto> findAllPaginated(@PathVariable("page") int page, @RequestParam(defaultValue = NUMBER_OF_ELEMENTS) int numberOfElements) {
    Pageable pageable = PageRequest.of(page, numberOfElements);
    return getBaseFacade().findAllPaginated(pageable);
}

And

getPaginatedResults = (pageIndex, resultsPerPage, endpoint, jwt) => {
    const resultsPerPagePath = resultsPerPage !== undefined ? "?numberOfElements=" + resultsPerPage : "";
    const endpointPath = BASE_URL + "/" + endpoint + "/find-all/" + pageIndex + resultsPerPagePath;
    return fetch(endpointPath, {
        method: "GET",
        headers: new Headers({
            "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
            "Authorization": "Bearer " + jwt
        })
    }).then( .. some error handling here )

I've configured WebSecurityConfigurerAdapter in this way:

protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();

    http.authorizeRequests()
            .antMatchers("/users/login").permitAll()
            .antMatchers("/users/find-all/*").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

And I have a WebMvcConfigurer too :

public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedMethods("*")
            .allowedHeaders("Authorization", "Content-Type");
}

But I just can't solve this problem.. I've tried every solution from stack overflow but it didn't worked.

Body:
You have to create CorsConfigurationSource bean, example is as below:

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(
                "http://localhost:8080",
                "http://localhost:4200",
                "https://localhost:4200"
                )
        );
        configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT", "OPTIONS"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(
                Arrays.asList(
                        "Access-Control-Allow-Headers",
                        "Access-Control-Allow-Origin",
                        "Access-Control-Request-Method",
                        "Access-Control-Request-Headers",
                        "Origin", "Cache-Control",
                        "Content-Type",
                        "Authorization"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

Later in *[Web/Resource]ServerConfigurerAdapter add following code

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(corsConfigurationSource())
                .and()
         ...// Please complete this line to compile
    }


来源: stackexchange

问:
How to add mappings by namespace in Fluent NHibernate
In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way.

The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings:

```<code>    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>())
    .Mappings(m => m.FluentMappings.Add<UserClassMap>()
</code>```

If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace(). Is there a way to do this?

答:
There is no way to do this. I recommend separating the namespaces out into separate projects. Remember:

Separate namespaces, same project when logical separation makes sense.
Separate namespaces, separate projects when physical separation makes sense.

In this case, since you can't separate by namespace in nhibernate mappings, physical separation makes sense. You can, however, get around this with with fluent automaps that use a .Where or a ShouldMap configuration. Look up fluent automaps and see if that can get you where you want to be.

ContentLicense: CC BY-SA 3.0

Body:
In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way.

The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings:

    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>())
    .Mappings(m => m.FluentMappings.Add<UserClassMap>()

If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace(). Is there a way to do this?


问:
Question marks instead of non-ASCII symbols in Ruby gets using Windows terminal
I am new to Ruby and writing simple Ruby (without Rails) program, basically just one script file, and seem unable to get user entered Cyrillic text, e.g.

```<code>puts gets.chomp
</code>```

returns ??? instead of жжж, but works just fine with English letters.

puts gets.chomp.encoding and ruby -e 'p Encoding.default_external' return UTF-8.

On this test

```<code>a = gets.chomp
puts a == 'жжж'
puts a == '???'
</code>```

жжж input produced

```<code>false
true
</code>```

So they are stored as question marks.

I'm using Windows 10 command prompt (or working in RubyMine, which uses it anyway). Problem persists in pry and irb.

I've tried putting #coding: UTF-8 at the beginning of the source file, didn't help. I've seen advise to edit some configuration files in Ruby on Rails project, but this is not my case.

Is there any simple solution?

答:
I've found a partial solution, maybe someone will find it helpful.

Change system locale in your Windows to Ukrainian/Belarusian/Russian etc (Control Panel -> Date and Time - > Change date and time -> Change calendar settings -> Administrative -> Change system locale).

Now you've got hexadecimal \xNN\ output for Cyrillic input instead of question marks (like that: \xA2\xE7\xB4). I've found out that it's Windows encoding and by trial and error found the one that suits me - CP866, however, it lacks some characters. So passed string wasn't actually UTF, and we need to force its real encoding explicitly.

I've written this method to get a real UTF-8 string from my gets input, which converts CP866 string to UTF-8 char by char (require 'iconv').

```<code>def decode(string)
 string.force_encoding('CP866')
 Iconv.iconv('utf-8','ibm866', string).join('')
end
</code>```

Another workaround I'm using is letting user enter UTF input in default notepad app, and then read it from the file, after user pressed some key:

```<code>system %{cmd /c "start #{file_to_open}"}
gets
input = File.open('file_to_open').read
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to Ruby and writing simple Ruby (without Rails) program, basically just one script file, and seem unable to get user entered Cyrillic text, e.g.

puts gets.chomp

returns ??? instead of жжж, but works just fine with English letters.

puts gets.chomp.encoding and ruby -e 'p Encoding.default_external' return UTF-8.

On this test

a = gets.chomp
puts a == 'жжж'
puts a == '???'

жжж input produced

false
true

So they are stored as question marks.

I'm using Windows 10 command prompt (or working in RubyMine, which uses it anyway). Problem persists in pry and irb.

I've tried putting #coding: UTF-8 at the beginning of the source file, didn't help. I've seen advise to edit some configuration files in Ruby on Rails project, but this is not my case.

Is there any simple solution?

Body:
I've found a partial solution, maybe someone will find it helpful.

Change system locale in your Windows to Ukrainian/Belarusian/Russian etc (Control Panel -> Date and Time - > Change date and time -> Change calendar settings -> Administrative -> Change system locale).

Now you've got hexadecimal \xNN\ output for Cyrillic input instead of question marks (like that: \xA2\xE7\xB4). I've found out that it's Windows encoding and by trial and error found the one that suits me - CP866, however, it lacks some characters. So passed string wasn't actually UTF, and we need to force its real encoding explicitly.

I've written this method to get a real UTF-8 string from my gets input, which converts CP866 string to UTF-8 char by char (require 'iconv').

def decode(string)
 string.force_encoding('CP866')
 Iconv.iconv('utf-8','ibm866', string).join('')
end

Another workaround I'm using is letting user enter UTF input in default notepad app, and then read it from the file, after user pressed some key:

system %{cmd /c "start #{file_to_open}"}
gets
input = File.open('file_to_open').read


问:
Is it better to write the same lines of code, or to recall the same function?
It's true that writing the same lines of code is not good programming, and would be better this approach, but does this bring to problems of any kind? will the variables created still exist, so am I wasting memory?

What do actually happens when I recall foo() ?

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

int foo(){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
    unsigned int choice;
    scanf("%d",&choice);
    while (choice!=3){
        if (choice==1){
            // stuff
        } else if (choice==2){
            // stuff
        } else {
            printf("\nError, try again..\n");
            foo();          // what happens? does this bring to problems of any kind? will the variables created still exist, so am I wasting memory?
        }
    }
    printf("\nEnd of run.\n");
}
</code>```

or

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

int foo(){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
    unsigned int choice;
    scanf("%d",&choice);
    while (choice!=3){
        if (choice==1){
            // stuff
        } else if (choice==2){
            // stuff
        } else {
            printf("\nError, try again..\n");
            printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
            printf("\n> ");
            scanf("%d",&choice);
        }
    }
    printf("\nEnd of run.\n");
}
</code>```

What's the best approach? I have also read that calling main() for example, is not good programming.

答:
I'm assuming that the loop is supposed to run until the user enters '3'. The main problem then seems to be that you want the usage printed once at the beginning, but then again for each invalid input. One way of doing this, without changing too much of your code, would be like this:

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

void print_usage(void){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
}

int foo(){
    print_usage();
    unsigned int choice;

    do {
        scanf("%d",&choice);

        if (choice==1){
            // stuff
        } else if (choice==2){
            // stuff
        } else if(choice!=3){
            printf("\nError, try again..\n");
            print_usage();
        }
    } while (choice!=3);

    printf("\nEnd of run.\n");
}
</code>```

By doing it like this, scanf() will be executed in each iteration (so the user can enter '1' or '2' as often as they like), and the problem with the duplicated code is solved be putting that part into a small separate function.

Please note that this code doesn't actually behave the same way as either of your versions. It works like i guess you would probably want it to work.

Body:
It's true that writing the same lines of code is not good programming, and would be better this approach, but does this bring to problems of any kind? will the variables created still exist, so am I wasting memory?

What do actually happens when I recall foo() ?

#include <stdio.h>

int foo(){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
    unsigned int choice;
    scanf("%d",&choice);
    while (choice!=3){
        if (choice==1){
            // stuff
        } else if (choice==2){
            // stuff
        } else {
            printf("\nError, try again..\n");
            foo();          // what happens? does this bring to problems of any kind? will the variables created still exist, so am I wasting memory?
        }
    }
    printf("\nEnd of run.\n");
}

or

#include <stdio.h>

int foo(){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
    unsigned int choice;
    scanf("%d",&choice);
    while (choice!=3){
        if (choice==1){
            // stuff
        } else if (choice==2){
            // stuff
        } else {
            printf("\nError, try again..\n");
            printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
            printf("\n> ");
            scanf("%d",&choice);
        }
    }
    printf("\nEnd of run.\n");
}

What's the best approach? I have also read that calling main() for example, is not good programming.

Body:
I'm assuming that the loop is supposed to run until the user enters '3'. The main problem then seems to be that you want the usage printed once at the beginning, but then again for each invalid input. One way of doing this, without changing too much of your code, would be like this:

#include <stdio.h>

void print_usage(void){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
}

int foo(){
    print_usage();
    unsigned int choice;

    do {
        scanf("%d",&choice);

        if (choice==1){
            // stuff
        } else if (choice==2){
            // stuff
        } else if(choice!=3){
            printf("\nError, try again..\n");
            print_usage();
        }
    } while (choice!=3);

    printf("\nEnd of run.\n");
}

By doing it like this, scanf() will be executed in each iteration (so the user can enter '1' or '2' as often as they like), and the problem with the duplicated code is solved be putting that part into a small separate function.

Please note that this code doesn't actually behave the same way as either of your versions. It works like i guess you would probably want it to work.


问:
MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB
I want to create a table of 325 column:

```<code>CREATE TABLE NAMESCHEMA.NAMETABLE
(
      ROW_ID TEXT NOT NULL ,        //this is the primary key

324 column of these types:
      CHAR(1),
      DATE,
      DECIMAL(10,0),
      DECIMAL(10,7),
      TEXT,
      LONG,

) ROW_FORMAT=COMPRESSED;
</code>```

I replaced all the VARCHAR with the TEXT and i have added Barracuda in the my.ini file of MySQL, this is the attributes added:

```<code>innodb_file_per_table=1
innodb_file_format=Barracuda
innodb_file_format_check = ON
</code>```

but i still have this error:

```<code>Error Code: 1118
 Row size too large (> 8126). Changing some columns to TEXT or BLOB may help. In current row format, BLOB prefix of 0 bytes is stored inline.
</code>```

EDIT: I can't change the structure of the database because it's legacy application/system/database. The create of a new table, it's an export of the legacy database.

EDIT2: i wrote this question that is similar to others but inside there are some solution that i found on internet like VARCHAR and Barracuda, but i still have that problem so i decided to open a new question with already the classic answer inside for seeing if someone have other answers

答:
I was using XAMPP on Windows 10 and had this issue using PHPMyAdmin.

when I added  innodb_log_file_size = 500M and innodb_log_buffer_size = 800M to my my.ini file, MySQL would not start.

So I tried deleting ib_logfile0 and ib_logfile1 located in (C:\xampp\mysql\data) and this did not help at all.

luckily I could re-install (I needed to upgrade XAMPP anyway)

The simple solution in my case was to set innodb_strict_mode=0 in the my.ini file.

After this I was able to create the table.

STEPS:

Close XAMPP completely.

Edit the my.ini file (located in C:\xampp\mysql\data) add innodb_strict_mode=0 in the InnoDB section.

Start XAMPP and import the table again.

N.B complete these steps as ADMIN

Body:
I want to create a table of 325 column:

CREATE TABLE NAMESCHEMA.NAMETABLE
(
      ROW_ID TEXT NOT NULL ,        //this is the primary key

324 column of these types:
      CHAR(1),
      DATE,
      DECIMAL(10,0),
      DECIMAL(10,7),
      TEXT,
      LONG,

) ROW_FORMAT=COMPRESSED;

I replaced all the VARCHAR with the TEXT and i have added Barracuda in the my.ini file of MySQL, this is the attributes added:

innodb_file_per_table=1
innodb_file_format=Barracuda
innodb_file_format_check = ON

but i still have this error:

Error Code: 1118
 Row size too large (> 8126). Changing some columns to TEXT or BLOB may help. In current row format, BLOB prefix of 0 bytes is stored inline.

EDIT: I can't change the structure of the database because it's legacy application/system/database. The create of a new table, it's an export of the legacy database.

EDIT2: i wrote this question that is similar to others but inside there are some solution that i found on internet like VARCHAR and Barracuda, but i still have that problem so i decided to open a new question with already the classic answer inside for seeing if someone have other answers


问:
Reduce Team Foundation Server database space
I have some large projects hosted in Team Foundation Server 2010 Source Control. This projects are long time so many check-ins will occour and as we make check-ins the database grows up.

I'm afraid that size will be a problem in the future (including performance and backup space/upload time).

Is there some way to reduce this size (deleting old changesets or something else)?

答: For many files TFS stores a delta of the changes, not full copies every time you check-in. This can greatly reduce the size of the database. You may be worying abount a non-issue.</p>


问:
SQL Server: SELECT XML with Namespaces gives NULL Result
I want to load a XML File into SQL Server 2012 as a variable, one of the columns should contain the XML itself and the other columns should contain values from the XML elements.

My Issue is that I don't get an ERROR but also no record in my table, it just returned blank result

USE [testjrazt]
GO
DECLARE @doc XML
SELECT @doc = '<?xml version="1.0"?>
<SyncSalesOrder xmlns="http://schema.infor.com/InforOAGIS/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/2.12.x/InforOAGIS/BODs/SyncSalesOrder.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" releaseID="9.2" versionID="2.12.x">
    <ApplicationArea>
        <Sender>
            <LogicalID>lid://infor.ln.dach_nausveln1_200_2</LogicalID>
            <ComponentID>erp</ComponentID>
            <ConfirmationCode>OnError</ConfirmationCode>
        </Sender>
        <CreationDateTime>2019-12-02T15:47:42Z</CreationDateTime>
        <BODID>infor-nid:infor:200::AA0000008:?SalesOrder&verb=Sync</BODID>
    </ApplicationArea>
    <DataArea>
        <Sync>
            <TenantID>infor</TenantID>
            <AccountingEntityID>200</AccountingEntityID>
            <LocationID>
        </LocationID>
        <ActionCriteria>
            <ActionExpression actionCode="Add"/>
        </ActionCriteria>
    </Sync>
    <SalesOrder>
        --CUT FOR BETTER READABILITY
    </SalesOrder>
</DataArea>
</SyncSalesOrder>
'

--Inserting into COR_Outbox_Entry Tabelle -> I/O BOX
/*
INSERT INTO [dbo].[COR_OUTBOX_ENTRY]
           ([C_XML]
           ,[C_TENANT_ID]
           ,[C_MESSAGE_PRIORITY]
           ,[C_CREATED_DATE_TIME]
           ,[C_WAS_PROCESSED]
           ,[C_LOGICAL_ID])
*/
--Only SELECT to check if data get loaded from XML - BLANK RESULT
SELECT
    i_xml = CAST (@doc AS varbinary(max)),
    i_tenant_id = xdoc.value('(DataArea/Sync/TenantID)[1]','nvarchar(250)'), -- xpath /SyncSalesOrder/DataArea/Sync/TenantID
    --i_message_priority =xdoc.value('()[1]','int'),
    i_created_date_time = xdoc.value('(ApplicationArea/CreationDateTime)[1]','datetime'),
    --i_was_processed = xdoc.value('()[1]','int'),
    i_lid = xdoc.value('(ApplicationArea/Sender/LogicalID)[1]','nvarchar(250)')
FROM @doc.nodes('SyncSalesOrder') AS InputTable(xdoc)
```

答:
Here is how to do it. Your XML has a default namespace. It should be taken into account via WITH XMLNAMESPACES clause.

-- DDL and sample data population, start
DECLARE @doc XML =
N'<SyncSalesOrder xmlns="http://schema.infor.com/InforOAGIS/2"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/2.12.x/InforOAGIS/BODs/SyncSalesOrder.xsd"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema" releaseID="9.2"
                versionID="2.12.x">
    <ApplicationArea>
        <Sender>
            <LogicalID>lid://infor.ln.dach_nausveln1_200_2</LogicalID>
            <ComponentID>erp</ComponentID>
            <ConfirmationCode>OnError</ConfirmationCode>
        </Sender>
        <CreationDateTime>2019-12-02T15:47:42Z</CreationDateTime>
        <BODID>infor-nid:infor:200::AA0000008:?SalesOrder&verb=Sync</BODID>
    </ApplicationArea>
    <DataArea>
        <Sync>
            <TenantID>infor</TenantID>
            <AccountingEntityID>200</AccountingEntityID>
            <LocationID>
            </LocationID>
            <ActionCriteria>
                <ActionExpression actionCode="Add"/>
            </ActionCriteria>
        </Sync>
        <SalesOrder>--CUT FOR BETTER READABILITY</SalesOrder>
    </DataArea>
</SyncSalesOrder>';

DECLARE @COR_OUTBOX_ENTRY TABLE ([C_XML] XML
           ,[C_TENANT_ID] NVARCHAR(250)
           --,[C_MESSAGE_PRIORITY]
           ,[C_CREATED_DATE_TIME] DATETIME
           --,[C_WAS_PROCESSED]
           ,[C_LOGICAL_ID] NVARCHAR(250));
-- DDL and sample data population, end

;WITH XMLNAMESPACES (DEFAULT 'http://schema.infor.com/InforOAGIS/2')
INSERT INTO @COR_OUTBOX_ENTRY
           ([C_XML]
           ,[C_TENANT_ID]
           --,[C_MESSAGE_PRIORITY]
           ,[C_CREATED_DATE_TIME]
           --,[C_WAS_PROCESSED]
           ,[C_LOGICAL_ID])
SELECT  @doc AS i_xml
    , i_tenant_id = c.value('(DataArea/Sync/TenantID/text())[1]','nvarchar(250)')
--i_message_priority =xdoc.value('()[1]','int'),
    , i_created_date_time = c.value('(ApplicationArea/CreationDateTime/text())[1]','datetime')
--i_was_processed = xdoc.value('()[1]','int'),
    , i_lid = c.value('(ApplicationArea/Sender/LogicalID/text())[1]','nvarchar(250)')
FROM @doc.nodes('/SyncSalesOrder') AS t(c);

-- test
SELECT * FROM @COR_OUTBOX_ENTRY;
```

Body:
Here is how to do it. Your XML has a default namespace. It should be taken into account via WITH XMLNAMESPACES clause.

-- DDL and sample data population, start
DECLARE @doc XML =
N'<SyncSalesOrder xmlns="http://schema.infor.com/InforOAGIS/2"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/2.12.x/InforOAGIS/BODs/SyncSalesOrder.xsd"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema" releaseID="9.2"
                versionID="2.12.x">
    <ApplicationArea>
        <Sender>
            <LogicalID>lid://infor.ln.dach_nausveln1_200_2</LogicalID>
            <ComponentID>erp</ComponentID>
            <ConfirmationCode>OnError</ConfirmationCode>
        </Sender>
        <CreationDateTime>2019-12-02T15:47:42Z</CreationDateTime>
        <BODID>infor-nid:infor:200::AA0000008:?SalesOrder&amp;verb=Sync</BODID>
    </ApplicationArea>
    <DataArea>
        <Sync>
            <TenantID>infor</TenantID>
            <AccountingEntityID>200</AccountingEntityID>
            <LocationID>
            </LocationID>
            <ActionCriteria>
                <ActionExpression actionCode="Add"/>
            </ActionCriteria>
        </Sync>
        <SalesOrder>--CUT FOR BETTER READABILITY</SalesOrder>
    </DataArea>
</SyncSalesOrder>';

DECLARE @COR_OUTBOX_ENTRY TABLE ([C_XML] XML
           ,[C_TENANT_ID] NVARCHAR(250)
           --,[C_MESSAGE_PRIORITY]
           ,[C_CREATED_DATE_TIME] DATETIME
           --,[C_WAS_PROCESSED]
           ,[C_LOGICAL_ID] NVARCHAR(250));
-- DDL and sample data population, end

;WITH XMLNAMESPACES (DEFAULT 'http://schema.infor.com/InforOAGIS/2')
INSERT INTO @COR_OUTBOX_ENTRY
           ([C_XML]
           ,[C_TENANT_ID]
           --,[C_MESSAGE_PRIORITY]
           ,[C_CREATED_DATE_TIME]
           --,[C_WAS_PROCESSED]
           ,[C_LOGICAL_ID])
SELECT  @doc AS i_xml
    , i_tenant_id = c.value('(DataArea/Sync/TenantID/text())[1]','nvarchar(250)')
--i_message_priority =xdoc.value('()[1]','int'),
    , i_created_date_time = c.value('(ApplicationArea/CreationDateTime/text())[1]','datetime')
--i_was_processed = xdoc.value('()[1]','int'),
    , i_lid = c.value('(ApplicationArea/Sender/LogicalID/text())[1]','nvarchar(250)')
FROM @doc.nodes('/SyncSalesOrder') AS t(c);

-- test
SELECT * FROM @COR_OUTBOX_ENTRY;


问:
Why .NET framework project can be added as reference in .NET Standard 2.0 project?
While doing some conversion of .NET Framework 4.6.2 project into .NET Standard project, I noticed that I could add .NET Framework project reference in the .NET Standard project, which doesn't sound correct theoretically.

Why .NET framework project can be added as reference in .NET Standard 2.0 project?

答:
When you have .NET Standard project it is compiled against netstandard.dll. Both .NET Framework and .NET Core have netstandard.dll (which provides type-forwarding to mscorlib.dll or System.Runtime.dll). That is why you can use .NET Standard project both in .NET Core and .NET Framework.

So what happens when your .NET Standard project references .NET Framework project (which is compiled against mscorlib.dll)?

If you have references chain .NET Framework -> .NET Standard -> .NET Framework then there is no problem at all because at runtime you have mscorlib.dll with all required types.

But what about .NET Core -> .NET Standard -> .NET Framework references? At runtime you have only System.Runtime.dll. There is no problem with .NET Standard project because netstandard.dll will type-forward to System.Runtime.dll. But the trick is that .NET Core has also mscorlib.dll! And yes, it's also only type-forwarding to System.Runtime.dll types. And everything works. ...unless you will use some .NET Framework type which does not exist in System.Runtime.dll.

Further reading: .NET Framework Compatibility Shim


问:
Unexpected output when creating a JK Flip Flop module using an SR Flip Flop
I have written Verilog modules for SR Latch, SR Flip Flop (by instantiating the SR Latch module), and JK Flip Flop (by instantiating the SR Latch module). I'm using Xilinx Vivado 2019 version for simulation and viewing output waveforms. The SR Latch and SR Flip flop modules work just fine and I'm getting the proper output waveforms also. I tried creating a JK Flip Flop Module by instantiating the SR Latch Module. But, I just don't get the output waveforms. I don't know what is going wrong. I checked the Boolean expressions as well. Everything seems to be fine. Can someone please point out the error?

Here are the codes.

SR Latch Module

```<code>module sr_latch(s, r, q, qbar);
    input s, r;
    output q, qbar;
    nand(q, s, qbar);
    nand(qbar, r, q);
endmodule
</code>```

SR Flip Flop Module using the SR Latch

```<code>module sr_ff(s, r, clk, q, qbar);
    input s, r, clk;
    output q, qbar;
    reg t1, t2;
    always @(posedge clk)
        begin
            t1 <= !(clk & s);
            t2 <= !(clk & r);
        end
    sr_latch SRL(t1, t2, q, qbar);
endmodule
</code>```

JK Flip Flop using SR Latch

```<code>module jk_ff(j, k, clk, q, qbar);
    input j, k, clk;
    output q, qbar;
    reg t1, t2;
    always @(posedge clk)
        begin
            t1 <= !(clk & qbar & j);
            t2 <= !(clk & q & k);
        end
    sr_latch SRL(t2, t1, q, qbar);
endmodule
</code>```

JK Flip Flop Testbench

```<code>module jk_ff_tb();
    wire q, qbar;
    reg j, k, clk=1;
    integer i;
    jk_ff JKFF(j, k, clk, q, qbar);
    always #25 clk = !clk;

    initial
        begin
            for(i=0; i<4; i=i+1)
                begin
                    {j, k} <= i; #50;
                end
        $stop;
        end
endmodule
</code>```

答:
Your output is unknown (X) because your jk_ff model does not allow for proper initialization of the SR Latch.

Based on this simple schematic, you need to just implement the 2 NAND gates on the inputs to the SR latch:

This is one way, using continuous assignments:

```<code>module jk_ff (j, k, clk, q, qbar);
    input j, k, clk;
    output q, qbar;
    wire sn = clk & qbar & j;
    wire rn = clk & q    & k;
    sr_latch SRL (sn, rn, q, qbar);
endmodule
</code>```

This allows the output to become known.

Another way is to add 2 nand primitives.

Note that the JK Flip-flop can be constructed from an SR Latch, not an SR Flip-flop.

Body:
I have written Verilog modules for SR Latch, SR Flip Flop (by instantiating the SR Latch module), and JK Flip Flop (by instantiating the SR Latch module). I'm using Xilinx Vivado 2019 version for simulation and viewing output waveforms. The SR Latch and SR Flip flop modules work just fine and I'm getting the proper output waveforms also. I tried creating a JK Flip Flop Module by instantiating the SR Latch Module. But, I just don't get the output waveforms. I don't know what is going wrong. I checked the Boolean expressions as well. Everything seems to be fine. Can someone please point out the error?

Here are the codes.

SR Latch Module

module sr_latch(s, r, q, qbar);
    input s, r;
    output q, qbar;
    nand(q, s, qbar);
    nand(qbar, r, q);
endmodule

SR Flip Flop Module using the SR Latch

module sr_ff(s, r, clk, q, qbar);
    input s, r, clk;
    output q, qbar;
    reg t1, t2;
    always @(posedge clk)
        begin
            t1 <= !(clk & s);
            t2 <= !(clk & r);
        end
    sr_latch SRL(t1, t2, q, qbar);
endmodule

JK Flip Flop using SR Latch

module jk_ff(j, k, clk, q, qbar);
    input j, k, clk;
    output q, qbar;
    reg t1, t2;
    always @(posedge clk)
        begin
            t1 <= !(clk & qbar & j);
            t2 <= !(clk & q & k);
        end
    sr_latch SRL(t2, t1, q, qbar);
endmodule

JK Flip Flop Testbench

module jk_ff_tb();
    wire q, qbar;
    reg j, k, clk=1;
    integer i;
    jk_ff JKFF(j, k, clk, q, qbar);
    always #25 clk = !clk;

    initial
        begin
            for(i=0; i<4; i=i+1)
                begin
                    {j, k} <= i; #50;
                end
        $stop;
        end
endmodule

Body:
Your output is unknown (X) because your jk_ff model does not allow for proper initialization of the SR Latch.

Based on this simple schematic, you need to just implement the 2 NAND gates on the inputs to the SR latch:

This is one way, using continuous assignments:

module jk_ff (j, k, clk, q, qbar);
    input j, k, clk;
    output q, qbar;
    wire sn = clk & qbar & j;
    wire rn = clk & q    & k;
    sr_latch SRL (sn, rn, q, qbar);
endmodule

This allows the output to become known.

Another way is to add 2 nand primitives.

Note that the JK Flip-flop can be constructed from an SR Latch, not an SR Flip-flop.


问:
What does &H57 represent and how can I translate it for C#?
I'm trying to convert old VB.NET code into C# and I'm not sure about the current line and what it means really.

VB.NET:

```<code>Const REQUEST_EFI As Byte = &H57
</code>```

What would this be in c#?  I tried:

```<code>const byte request_efi = &H57;
</code>```

But it says

"H57 is not part of the current
  context".

First of all, how is &H57 a byte?  Second, it seems that the & operator has a different representation in this context aside from concatenation.  Third obviously being, how the heck do I re-write this for C#? lol.  Thanks!

答:
&H57 is a way to represent hex numbers in VB, so the C# equivalent would be:

```<code>const byte request_efi = 0x57;
</code>```

Body:
I'm trying to convert old VB.NET code into C# and I'm not sure about the current line and what it means really.

VB.NET:

Const REQUEST_EFI As Byte = &H57

What would this be in c#?  I tried:

const byte request_efi = &H57;

But it says

"H57 is not part of the current
  context".

First of all, how is &H57 a byte?  Second, it seems that the & operator has a different representation in this context aside from concatenation.  Third obviously being, how the heck do I re-write this for C#? lol.  Thanks!

Body:
&H57 is a way to represent hex numbers in VB, so the C# equivalent would be:

const byte request_efi = 0x57;


问:
Azure api: The value for one of the HTTP headers is not in the correct format. HeaderName: Content-Length
I am trying to call azure API "put range" function with postman.
I get result:

```<code><?xml version="1.0" encoding="utf-8"?>
<Error>
    <Code>InvalidHeaderValue</Code>
    <Message>The value for one of the HTTP headers is not in the correct format.
RequestId:b131385d-301a-0044-31fd-344678000000
Time:2020-05-28T14:35:45.0769047Z</Message>
    <HeaderName>Content-Length</HeaderName>
    <HeaderValue>9</HeaderValue>
</Error>
</code>```

My request has these headers:

```<code>x-ms-write:Update
Range:bytes=0-3
Content-Length:9
</code>```

Body includes:

some text

答:
If you notice, your Range header has only 4 bytes (0 - 3) however your content length is actually 9 bytes. This is probably the reason why you're getting this error.

Please change your Range header so that it sends 9 bytes.

Range:bytes=0-8

Or change your content length header to send only 4 bytes.

Body:
I am trying to call azure API "put range" function with postman.
I get result:

<?xml version="1.0" encoding="utf-8"?>
<Error>
    InvalidHeaderValue
    <Message>The value for one of the HTTP headers is not in the correct format.
RequestId:b131385d-301a-0044-31fd-344678000000
Time:2020-05-28T14:35:45.0769047Z</Message>
    <HeaderName>Content-Length</HeaderName>
    <HeaderValue>9</HeaderValue>
</Error>

My request has these headers:

x-ms-write:Update
Range:bytes=0-3
Content-Length:9

Body includes:

some text


问:
Using Generic swift enum in a protocol
I have case where I often scratch my head around, let's say I have a generic Manager class in a pod that can handle permission, and within the app, I want to be able to extend it to create more meaningful method name, aka to use with enum as parameter, to make its use more clear and less prone to mistake.

But it seems that you can't call private method when you create the extension elsewhere.

I'm sure there would be a more clean way with Generic/AssociatedValue or maybe my pattern is just wrong...

Here's the simplified version of it:

Class in the external pod:

```<code>public class FeatureDataManager {

    public static let shared = FeatureDataManager()

    private var permissionManager: PermissionManager!

    private init() {
        self.permissionManager = PermissionManager()
    }

    private getPermission(forFeature feature: String) -> Bool {
        return self.permissionManager.isEnable(feature)
    }
}
</code>```

and the extension in the app:

```<code>extension FeatureDataManager {
    enum FeatureType: String {
        case ads = "ads"
        case showBanner = "banner"
        case showFullScreenPub = "showFullScreenPub"
    }

    public func isPermissionEnable(forFeature feature: FeatureType) {
        // Does not compile, visibility issue
        self.getPermission(forFeature: feature.rawValue)
    }
}
</code>```

Clarification:

FeatureDataManager is a class in the Pod that is solely used to check for permissions in the form of String value across many app that are using importing it.

I wanted each single app using it, to define an extension that would have their own finite enum of their supported permissions. Let's say App A support Ads, but not App B. So I wanted to have a universal method that when you call featureManager.isPermissionEnable(.Ads), whenever app that is, the auto-complete would just offer the list of the supported permission for that app. Also, the goal of wrapping my string permission value into an enum is to be more bulletproof to mistake and easier refactoring if a name change, just have to change it in a single place.

答:
The private access control restricts the use of an entity :

Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file.

Access Control - The Swift Programming Language

If you want an entity accessible through class extension (in another file and in the same module/package) : use internal access control.

If you want an entity accessible through class extension (in another file and in another module/package) : use public access control.

Title: Using Generic swift enum in a protocol

Body:
I have case where I often scratch my head around, let's say I have a generic Manager class in a pod that can handle permission, and within the app, I want to be able to extend it to create more meaningful method name, aka to use with enum as parameter, to make its use more clear and less prone to mistake.

But it seems that you can't call private method when you create the extension elsewhere.

I'm sure there would be a more clean way with Generic/AssociatedValue or maybe my pattern is just wrong...

Here's the simplified version of it:

Class in the external pod:

public class FeatureDataManager {

    public static let shared = FeatureDataManager()

    private var permissionManager: PermissionManager!

    private init() {
        self.permissionManager = PermissionManager()
    }

    private getPermission(forFeature feature: String) -> Bool {
        return self.permissionManager.isEnable(feature)
    }
}

and the extension in the app:

extension FeatureDataManager {
    enum FeatureType: String {
        case ads = "ads"
        case showBanner = "banner"
        case showFullScreenPub = "showFullScreenPub"
    }

    public func isPermissionEnable(forFeature feature: FeatureType) {
        // Does not compile, visibility issue
        self.getPermission(forFeature: feature.rawValue)
    }
}

Clarification:

FeatureDataManager is a class in the Pod that is solely used to check for permissions in the form of String value across many app that are using importing it.

I wanted each single app using it, to define an extension that would have their own finite enum of their supported permissions. Let's say App A support Ads, but not App B. So I wanted to have a universal method that when you call featureManager.isPermissionEnable(.Ads), whenever app that is, the auto-complete would just offer the list of the supported permission for that app. Also, the goal of wrapping my string permission value into an enum is to be more bulletproof to mistake and easier refactoring if a name change, just have to change it in a single place.


问:
luajit '=' expected near '-'
I have been trying to use luajit to compile luas, which is not relevant right now.
However, when I try to enter luajit -h (which should usually list commands) into the cmd looking luajit.exe window, I get the error " '=' expected near '-' ".

I have tried everything, including building the program using visual studio (msvcbuild into visual studio console) but nothing has worked so far and I am just devastated.

This error seems so easy to fix, yet is just a nightmare for someone who doesn't code at all.

答:
The error you are facing is a Lua error. To Lua luajit -h doesn't make sense.

-h is a command line option It is appended to a command. In that case running luajit with the -h option will print the available command line options to your terminal console.

You can create a shortcut to luajit with that option or run luajit from your command line.

Start Window's command line interpreter cmd.exe and enter luajit -h. (assuming your luajit.exe is in PATH or you're already in the directory containing luajit.exe

Title: luajit '=' expected near '-'


问:
Stripe credit card fields not working on WordPress
My WordPress website is using Stripe and WooCommerce plugin to accept credit card.

But on final checkout page, the credit card field is not working and showing very small size:

"Live Publishable Key" and "Live Secret Key" are correct.

Any idea how to fix it?

答:
There are many types of solutions for this problem, like having SSL installed, using the correct domain, etc.

On my site there was an error with the PayPal Checkout, which I had active too, that caused the stripe credit card form to not get filled with the according input fields. When I deactivated PayPal Checkout I could use the form just as expected again.

So far that's enough of a solution for me since I can continue using the normal PayPal implementation on WooCommerce without needing PayPal Checkout.

The PayPal Checkout error I received was:

```<code>Uncaught TypeError: Cannot read property 'FUNDING' of undefined at getFundingMethods".
</code>```

I have not been able to resolve it yet though without deactivating PayPal Checkout.

Body:
There are many types of solutions for this problem, like having SSL installed, using the correct domain, etc.

On my site there was an error with the PayPal Checkout, which I had active too, that caused the stripe credit card form to not get filled with the according input fields. When I deactivated PayPal Checkout I could use the form just as expected again.

So far that's enough of a solution for me since I can continue using the normal PayPal implementation on WooCommerce without needing PayPal Checkout.

The PayPal Checkout error I received was:

Uncaught TypeError: Cannot read property 'FUNDING' of undefined at getFundingMethods".

I have not been able to resolve it yet though without deactivating PayPal Checkout.


问:
Using wrap_content without content going of the screen and without using layout_weight
So I have something like this:

```<code>LinearLayout:
   LinearLayout - wrap_content, background black:
      TextView - wrap_content
   LinearLayout:
      Image - 20dp
</code>```

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusable="true"
    android:gravity="center|start"
    android:padding="5dp"
    android:layout_margin="2dp">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="klgjdkljgilfdjgidfhjiogjdio;jhgiju;fgjdhjgu;hdfuighdfuk;ghduk;fhgukldhfgujkdfhyufhglfdhguldfhguklhfdulghldfughyulfhdulghdfulghul"
        android:textColor="#D5D5D5" />

    <LinearLayout
        android:layout_width="15dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_marginBottom="2dp"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_gravity="bottom|center"
            android:src="@drawable/edit" />
    </LinearLayout>
</LinearLayout>
```

This works perfectly but when the TextView contains text larger than the screen size, the image gets out of the screen. I don't want that to happen.

Here's the example:

Does anyone know how to fix this so it doesn't go outside the screen?

Thanks!

答:
Try this with ConstraintLayout

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="klgjdkljgilfdjgidfhjiogjdio;jhgiju;fgjdhjgu;hdfuighdfuk;ghduk;fhgukldhfgujkdfhyufhglfdhguldfhguklhfdulghldfughyulfhdulghdfulghul"
        android:textColor="#D5D5D5"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toStartOf="@id/image"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <ImageView
        android:id="@+id/image"
        android:layout_width="20dp"
        android:layout_height="10dp"
        android:layout_gravity="bottom|center"
        android:src="@drawable/edit"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/message"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
So I have something like this:

LinearLayout:
   LinearLayout - wrap_content, background black:
      TextView - wrap_content
   LinearLayout:
      Image - 20dp

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusable="true"
    android:gravity="center|start"
    android:padding="5dp"
    android:layout_margin="2dp">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="klgjdkljgilfdjgidfhjiogjdio;jhgiju;fgjdhjgu;hdfuighdfuk;ghduk;fhgukldhfgujkdfhyufhglfdhguldfhguklhfdulghldfughyulfhdulghdfulghul"
        android:textColor="#D5D5D5" />

    <LinearLayout
        android:layout_width="15dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_marginBottom="2dp"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_gravity="bottom|center"
            android:src="@drawable/edit" />
    </LinearLayout>
</LinearLayout>

This works perfectly but when the TextView contains text larger than the screen size, the image gets out of the screen. I don't want that to happen.

Here's the example:

Does anyone know how to fix this so it doesn't go outside the screen?

Thanks!

Body:
Try this with ConstraintLayout

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="klgjdkljgilfdjgidfhjiogjdio;jhgiju;fgjdhjgu;hdfuighdfuk;ghduk;fhgukldhfgujkdfhyufhglfdhguldfhguklhfdulghldfughyulfhdulghdfulghul"
        android:textColor="#D5D5D5"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toStartOf="@id/image"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <ImageView
        android:id="@+id/image"
        android:layout_width="20dp"
        android:layout_height="10dp"
        android:layout_gravity="bottom|center"
        android:src="@drawable/edit"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/message"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Extract sub-page links by Looping Python
Extract sub-page links by Looping Python

I need to extract only the links of the "Next" at the bottom of all the "A category " stock pages using a dynamic loop.
I am new to python, but coded the same in VB and running in fine.
This code must be infested with syntax errors , do bear with it.

Help will be appreciated.

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import re

sub_link=[]
sub_link_edit=[]

 def convert(url):
  if not url.startswith('http://'):
    return 'http:' + url
  return url

next_link = 'https://money.rediff.com/companies/groups/A'

while next_link:
 page = requests.get(next_link)
 soup = BeautifulSoup(page.content,,'html.parser')

 pagination_container_company = soup.find_all("table", class_="pagination-
 container-company")[0].text

sub_link = re.search('href="(.*)">Next',
pagination_container_company).group(1)
sub_link_edit.append(convert(sub_link))
next_link=convert(sub_link)

data_df = pd.DataFrame()
df = pd.DataFrame(
 {
    'Link': sub_link_edit
 })
data_df = pd.concat([data_df, df], sort=False)

print(df.shape)
tot_sub=len(sub_link_edit)
print(tot_sub)

data_df.to_csv('results_1.csv')
</code>```

答:
ok, I decided to edit my answer. since you want to do it automatically this code will get all the "Next" URLs one after the other until there are none left then it will save them to a CSV file called urls.csv.

```<code>import requests
from bs4 import BeautifulSoup

csv_file = "page number,url\n"
url = "https://money.rediff.com/companies/groups/A"
urls = [url]

while True:
    data = requests.get(url).text

    soup = BeautifulSoup(data, 'html.parser')
    table = soup.find_all(class_="pagination-container-company")[0]
    row = table.find_all("a", text="Next")

    if row:
        url = "https:" + row[0]["href"]
        urls.append(url)
    else:
        break

for index, url in enumerate(urls):
    csv_file += f"{index},{url}\n"

with open("urls.csv", "w") as o:
    o.write(csv_file)
</code>```

===============================

[old answer] do you really need all this code just to extract the next page link?. the link for each page is of the form https://money.rediff.com/companies/groups/A/<number> where <number> the number of the page

Body:
Extract sub-page links by Looping Python

I need to extract only the links of the "Next" at the bottom of all the "A category " stock pages using a dynamic loop.
I am new to python, but coded the same in VB and running in fine.
This code must be infested with syntax errors , do bear with it.

Help will be appreciated.

import requests
from bs4 import BeautifulSoup
import pandas as pd
import re

sub_link=[]
sub_link_edit=[]

 def convert(url):
  if not url.startswith('http://'):
    return 'http:' + url
  return url

next_link = 'https://money.rediff.com/companies/groups/A'

while next_link:
 page = requests.get(next_link)
 soup = BeautifulSoup(page.content,,'html.parser')

 pagination_container_company = soup.find_all("table", class_="pagination-
 container-company")[0].text

sub_link = re.search('href="(.*)">Next',
pagination_container_company).group(1)
sub_link_edit.append(convert(sub_link))
next_link=convert(sub_link)

data_df = pd.DataFrame()
df = pd.DataFrame(
 {
    'Link': sub_link_edit
 })
data_df = pd.concat([data_df, df], sort=False)

print(df.shape)
tot_sub=len(sub_link_edit)
print(tot_sub)

data_df.to_csv('results_1.csv')

Body:
ok, I decided to edit my answer. since you want to do it automatically this code will get all the "Next" URLs one after the other until there are none left then it will save them to a CSV file called urls.csv.

import requests
from bs4 import BeautifulSoup

csv_file = "page number,url\n"
url = "https://money.rediff.com/companies/groups/A"
urls = [url]

while True:
    data = requests.get(url).text

    soup = BeautifulSoup(data, 'html.parser')
    table = soup.find_all(class_="pagination-container-company")[0]
    row = table.find_all("a", text="Next")

    if row:
        url = "https:" + row[0]["href"]
        urls.append(url)
    else:
        break

for index, url in enumerate(urls):
    csv_file += f"{index},{url}\n"

with open("urls.csv", "w") as o:
    o.write(csv_file)

===============================

[old answer] do you really need all this code just to extract the next page link?. the link for each page is of the form https://money.rediff.com/companies/groups/A/<number> where <number> the number of the page


问:
Empty request from Google Smart Home SDK
I'm creating web server to connect my DIY smart home devices to Google Home app.

After authorisation and token request Google server makes POST request to fullfillment URL, but request is empty for some reason. According to documentation, it must be SYNC request, but it does not contain any values, even request ID.

There is error "Couldn't  update the setting. Check your Internet connection." on my phone after request.

So why does it happen and how I can fix it?

```<code>const app=smarthome({ debug: true, });

app.onSync( async (body) => {
    return {
        requestId: body.requestId,
        payload: {
            agentUserId: "agentUserId",
            devices                       // devices list
        }
    };
});

server.post("/request", app);
</code>```

答:
Oh, I forgot to include body-parser 'cause I'm using general web server instead of actions-on-google API. LOL

Case closed.

Body:
I'm creating web server to connect my DIY smart home devices to Google Home app.

After authorisation and token request Google server makes POST request to fullfillment URL, but request is empty for some reason. According to documentation, it must be SYNC request, but it does not contain any values, even request ID.

There is error "Couldn't  update the setting. Check your Internet connection." on my phone after request.

So why does it happen and how I can fix it?

const app=smarthome({ debug: true, });

app.onSync( async (body) => {
    return {
        requestId: body.requestId,
        payload: {
            agentUserId: "agentUserId",
            devices                       // devices list
        }
    };
});

server.post("/request", app);


问:
How to compress GIF image before uploading to server in android?
how to compress GIF image before upload it to the server ?, i tried some android libraries to compress gif image but it convert it to png image. is there any way to compress gif image ?</p>

答:
im using a bitmap in my projects.

Bitmap

Example code:

```<code> ImageView carView = (ImageView) v.findViewById(R.id.imagen_cr7);

                        byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
                        InputStream input=new ByteArrayInputStream(decodedString);
                        Bitmap ext_pic = BitmapFactory.decodeStream(input);
                        carView.setImageBitmap(ext_pic);
</code>```

Body:
im using a bitmap in my projects.

Bitmap

Example code:

 ImageView carView = (ImageView) v.findViewById(R.id.imagen_cr7);

                        byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
                        InputStream input=new ByteArrayInputStream(decodedString);
                        Bitmap ext_pic = BitmapFactory.decodeStream(input);
                        carView.setImageBitmap(ext_pic);


问:
Django - Trying to render a modelform or formset get error I don't understand: __init__() got an unexpected keyword argument 'editable'
trying to create a simple modelform
model:

```<code>class Category(BaseModel):
    categoryText = db.StringProperty()
    parentCat = db.IntegerProperty()
</code>```

form:

```<code>class CategoryForm(forms.ModelForm):
    categoryText = forms.CharField(editable=True)
    class Meta:
        model = Category
</code>```

view:

```<code>if request.POST:
   pass
else:
form = CategoryForm()
    return render_to_response('adminCategories.html', {'form': form})
</code>```

I get an error :

init() got an unexpected keyword argument 'editable'

what am I doing wrong?

答: editable is for model fields, not form fields. If you want a form field to be read-only then you will have to use a different widget.

Body:
trying to create a simple modelform
model:

class Category(BaseModel):
    categoryText = db.StringProperty()
    parentCat = db.IntegerProperty()

form:

class CategoryForm(forms.ModelForm):
    categoryText = forms.CharField(editable=True)
    class Meta:
        model = Category

view:

if request.POST:
   pass
else:
form = CategoryForm()
    return render_to_response('adminCategories.html', {'form': form})

I get an error :

init() got an unexpected keyword argument 'editable'

what am I doing wrong?


问:
Too many open files - Failed to initialize inotify: the user limit on the total number of inotify instances has been reached
How can I fix below problem? I am using compass.</p>

```<code>   Too many open files - Failed to initialize inotify: the user limit on the total number of inotify instances has been reached.
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/rb-inotify-0.9.5/lib/rb-inotify/notifier.rb:64:in `initialize'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapters/linux.rb:66:in `initialize_worker'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:87:in `initialize'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapters/linux.rb:31:in `initialize'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:226:in `works?'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:190:in `usable_and_works?'
org/jruby/RubyEnumerable.java:1425:in `all?'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:190:in `usable_and_works?'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:57:in `select_and_initialize'
org/jruby/RubyArray.java:1613:in `each'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:55:in `select_and_initialize'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/listener.rb:291:in `initialize_adapter'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/listener.rb:283:in `setup'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/listener.rb:65:in `start!'
    /home/rmack/Downloads/compass.app/lib/ruby/compass_1.0/sass-3.4.13/lib/sass/plugin/compiler.rb:405:in `listen_to'
    /home/rmack/Downloads/compass.app/lib/ruby/compass_1.0/sass-3.4.13/lib/sass/plugin/compiler.rb:338:in `watch'
    /home/rmack/Downloads/compass.app/lib/ruby/compass_1.0/compass-1.0.3/lib/compass/sass_compiler.rb:46:in `watch!'
    /home/rmack/Downloads/compass.app/lib/ruby/compass_1.0/compass-1.0.3/lib/compass/commands/watch_project.rb:41:in `perform'
file:/home/rmack/Downloads/compass.app/compass-app.jar!/app_watcher.rb:12:in `watch!'
file:/home/rmack/Downloads/compass.app/compass-app.jar!/ui/tray.rb:447:in `watch'
</code>```

答:
As it is described in other comments, you can try to find application which does not work correctly with the file system.

But in some cases it is alright, only some application (in my case Felix OSGI cache) has too many open files and limits are too low.

Then open /etc/security/limits.conf and add line with limits for the user or group, ie.:

```<code>dmatej          soft    nofile          10000
</code>```

Body:
How can I fix below problem? I am using compass.

   Too many open files - Failed to initialize inotify: the user limit on the total number of inotify instances has been reached.
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/rb-inotify-0.9.5/lib/rb-inotify/notifier.rb:64:in `initialize'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapters/linux.rb:66:in `initialize_worker'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:87:in `initialize'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapters/linux.rb:31:in `initialize'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:226:in `works?'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:190:in `usable_and_works?'
org/jruby/RubyEnumerable.java:1425:in `all?'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:190:in `usable_and_works?'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:57:in `select_and_initialize'
org/jruby/RubyArray.java:1613:in `each'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/adapter.rb:55:in `select_and_initialize'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/listener.rb:291:in `initialize_adapter'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/listener.rb:283:in `setup'
    /home/rmack/Downloads/compass.app/lib/ruby/jruby/listen-1.3.1-patched/lib/listen/listener.rb:65:in `start!'
    /home/rmack/Downloads/compass.app/lib/ruby/compass_1.0/sass-3.4.13/lib/sass/plugin/compiler.rb:405:in `listen_to'
    /home/rmack/Downloads/compass.app/lib/ruby/compass_1.0/sass-3.4.13/lib/sass/plugin/compiler.rb:338:in `watch'
    /home/rmack/Downloads/compass.app/lib/ruby/compass_1.0/compass-1.0.3/lib/compass/sass_compiler.rb:46:in `watch!'
    /home/rmack/Downloads/compass.app/lib/ruby/compass_1.0/compass-1.0.3/lib/compass/commands/watch_project.rb:41:in `perform'
file:/home/rmack/Downloads/compass.app/compass-app.jar!/app_watcher.rb:12:in `watch!'
file:/home/rmack/Downloads/compass.app/compass-app.jar!/ui/tray.rb:447:in `watch'

Body:
As it is described in other comments, you can try to find application which does not work correctly with the file system.

But in some cases it is alright, only some application (in my case Felix OSGI cache) has too many open files and limits are too low.

Then open /etc/security/limits.conf and add line with limits for the user or group, ie.:

dmatej          soft    nofile          10000


问:
Custom tooltip with Rxjs
I'm trying to implement my custom tooltip on a diagram using vis-network library and RXJS.

The main principle is:

One observable diagramElementHover$ to show the tooltip

One observable hideTooltipObs$ to hide the tooltip (the emitted value is null)

I want the tooltip to wait 1000ms to check if the mouse pointer is still under the element to be displayed (clear the tooltip if the pointer has gone before that delay)

The tooltip display uses the *ngIf directive with tooltip value

For now, the problem is that I can't prevent the tooltip to be shown if the user hovers one element and stays less that 1 second (then the tooltip is not hidden, unless you enter another node)

Globally, my implementation looks like this:

this.sub = merge(
    diagramElementHover$.pipe(
        mergeMap(event => of(event).pipe(delay(1000))),
        repeat()
    ),
        hideTooltipObs$
    ).pipe(
        tap(tooltip => this.tooltip = tooltip)
    )
```

I tried to use the takeUntil() operator but without success...
Can you guide me through this?

Here is the stackblitz example.

答:
You can use switchMap on the merged subjects.

The delay should then be inside the switchMap.

```<code>this.sub = merge<any>(
    diagramElementHover$.pipe(
      map(event => event),
      repeat()
    ),
    hideTooltipObs$
).pipe(
    switchMap(tooltip => {
      return of(tooltip).pipe(
        delay(tooltip ? 1000 : 0),
        tap(() =>this.tooltip = tooltip ))
    })
).subscribe()
</code>```

Here my stackblitz

Title: Custom tooltip with Rxjs

Body:
I'm trying to implement my custom tooltip on a diagram using vis-network library and RXJS.

The main principle is:

One observable diagramElementHover$ to show the tooltip

One observable hideTooltipObs$ to hide the tooltip (the emitted value is null)

I want the tooltip to wait 1000ms to check if the mouse pointer is still under the element to be displayed (clear the tooltip if the pointer has gone before that delay)

The tooltip display uses the *ngIf directive with tooltip value

For now, the problem is that I can't prevent the tooltip to be shown if the user hovers one element and stays less that 1 second (then the tooltip is not hidden, unless you enter another node)

Globally, my implementation looks like this:

this.sub = merge(
    diagramElementHover$.pipe(
        mergeMap(event => of(event).pipe(delay(1000))),
        repeat()
    ),
        hideTooltipObs$
    ).pipe(
        tap(tooltip => this.tooltip = tooltip)
    )

I tried to use the takeUntil() operator but without success...
Can you guide me through this?

Here is the stackblitz example.

Body:
You can use switchMap on the merged subjects.

The delay should then be inside the switchMap.

this.sub = merge<any>(
    diagramElementHover$.pipe(
      map(event => event),
      repeat()
    ),
    hideTooltipObs$
).pipe(
    switchMap(tooltip => {
      return of(tooltip).pipe(
        delay(tooltip ? 1000 : 0),
        tap(() =>this.tooltip = tooltip ))
    })
).subscribe()

Here my stackblitz


问:
Change Color of selection Angular Material Table with selection
How to change the color of the selector in the angular material table with selection

答:
Works for all normal check-boxes as well as indeterminate ones in the header.</p>

```<code>::ng-deep .mat-checkbox-checked .mat-checkbox-background,
::ng-deep .mat-checkbox-indeterminate .mat-checkbox-background {
  background-color: green !important; // Example color green
}
</code>```

Body:
Works for all normal check-boxes as well as indeterminate ones in the header.

::ng-deep .mat-checkbox-checked .mat-checkbox-background,
::ng-deep .mat-checkbox-indeterminate .mat-checkbox-background {
  background-color: green !important; // Example color green
}


问:
Add Buy Me A Coffee Widget to React application
I am trying to create a component that renders the Buy Me A Coffee widget in some routes of my react single page application. This is my component so far:

```<code>class BuyMeACoffee extends React.Component {
    componentDidMount () {
         const script = document.createElement("script",);
         script.setAttribute('data-name','BMC-Widget')
         script.src = "https://cdnjs.buymeacoffee.com/1.0.0/widget.prod.min.js"
         script.setAttribute('data-id', 'boulderproblems');
         script.setAttribute('data-description', 'Thank you for your support!');
         script.setAttribute('data-message', 'This web is free to use. Do you want to help supporting it?');
         script.setAttribute('data-color',"#FF5F5F")
         script.setAttribute('data-position','right')
         script.setAttribute('data-x_margin','18')
         script.setAttribute('data-y-margin','18')
         script.async = true
         document.head.appendChild(script)
    }

    render(){
         return(null)
    }
}
</code>```

When I inspect the page with the developer tools, the  tag is at the end of the head section and everything seems correct but the widget doesn't show in the page.

Note: If I copy the script code in the head section of the index.html page:

```<code><script data-name="BMC-Widget" src="https://cdnjs.buymeacoffee.com/1.0.0/widget.prod.min.js" data-id="boulderproblems" data-description="Thank you for your support!" data-message="This web is free to use. Do you want to help supporting it?" data-color="#FF5F5F" data-position="right" data-x_margin="18" data-y-margin="18"></script>
</code>```

then it works perfectly. The problem is that in this case, the widget is shown for all routes. I have also tried react-helmet without success.

答:
I finnally got it working. I post my solution here in case it is useful for someone. Not sure if it is the most elegant but it works. I slightly modified the original component so the script and widget is removed when the component is unmounted. Here is the component now:

class BuyMeACoffe extends React.Component {
    constructor(props){
        super(props)
        let script = document.createElement("script");
        script.setAttribute('data-name','BMC-Widget')
        script.src = "https://cdnjs.buymeacoffee.com/1.0.0/widget.prod.min.js"
        script.setAttribute('data-id', 'boulderproblems');
        script.setAttribute('data-description', 'Thank you for your support!');
        script.setAttribute('data-message', 'This web is free to use. Do you want to help supporting it?');
        script.setAttribute('data-color',"#FF5F5F")
        script.setAttribute('data-position','right')
        script.setAttribute('data-x_margin','18')
        script.setAttribute('data-y-margin','18')
        script.async = true
        //Call window on load to show the image
        script.onload=function(){
            var evt = document.createEvent('Event');
            evt.initEvent('DOMContentLoaded', false, false);
            window.dispatchEvent(evt);
        }
        this.script=script
    }

    componentDidMount () {
        document.head.appendChild(this.script)
    }

    componentWillUnmount(){
        document.head.removeChild(this.script);
        document.body.removeChild(document.getElementById("bmc-wbtn"))
     }

    render(){
        return(null)
    }
}
```
<p>Basically, after reading the buymeacoffee script I realized that they load the widget when the window is DOMContentLoaded event is fired. What I do is to fire this event manually after I insert the script.</p>
<p>Note: After doing this, I had to add a couple of styles because the widget was showing out of the screen. Maybe it was because of my layout. Anyway, here they are in case they you need them:</p>
```#bmc-wbtn{
    bottom: 15px;
}

#bmc-wbtn + div{
    bottom:15px;
}
```

Body:
I am trying to create a component that renders the Buy Me A Coffee widget in some routes of my react single page application. This is my component so far:

class BuyMeACoffee extends React.Component {
    componentDidMount () {
         const script = document.createElement("script",);
         script.setAttribute('data-name','BMC-Widget')
         script.src = "https://cdnjs.buymeacoffee.com/1.0.0/widget.prod.min.js"
         script.setAttribute('data-id', 'boulderproblems');
         script.setAttribute('data-description', 'Thank you for your support!');
         script.setAttribute('data-message', 'This web is free to use. Do you want to help supporting it?');
         script.setAttribute('data-color',"#FF5F5F")
         script.setAttribute('data-position','right')
         script.setAttribute('data-x_margin','18')
         script.setAttribute('data-y-margin','18')
         script.async = true
         document.head.appendChild(script)
    }

    render(){
         return(null)
    }
}

When I inspect the page with the developer tools, the  tag is at the end of the head section and everything seems correct but the widget doesn't show in the page.

Note: If I copy the script code in the head section of the index.html page:

then it works perfectly. The problem is that in this case, the widget is shown for all routes. I have also tried react-helmet without success.

Body:
I finnally got it working. I post my solution here in case it is useful for someone. Not sure if it is the most elegant but it works. I slightly modified the original component so the script and widget is removed when the component is unmounted. Here is the component now:

class BuyMeACoffe extends React.Component {
    constructor(props){
        super(props)
        let script = document.createElement("script");
        script.setAttribute('data-name','BMC-Widget')
        script.src = "https://cdnjs.buymeacoffee.com/1.0.0/widget.prod.min.js"
        script.setAttribute('data-id', 'boulderproblems');
        script.setAttribute('data-description', 'Thank you for your support!');
        script.setAttribute('data-message', 'This web is free to use. Do you want to help supporting it?');
        script.setAttribute('data-color',"#FF5F5F")
        script.setAttribute('data-position','right')
        script.setAttribute('data-x_margin','18')
        script.setAttribute('data-y-margin','18')
        script.async = true
        //Call window on load to show the image
        script.onload=function(){
            var evt = document.createEvent('Event');
            evt.initEvent('DOMContentLoaded', false, false);
            window.dispatchEvent(evt);
        }
        this.script=script
    }

    componentDidMount () {
        document.head.appendChild(this.script)
    }

    componentWillUnmount(){
        document.head.removeChild(this.script);
        document.body.removeChild(document.getElementById("bmc-wbtn"))
     }

    render(){
        return(null)
    }
}

Basically, after reading the buymeacoffee script I realized that they load the widget when the window is DOMContentLoaded event is fired. What I do is to fire this event manually after I insert the script.

Note: After doing this, I had to add a couple of styles because the widget was showing out of the screen. Maybe it was because of my layout. Anyway, here they are in case they you need them:

#bmc-wbtn{
    bottom: 15px;
}

#bmc-wbtn + div{
    bottom:15px;
}


问:
How to create a list of a number?
I am new to python and i was wondering how i could create a list of numbers in python as such

```<code>number = 123456
list_to_be_created = [1,2,3,4,5,6]
</code>```

Thank you in advance

答:
```<code>>>> list(range(1, 7))
[1, 2, 3, 4, 5, 6]
</code>```

If you literally have the number 123456 (i.e. the int value for one hundred twenty three thousand four hundred fifty six) and you want to turn it into a list of its digits, you might do:

```<code>>>> number = 123456
>>> list_to_be_created = list(map(int, str(number)))
>>> list_to_be_created
[1, 2, 3, 4, 5, 6]
</code>```

Title: How to create a list of a number?

Body:
I am new to python and i was wondering how i could create a list of numbers in python as such

number = 123456
list_to_be_created = [1,2,3,4,5,6]

Thank you in advance

Body:
>>> list(range(1, 7))
[1, 2, 3, 4, 5, 6]

If you literally have the number 123456 (i.e. the int value for one hundred twenty three thousand four hundred fifty six) and you want to turn it into a list of its digits, you might do:

>>> number = 123456
>>> list_to_be_created = list(map(int, str(number)))
>>> list_to_be_created
[1, 2, 3, 4, 5, 6]


问:
(tidy, glance, augment) with exec
I see from the purrr documentation that it should be possible to map a list of functions onto arguments using the map(list(fn1, fn2, fn3), exec, !!!args) syntax or something similar.  How would this work for the broom functions tidy, glance, and augment, which usually must be supplemented with do?  These are three functions I almost always like to execute at the same time on the same data and model.  Of course I can do this explicitly:

```<code># works but is repetitive
MY_MODEL <- hp ~ cyl
my_glance <- mtcars %>% do(glance(lm(data = ., formula = MY_MODEL)))
my_tidy <- mtcars %>% do(tidy(lm(data = ., formula = MY_MODEL)))
my_augment <- mtcars %>% do(augment(lm(data = ., formula = MY_MODEL)))
</code>```

I suspect there is a better, more compact way to do this without having to retype ...lm(data = ., formula = MY_MODEL... every time, but I couldn't figure it out.  I tried

```<code># doesn't work
omnibroom <- function(df, model){
    map(list(glance, tidy, augment),
        exec,
        ~{(do(.x(lm(data = df, formula = model))))}
        )
    }

omnibroom(mtcars, MY_MODEL)
</code>```

but I think I don't understand the !!! syntax appropriately.

Is there a compact idiom for calling these three broom functions on the same model and data?

答:
It's possible to do this in two lines with simple re-factoring. No do or !!! necessary.

```<code>mdl <- mtcars %>% lm(data=., formula=MY_MODEL)
res1 <- map( list(glance, tidy, augment), exec, mdl )
</code>```

If you really want to squish it down into a single line, use { to help guide pipe input to the correct place in lm:

```<code>res2 <- mtcars %>%
    {map( list(glance, tidy, augment), exec, lm(data=., formula=MY_MODEL) )}
</code>```

Verification:

```<code>identical( res1, list(my_glance, my_tidy, my_augment) )    # TRUE
identical( res1, res2 )                                    # TRUE
</code>```

EDIT to address grouping

Arbitrary functions like lm don't respect data frame groups. While do is a popular approach to handle grouping in this case, I personally think that tidyr::nest() is more intuitive because it places all intermediates and results alongside the data:

```<code>## "Listify" broom functions: f -> map( ..., f )
omnibroom <- map( list(glance, tidy, augment), ~function(l) map(l, .x) ) %>%
    set_names( c("glance","tidy","augment") )

result <- mtcars %>% nest( data = -gear ) %>%
    mutate( model = map(data, lm, formula=MY_MODEL) ) %>%
    mutate_at( "model", omnibroom )

#  # A tibble: 3 x 6
#     gear data              model  glance           tidy           augment
#    <dbl> <list>            <list> <list>           <list>         <list>
#  1     4 <tibble [12 × 10… <lm>   <tibble [1 × 11… <tibble [2 × … <tibble [12 × …
#  2     3 <tibble [15 × 10… <lm>   <tibble [1 × 11… <tibble [2 × … <tibble [15 × …
#  3     5 <tibble [5 × 10]> <lm>   <tibble [1 × 11… <tibble [2 × … <tibble [5 × 9…

</code>```

This format also naturally lends itself to unnesting, since broom functions produce data frames:

```<code>result %>% select( gear, tidy ) %>% unnest( tidy )

#  # A tibble: 6 x 6
#     gear term        estimate std.error statistic p.value
#    <dbl> <chr>          <dbl>     <dbl>     <dbl>   <dbl>
#  1     4 (Intercept)    -5.00     25.3     -0.198 0.847
#  2     4 cyl            20.2       5.30     3.82  0.00339
#  3     3 (Intercept)   -47.5      56.1     -0.847 0.412
#  4     3 cyl            30.0       7.42     4.04  0.00142
#  5     5 (Intercept)  -101.       51.9     -1.94  0.148
#  6     5 cyl            49.4       8.28     5.96  0.00944
</code>```

Title: (tidy, glance, augment) with exec

Body:
I see from the purrr documentation that it should be possible to map a list of functions onto arguments using the map(list(fn1, fn2, fn3), exec, !!!args) syntax or something similar.  How would this work for the broom functions tidy, glance, and augment, which usually must be supplemented with do?  These are three functions I almost always like to execute at the same time on the same data and model.  Of course I can do this explicitly:

# works but is repetitive
MY_MODEL <- hp ~ cyl
my_glance <- mtcars %>% do(glance(lm(data = ., formula = MY_MODEL)))
my_tidy <- mtcars %>% do(tidy(lm(data = ., formula = MY_MODEL)))
my_augment <- mtcars %>% do(augment(lm(data = ., formula = MY_MODEL)))

I suspect there is a better, more compact way to do this without having to retype ...lm(data = ., formula = MY_MODEL... every time, but I couldn't figure it out.  I tried

# doesn't work
omnibroom <- function(df, model){
    map(list(glance, tidy, augment),
        exec,
        ~{(do(.x(lm(data = df, formula = model))))}
        )
    }

omnibroom(mtcars, MY_MODEL)

but I think I don't understand the !!! syntax appropriately.

Is there a compact idiom for calling these three broom functions on the same model and data?

Body:
It's possible to do this in two lines with simple re-factoring. No do or !!! necessary.

mdl <- mtcars %>% lm(data=., formula=MY_MODEL)
res1 <- map( list(glance, tidy, augment), exec, mdl )

If you really want to squish it down into a single line, use { to help guide pipe input to the correct place in lm:

res2 <- mtcars %>%
    {map( list(glance, tidy, augment), exec, lm(data=., formula=MY_MODEL) )}

Verification:

identical( res1, list(my_glance, my_tidy, my_augment) )    # TRUE
identical( res1, res2 )                                    # TRUE

EDIT to address grouping

Arbitrary functions like lm don't respect data frame groups. While do is a popular approach to handle grouping in this case, I personally think that tidyr::nest() is more intuitive because it places all intermediates and results alongside the data:

## "Listify" broom functions: f -> map( ..., f )
omnibroom <- map( list(glance, tidy, augment), ~function(l) map(l, .x) ) %>%
    set_names( c("glance","tidy","augment") )

result <- mtcars %>% nest( data = -gear ) %>%
    mutate( model = map(data, lm, formula=MY_MODEL) ) %>%
    mutate_at( "model", omnibroom )

#  # A tibble: 3 x 6
#     gear data              model  glance           tidy           augment
#    <dbl> <list>            <list> <list>           <list>         <list>
#  1     4 <tibble [12 × 10… <lm>   <tibble [1 × 11… <tibble [2 × … <tibble [12 × …
#  2     3 <tibble [15 × 10… <lm>   <tibble [1 × 11… <tibble [2 × … <tibble [15 × …
#  3     5 <tibble [5 × 10]> <lm>   <tibble [1 × 11… <tibble [2 × … <tibble [5 × 9…

This format also naturally lends itself to unnesting, since broom functions produce data frames:

result %>% select( gear, tidy ) %>% unnest( tidy )

#  # A tibble: 6 x 6
#     gear term        estimate std.error statistic p.value
#    <dbl> <chr>          <dbl>     <dbl>     <dbl>   <dbl>
#  1     4 (Intercept)    -5.00     25.3     -0.198 0.847
#  2     4 cyl            20.2       5.30     3.82  0.00339
#  3     3 (Intercept)   -47.5      56.1     -0.847 0.412
#  4     3 cyl            30.0       7.42     4.04  0.00142
#  5     5 (Intercept)  -101.       51.9     -1.94  0.148
#  6     5 cyl            49.4       8.28     5.96  0.00944


问:
Enumeratum Circe Serialisation
I have a simple case class like so:

```<code>case class ColumnMetadata(name: String,
                          displayName: String,
                          description: Option[String],
                          attributeType: AttributeType)

sealed trait AttributeType extends EnumEntry

case object AttributeType extends Enum[AttributeType] with CirceEnum[AttributeType] {

 val values: immutable.IndexedSeq[AttributeType] = findValues

  case object Number extends AttributeType
  case object Text extends AttributeType
  case object Percentage extends AttributeType
}
</code>```

And semi-auto encoder:

```<code>package object circe {

  implicit val config: Configuration = Configuration.default.withSnakeCaseMemberNames

  implicit val columnMetaDecoder: Decoder[ColumnMetadata] = deriveConfiguredDecoder
  implicit val columnMetaEncoder: Encoder[ColumnMetadata] = deriveConfiguredEncoder

  implicit val columnTypeDecoder: Decoder[AttributeType] = deriveConfiguredDecoder
  implicit val columnTypeEncoder: Encoder[AttributeType] = deriveConfiguredEncoder
}
</code>```

However when I do a serialisation test:

```<code>  ColumnMetadata("column1", "Column 1", Some("column1"),
    AttributeType.withName("Text")).asJson
</code>```

I get:

```<code>  {
    "name" : "column1",
    "display_name" : "Column 1",
    "description" : "column1",
    "attribute_type" : {
      "Text": {}
    }
  }
</code>```

When I want:

```<code>  {
    "name" : "column1",
    "display_name" : "Column 1",
    "description" : "column1",
    "attribute_type" : "Text"
  }
</code>```

It works when I use the automatic derivation but I want to use a semi-auto derivation so I can use feature such as withSnakeCaseMemberNames.

答:
This is your error:

```<code>
  implicit val columnTypeDecoder: Decoder[AttributeType] = deriveConfiguredDecoder
  implicit val columnTypeEncoder: Encoder[AttributeType] = deriveConfiguredEncoder
</code>```

This will derive new codecs, treating AttributeType as any other sealed trait, so it will use discrimination value (semi auto always ignores existing codecs of the type that they are deriving!).

So you are deriving a new AttributeType codecs, put them in scope where they are used, and so making these new implementations have higher priority than the ones from an companion object. Closer implicit always wins.

If you won't derive the codecs (because there are already existing implementations provided by CirceEnum trait) then it will work as you expect.

Additionally instead of doing this:

```<code>  implicit val columnMetaDecoder: Decoder[ColumnMetadata] = deriveConfiguredDecoder
  implicit val columnMetaEncoder: Encoder[ColumnMetadata] = deriveConfiguredEncoder
</code>```

you can just do this:

```<code>// make sure that Configuration is in scope by e.g. importing it
// or putting it in package object in the same package as case class
@ConfiguredJsonCodec
case class ColumnMetadata(name: String,
                          displayName: String,
                          description: Option[String],
                          attributeType: AttributeType)
</code>```

This will spare you effort of creating package of codecs and importing them manually, everywhere you need them. E.g.

```<code>// imports

package object models_package {

  private[models_package] implicit val config: Configuration = Configuration.default.withSnakeCaseMemberNames
}
</code>```

```<code>package models_package

// imports

@ConfiguredJsonCodec
case class ColumnMetadata(name: String,
                          displayName: String,
                          description: Option[String],
                          attributeType: AttributeType)

sealed trait AttributeType extends EnumEntry
object AttributeType extends Enum[AttributeType] with CirceEnum[AttributeType] {

 val values: immutable.IndexedSeq[AttributeType] = findValues

  case object Number extends AttributeType
  case object Text extends AttributeType
  case object Percentage extends AttributeType
}
</code>```

Title: Enumeratum Circe Serialisation

Body:
I have a simple case class like so:

case class ColumnMetadata(name: String,
                          displayName: String,
                          description: Option[String],
                          attributeType: AttributeType)

sealed trait AttributeType extends EnumEntry

case object AttributeType extends Enum[AttributeType] with CirceEnum[AttributeType] {

 val values: immutable.IndexedSeq[AttributeType] = findValues

  case object Number extends AttributeType
  case object Text extends AttributeType
  case object Percentage extends AttributeType
}

And semi-auto encoder:

package object circe {

  implicit val config: Configuration = Configuration.default.withSnakeCaseMemberNames

  implicit val columnMetaDecoder: Decoder[ColumnMetadata] = deriveConfiguredDecoder
  implicit val columnMetaEncoder: Encoder[ColumnMetadata] = deriveConfiguredEncoder

  implicit val columnTypeDecoder: Decoder[AttributeType] = deriveConfiguredDecoder
  implicit val columnTypeEncoder: Encoder[AttributeType] = deriveConfiguredEncoder
}

However when I do a serialisation test:

  ColumnMetadata("column1", "Column 1", Some("column1"),
    AttributeType.withName("Text")).asJson

I get:

  {
    "name" : "column1",
    "display_name" : "Column 1",
    "description" : "column1",
    "attribute_type" : {
      "Text": {}
    }
  }

When I want:

  {
    "name" : "column1",
    "display_name" : "Column 1",
    "description" : "column1",
    "attribute_type" : "Text"
  }

It works when I use the automatic derivation but I want to use a semi-auto derivation so I can use feature such as withSnakeCaseMemberNames.

Body:
This is your error:

  implicit val columnTypeDecoder: Decoder[AttributeType] = deriveConfiguredDecoder
  implicit val columnTypeEncoder: Encoder[AttributeType] = deriveConfiguredEncoder

This will derive new codecs, treating AttributeType as any other sealed trait, so it will use discrimination value (semi auto always ignores existing codecs of the type that they are deriving!).

So you are deriving a new AttributeType codecs, put them in scope where they are used, and so making these new implementations have higher priority than the ones from an companion object. Closer implicit always wins.

If you won't derive the codecs (because there are already existing implementations provided by CirceEnum trait) then it will work as you expect.

Additionally instead of doing this:

  implicit val columnMetaDecoder: Decoder[ColumnMetadata] = deriveConfiguredDecoder
  implicit val columnMetaEncoder: Encoder[ColumnMetadata] = deriveConfiguredEncoder

you can just do this:

// make sure that Configuration is in scope by e.g. importing it
// or putting it in package object in the same package as case class
@ConfiguredJsonCodec
case class ColumnMetadata(name: String,
                          displayName: String,
                          description: Option[String],
                          attributeType: AttributeType)

This will spare you effort of creating package of codecs and importing them manually, everywhere you need them. E.g.

// imports

package object models_package {

  private[models_package] implicit val config: Configuration = Configuration.default.withSnakeCaseMemberNames
}

package models_package

// imports

@ConfiguredJsonCodec
case class ColumnMetadata(name: String,
                          displayName: String,
                          description: Option[String],
                          attributeType: AttributeType)

sealed trait AttributeType extends EnumEntry
object AttributeType extends Enum[AttributeType] with CirceEnum[AttributeType] {

 val values: immutable.IndexedSeq[AttributeType] = findValues

  case object Number extends AttributeType
  case object Text extends AttributeType
  case object Percentage extends AttributeType
}


问:
How do I put together members of two Python lists that have the same indexes?
How do I combine the first member of a list in Python with the first member of the second list as well as the second member of the first list with the second member of the second list? And will this happen until the last members of the lists go ahead?</p>

答:
This is a basic zip function. For example:

```<code>list_1 = [1, 2, 3]
list_2 = ["s", "u", "p"]

final_list = list(zip(list_1, list_2))
print(final_list)
</code>```

This will return a list of tuples such that the first value from the first list is paired with the first value of the second list, iterating over each value up until the minimum length between the two lists is satisfied. In the example, this would be the output: [(1, 's'), (2, 'u'), (3, 'p')]

It's important to note that if one of the lists is longer than the other, the extra values will be excluded. There are a ton of ways to handle this, but it would help to know what you're wanting to accomplish.

Body:
This is a basic zip function. For example:

list_1 = [1, 2, 3]
list_2 = ["s", "u", "p"]

final_list = list(zip(list_1, list_2))
print(final_list)

This will return a list of tuples such that the first value from the first list is paired with the first value of the second list, iterating over each value up until the minimum length between the two lists is satisfied. In the example, this would be the output: [(1, 's'), (2, 'u'), (3, 'p')]

It's important to note that if one of the lists is longer than the other, the extra values will be excluded. There are a ton of ways to handle this, but it would help to know what you're wanting to accomplish.


问:
Rhino Mocks Use
Hello I have a class called MassRateChange and it has a method called

```<code>Long CreateFile(DatTime StartDate, DateTime EndDate);
</code>```

Can anyone tell me how I can mock this method using RhinoMocks.

The class is not static and neither is the method static.

答:
Make sure the method is virtual and it should be as easy as:

```<code>var rateChange = MockRepository.GenerateMock<MassRateChange>();
rateChange.Stub(r => r.CreateFile(DateTime.Now, DateTime.Now)).IgnoreArguments().Return(10);
</code>```

This, of course, assumes the start date and end date aren't really important and you just want the method to return the value "10" during testing.

Title: Rhino Mocks Use

Body:
Hello I have a class called MassRateChange and it has a method called

Long CreateFile(DatTime StartDate, DateTime EndDate);

Can anyone tell me how I can mock this method using RhinoMocks.

The class is not static and neither is the method static.

Body:
Make sure the method is virtual and it should be as easy as:

var rateChange = MockRepository.GenerateMock<MassRateChange>();
rateChange.Stub(r => r.CreateFile(DateTime.Now, DateTime.Now)).IgnoreArguments().Return(10);

This, of course, assumes the start date and end date aren't really important and you just want the method to return the value "10" during testing.