问:
Spring Security 5, No "Access Control Allow Origin" Header present on resource
I have the following Configuration Class that implements the WebMvcConfigurer Interface and Overrides the addCorsMappings method. (as described here: https://www.baeldung.com/spring-cors)

```<code>@Configuration
//@EnableWebMvc <- I tried with and without, no effect
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}
</code>```

I also have a Configuration Class extending the WebSecurityConfigurerAdapter:

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customService = new CustomUserDetailsService();

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/user/signup*").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/auth*").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/nummern/**").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/information/").hasRole("OWNER")
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .addFilter(new JwtAuthenticationFilter(authenticationManager()))
            .addFilter(new JwtAuthorizationFilter(authenticationManager()))
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
</code>```

Whenever I make an HTTP request to my authorization endpoint, using Ajax, I get the following error:

Access to XMLHttpRequest at 'http://localhost:8080/auth?username=Example&password=Example' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Since this approach had no effect, I also tried the approach found in the Spring Security 5 documentation, but that also did not work:

https://docs.spring.io/spring-security/site/docs/5.0.5.RELEASE/reference/htmlsingle/#cors

I am not sure if this is due to my CORS configuration or some CSRF configuration (as far as I am concerned CSRF should be disabled due to my HttpSecurity config):

```<code>2020-05-29 13:52:40.377 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /auth?username=Example&password=Example at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-05-29 13:52:40.378 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /auth?username=Example&password=Example at position 4 of 15 in additional filter chain; firing Filter: 'CsrfFilter'
2020-05-29 13:52:40.381 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8080/auth?username=Example&password=Example
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@4ea0d6af
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
</code>```

I have tried various other suggested solutions and CORS configurations for older Spring Security versions but none of them has had any effect on my issue so far.

This seems like the most recent Solution for a similar question, also didn't work for me:

Spring Boot Security No 'Access-Control-Allow-Origin' header is present on the requested resource Error

EDIT:
I tried using a CORS disabling extension for Firefox (and various HTTP clients), but I was not able to see any differences apart from being redirected to the /login endpoint, which I also tried to disable using:

```<code>  http.httpBasic().disable()
</code>```

My Spring Application still throws the same error as mentioned above in all of the test cases.

EDIT #2:
I also tried:

```<code>    @Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:3000");
        }
    };
}
</code>```

答:
I think it doesn't work because you didn't add your origin(localhost:3000) to allowed origins. So Spring doesn't know which origins have access.

Spring guide shows how to do that :

```<code>@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
        }
    };
}
</code>```

Also you can use second option specified here

Body:
I have the following Configuration Class that implements the WebMvcConfigurer Interface and Overrides the addCorsMappings method. (as described here: https://www.baeldung.com/spring-cors)

@Configuration
//@EnableWebMvc <- I tried with and without, no effect
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

I also have a Configuration Class extending the WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customService = new CustomUserDetailsService();

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/user/signup*").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/auth*").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/nummern/**").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/information/").hasRole("OWNER")
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .addFilter(new JwtAuthenticationFilter(authenticationManager()))
            .addFilter(new JwtAuthorizationFilter(authenticationManager()))
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

Whenever I make an HTTP request to my authorization endpoint, using Ajax, I get the following error:

Access to XMLHttpRequest at 'http://localhost:8080/auth?username=Example&password=Example' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Since this approach had no effect, I also tried the approach found in the Spring Security 5 documentation, but that also did not work:

https://docs.spring.io/spring-security/site/docs/5.0.5.RELEASE/reference/htmlsingle/#cors

I am not sure if this is due to my CORS configuration or some CSRF configuration (as far as I am concerned CSRF should be disabled due to my HttpSecurity config):

2020-05-29 13:52:40.377 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /auth?username=Example&password=Example at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-05-29 13:52:40.378 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /auth?username=Example&password=Example at position 4 of 15 in additional filter chain; firing Filter: 'CsrfFilter'
2020-05-29 13:52:40.381 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8080/auth?username=Example&password=Example
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@4ea0d6af
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.

I have tried various other suggested solutions and CORS configurations for older Spring Security versions but none of them has had any effect on my issue so far.

This seems like the most recent Solution for a similar question, also didn't work for me:

Spring Boot Security No 'Access-Control-Allow-Origin' header is present on the requested resource Error

EDIT:
I tried using a CORS disabling extension for Firefox (and various HTTP clients), but I was not able to see any differences apart from being redirected to the /login endpoint, which I also tried to disable using:

  http.httpBasic().disable()

My Spring Application still throws the same error as mentioned above in all of the test cases.

EDIT #2:
I also tried:

    @Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:3000");
        }
    };
}

Body:
I think it doesn't work because you didn't add your origin(localhost:3000) to allowed origins. So Spring doesn't know which origins have access.

Spring guide shows how to do that :

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
        }
    };
}

Also you can use second option specified here


来源: stackexchange

问:
How do I build a runtime version agnostic DLL in C++?
My product is a C++ library, which, on Windows, is distributed as a dll. It makes very little use of the c-runtime (basic iostream and that's it), so I'm sure that all recent versions of the CRT will be fine.

Since my client is supposed to build his application using my dll, I don't want to impose upon him any specific runtime version. I'd like my dll to bind to whatever runtime library version my client's app is using (and I can assume that he'll use dynamic linking for his CRT). After all, isn't that what dynamic linking is all about? Is that possible?

EDIT: linking the dll against the static runtime libs won't work either, because then the static runtime (from the dll) and the dynamic runtime (from the client's application) will be mixed, which is bad.

EDIT: What I'm mainly asking is how do I tell the runtime loader to link my dll against whatever CRT the application is linked with? Something with the manifest, perhaps?
More generally, my question is how to build a nicely-behaving dll, that's to be used by clients building they're own applications?

EDIT: Thanks to the advice in the answers, I've transferred all references to std classes into inlined functions in my headers, and linked my dll with the static runtime libraries. It now seems to work even in applications linked with different CRT versions.

答:
Well, there is a huge difference between the C-runtime and the C++-runtime. If you where to use msvcrt.dll, which in recent years became "knighted" as a true system DLL, you could rely on its existence on XP onwards (though for Windows 2000 you would need some redistributable for the version 6 of msvcrt.dll). You can make use of msvcrt.dll by compiling your code with the compiler from the latest WDKs (Windows Driver Kits). Even though this is user-mode code, this is a viable and good method to compiler it.

IOStreams, however, require the C++-runtime. And that complicates things a lot.

EDIT: linking the dll against the
  static runtime libs won't work either,
  because then the static runtime (from
  the dll) and the dynamic runtime (from
  the client's application) will be
  mixed, which is bad.

Well, if you mix code in such a way, you have something wrong in your design. You would have similar problems when running a debug build of your DLL with a release build of the other code or vice versa.

I can only recommend that you either make direct use of COM, or - if that's too big - try to emulate some ideas of COM. The most important one would be that you have a factory function and that there is an (class) interface declared (and gets never changed) between those two pieces of code (i.e. the DLL and its caller). The factory function would return an instance of the class and the class would manage its lifetime itself (which implies that all code for allocation and deallocation would reside in the same entity, i.e. your DLL). The lifetime management would then be exposed via addref and release member functions. IUnknown could be the basis for this interface of yours without relying on other parts of the actual COM.

EDIT: What I'm mainly asking is how do
  I tell the runtime loader to link my
  dll against whatever CRT the
  application is linked with? Something
  with the manifest, perhaps? More
  generally, my question is how to build
  a nicely-behaving dll, that's to be
  used by clients building they're own
  applications?

Not easy at all. Even if you had all the versions of VS installed, you'd have to script your way out of this dilemma to pick the right version.

ContentLicense: CC BY-SA 3.0


问:
Set height to container in Gridview.builder
I am working with the following code and got struck. I wanted to set the height to the container so that the images which are displayed inside it will be fitted well. In the present condition the image gets fitted inside the container and it does not look good. I have used a grid view to display images from firebase.

```<code>class Catview extends StatefulWidget {
  @override
  _CatviewState createState() => _CatviewState();
}

class _CatviewState extends State<Catview> {
  StreamSubscription<QuerySnapshot> subscription;
  List<DocumentSnapshot> wallpaperList;
  final CollectionReference collectionReference =
      Firestore.instance.collection("pubg");

  @override
  void initState() {
    super.initState();
    subscription = collectionReference.snapshots().listen((datasnapshot) {
      setState(() {
        wallpaperList = datasnapshot.documents;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    subscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return (SafeArea(
      child: Scaffold(
        body: wallpaperList != null
            ? GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 2,
                  mainAxisSpacing: 4,
                ),
                itemCount: wallpaperList.length,
                itemBuilder: (context, index) {
                  String image = wallpaperList[index].data['image'];
                  return Container(
                    color: Colors.red,
                    child: Image.network(
                      image,
                    ),
                  );
                },
              )
            : Center(
                child: CircularProgressIndicator(),
              ),
      ),
    ));
  }
}
</code>```

thank you!

答:
You need to add preperty childAspectRatio in SliverGridDelegateWithFixedCrossAxisCount. childAspectRatio as aspectRatio, because in gridview can't support height dan width. Unless you use this library Staggered Grid View . https://pub.dev/packages/flutter_staggered_grid_view.

this is example if you use gridview without library.

Example:

GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 2,
                  mainAxisSpacing: 4,
                  childAspectRatio: 0.7,
                ),
....

```

ContentLicense: CC BY-SA 4.0

Body:
I am working with the following code and got struck. I wanted to set the height to the container so that the images which are displayed inside it will be fitted well. In the present condition the image gets fitted inside the container and it does not look good. I have used a grid view to display images from firebase.

class Catview extends StatefulWidget {
  @override
  _CatviewState createState() => _CatviewState();
}

class _CatviewState extends State<Catview> {
  StreamSubscription<QuerySnapshot> subscription;
  List<DocumentSnapshot> wallpaperList;
  final CollectionReference collectionReference =
      Firestore.instance.collection("pubg");

  @override
  void initState() {
    super.initState();
    subscription = collectionReference.snapshots().listen((datasnapshot) {
      setState(() {
        wallpaperList = datasnapshot.documents;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    subscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return (SafeArea(
      child: Scaffold(
        body: wallpaperList != null
            ? GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 2,
                  mainAxisSpacing: 4,
                ),
                itemCount: wallpaperList.length,
                itemBuilder: (context, index) {
                  String image = wallpaperList[index].data['image'];
                  return Container(
                    color: Colors.red,
                    child: Image.network(
                      image,
                    ),
                  );
                },
              )
            : Center(
                child: CircularProgressIndicator(),
              ),
      ),
    ));
  }
}

thank you!


问:
How can i put two different threads on a single service?
can someone give me the code example that shows how to use two different threads on a single service? i didnt find the way to do it in google, then i need a code example...

one waiting 5 seconds and the other waiting 60 seconds, with different code

答:
```<code>Thread t5 = new Thread(Runnable_that_waits_5_seconds);
Thread t60 = new Thread(Runnable_that_waits_60_seconds);
t5.start();
t60;start();
</code>```

Now you just need to define your runnables.

Also, you should give your runnables a way to detect that they've been interrupted and terminate if they do, and interrupt each thread in your service's clean-up code.

Body:
Thread t5 = new Thread(Runnable_that_waits_5_seconds);
Thread t60 = new Thread(Runnable_that_waits_60_seconds);
t5.start();
t60;start();

Now you just need to define your runnables.

Also, you should give your runnables a way to detect that they've been interrupted and terminate if they do, and interrupt each thread in your service's clean-up code.


问:
compare multiple columns of 2 tables which some columns having comma separated values in oracle
I'm having 2 tables as below

TABLE A:

TABLE B:

I want to compare the columns of both tables and expected below output.

conditions:

1)All column values should match (atleast one value in comma separated values of a column)

Example :

if we take cbn100(cf1,cf2,cf3 column values) from 2nd table compare with first table M1001 (cf1,cf2,cf3 column values)

M1001.cf1 (co1)     = cbn100.cf1 (co1) - true

M1001.cf2 (co2,co3) = cbn100.cf2 (co2) - true (atleast 1 (co2) value matching)

M1001.cf3 (co4)     = cbn100.cf3 (co4) - true

Hence all values matching, the output should be M1001=cbn100

2)If the Null value is compared with non null value ,condition is true

Example:

If we take cbn103 valUes from 2nd table and compare with m1002 in first table

M1002 (null) = cbn103.cf1(co1) - true

M1002 (null) = cbn103.cf1(co5) - true

M1002 (co7)  =  cbn103.cf3(co7,co4) - true

Hence all condition matches the output should be M1002=cbn103

Expected Output:

答:
Try something like this (may need tweaking, only tested with your data set):

```<code>select result_
from (
  select
    case when
      ( AB1 = 'true' and AB2 = 'true' and AB3 = 'true' )
      or
      ( BA1 = 'true' and BA2 = 'true' and BA3 = 'true' )
      then mfpartno || '=' || cbn
    end result_
  from (
    select
      A.mfpartno
    , B.cbn
    , case when instr( A.cf1, B.cf1 ) > 0 or B.cf1 is null then 'true' else 'false' end AB1
    , case when instr( A.cf2, B.cf2 ) > 0 or B.cf2 is null then 'true' else 'false' end AB2
    , case when instr( A.cf3, B.cf3 ) > 0 or B.cf3 is null then 'true' else 'false' end AB3
    , case when instr( B.cf1, A.cf1 ) > 0 or A.cf1 is null then 'true' else 'false' end BA1
    , case when instr( B.cf2, A.cf2 ) > 0 or A.cf2 is null then 'true' else 'false' end BA2
    , case when instr( B.cf3, A.cf3 ) > 0 or A.cf3 is null then 'true' else 'false' end BA3
    from tablea A cross join tableb B
  )
)
where result_ is not null
;
</code>```

Result

```<code>        RESULT_
_______________
M1001=cbn100
M1002=cbn103
</code>```

Explanation

The inner query uses a CROSS JOIN, which allows us to compare all possible combinations of rows.  INSTR() is used for detecting whether a string of tableA contains a string from tableB (and vice versa).  There is also a condition for treating NULLs as per your requirements.  If we get 3 'true' results, then a "match" has been found.
DBfiddle here.

Body:
Try something like this (may need tweaking, only tested with your data set):

select result_
from (
  select
    case when
      ( AB1 = 'true' and AB2 = 'true' and AB3 = 'true' )
      or
      ( BA1 = 'true' and BA2 = 'true' and BA3 = 'true' )
      then mfpartno || '=' || cbn
    end result_
  from (
    select
      A.mfpartno
    , B.cbn
    , case when instr( A.cf1, B.cf1 ) > 0 or B.cf1 is null then 'true' else 'false' end AB1
    , case when instr( A.cf2, B.cf2 ) > 0 or B.cf2 is null then 'true' else 'false' end AB2
    , case when instr( A.cf3, B.cf3 ) > 0 or B.cf3 is null then 'true' else 'false' end AB3
    , case when instr( B.cf1, A.cf1 ) > 0 or A.cf1 is null then 'true' else 'false' end BA1
    , case when instr( B.cf2, A.cf2 ) > 0 or A.cf2 is null then 'true' else 'false' end BA2
    , case when instr( B.cf3, A.cf3 ) > 0 or A.cf3 is null then 'true' else 'false' end BA3
    from tablea A cross join tableb B
  )
)
where result_ is not null
;

Result

        RESULT_
_______________
M1001=cbn100
M1002=cbn103

Explanation

The inner query uses a CROSS JOIN, which allows us to compare all possible combinations of rows.  INSTR() is used for detecting whether a string of tableA contains a string from tableB (and vice versa).  There is also a condition for treating NULLs as per your requirements.  If we get 3 'true' results, then a "match" has been found.
DBfiddle here.


问:
Sharing a file between two Azure App Services
I need two applications hosted on two Azure App Services to access one specific file(.xml). What is my best option? What are my options?

I am trying to implement: Share authentication cookies among ASP.NET apps.
Both apps have to access the COMMON KEY RING FOLDER with the key file.

One of the applications is ASP.NET MVC, the second one is ASP.NET Core, both run on .NET472

Edit:
I need a file to be accessible for two .net applications running as appservices. I will use C#/F# to read/write the file. The file must be on Azure.

答:
I recomend you to use an Azure Blob Storage and read the xml from there.

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet


问:
finding nearby locations
How to get the locations nearby me? I've got a latitude and location. Based on this, I want to get nearest locations.

How can this be done?

答: Get list of places surrounding user's current location</p>

ContentLicense: CC BY-SA 2.5

Title: finding nearby locations


问:
Wordpress Admin Bar Not Showing in Front End
I have a [shayari website]1 . The issue with this website is when i am posting some shayari and status i am unable to see the admin bar in front end
I Am using Publisher Theme

答: Go to admin > Users > YOUR USERNAME and check the box that says Show Toolbar when viewing site</p>


问:
Angular Typescript assign values to class properties dynamically
I have a class and a json object I want the the items in the json object to update the new class. Using Angular 9

class

```<code>export class Searchdata{
  name:boolean=false;
  age:boolean=false;
  summer:boolean=false;
  winter:boolean=false;
  football:boolean=false;
  tennis:boolean=false;
}

</code>```

and the json

```<code>[
   {
"name": "name",
"visible": true,
},
{
"name": "age",
"visible": true
}, {
"name": "football",
"visible": true
}

]

</code>```

Json does not always have the same number of elements as the class has properties but if solves it easier it can have all the same number of items. I have tried a number of solutions so for illustrative purposes I below is how I envisaged it working.

```<code>permPageData:any="The JsonObject";
tableSearchModel:Searchdata;

someFunction(){
this.tableSearchModel = new Searchdata();

permPageData.forEach(element => {
      if(element.name == this.tableSearchModel["element.name"])
        this.tableSearchModel[element.name] = element.visible;
}
return this.tableSearchModel;
}

</code>```

答:
I think if you are going to use a class to represent your model SearchData, then it should be a method of the SearchData.

Something like this,

.ts

```<code>class Searchdata{
  name = false;
  age = false;
  summer = false;
  winter = false;
  football = false;
  tennis = false;

  constructor() {}

  setFromJSON(obj: Array<{name:string,visible:boolean}>) {
    obj.forEach(element => {
      this[element.name] = element.visible;
    });
  }

  toString() {
    return `{name:${this.name},age:${this.age},summer:${this.summer},winter:${this.winter},football:${this.football},tennis:${this.tennis}}`;
  }
}

const permPageData = [
  {
    "name": "name",
    "visible": true,
  },
  {
    "name": "age",
    "visible": true
  }, {
    "name": "football",
    "visible": true
  }
];

const tableSearchModel = new Searchdata();
console.log(tableSearchModel.toString());
tableSearchModel.setFromJSON(permPageData);
console.log(tableSearchModel.toString());
</code>```

output

```<code>{name:false,age:false,summer:false,winter:false,football:false,tennis:false}
{name:true,age:true,summer:false,winter:false,football:true,tennis:false}
</code>```

Although it is quite different approach, I had found interface pretty interest.

.ts

```<code>interface Searchdata{
  name: boolean;
  age: boolean;
  summer: boolean;
  winter: boolean;
  football: boolean;
  tennis: boolean;
}

function searchDataNew(): Searchdata {
  return {
    name: false,
    age: false,
    summer: false,
    winter: false,
    football: false,
    tennis: false
  };
}

function searchDataToString(sd: Searchdata) {
  return `{name:${sd.name},age:${sd.age},summer:${sd.summer},winter:${sd.winter},football:${sd.football},tennis:${sd.tennis}}`;
}

function arrayDataToObjData(arr: Array<{name:string,visible:boolean}>): Searchdata {
  const obj: any = {};
  arr.forEach(element => {
    obj[element.name] = element.visible;
  });
  return obj;
}

const permPageData = [
  {
    "name": "name",
    "visible": true,
  },
  {
    "name": "age",
    "visible": true
  }, {
    "name": "football",
    "visible": true
  }
];

const tableSearchModel: Searchdata = {
  ...searchDataNew(),
  ...arrayDataToObjData(permPageData2)
};
console.log(searchDataToString(tableSearchModel));
</code>```

result

```<code>{name:true,age:true,summer:false,winter:false,football:true,tennis:false}
</code>```

Body:
I have a class and a json object I want the the items in the json object to update the new class. Using Angular 9

class

export class Searchdata{
  name:boolean=false;
  age:boolean=false;
  summer:boolean=false;
  winter:boolean=false;
  football:boolean=false;
  tennis:boolean=false;
}

and the json

[
   {
"name": "name",
"visible": true,
},
{
"name": "age",
"visible": true
}, {
"name": "football",
"visible": true
}

]

Json does not always have the same number of elements as the class has properties but if solves it easier it can have all the same number of items. I have tried a number of solutions so for illustrative purposes I below is how I envisaged it working.

permPageData:any="The JsonObject";
tableSearchModel:Searchdata;

someFunction(){
this.tableSearchModel = new Searchdata();

permPageData.forEach(element => {
      if(element.name == this.tableSearchModel["element.name"])
        this.tableSearchModel[element.name] = element.visible;
}
return this.tableSearchModel;
}

Body:
I think if you are going to use a class to represent your model SearchData, then it should be a method of the SearchData.

Something like this,

.ts

class Searchdata{
  name = false;
  age = false;
  summer = false;
  winter = false;
  football = false;
  tennis = false;

  constructor() {}

  setFromJSON(obj: Array<{name:string,visible:boolean}>) {
    obj.forEach(element => {
      this[element.name] = element.visible;
    });
  }

  toString() {
    return `{name:${this.name},age:${this.age},summer:${this.summer},winter:${this.winter},football:${this.football},tennis:${this.tennis}}`;
  }
}

const permPageData = [
  {
    "name": "name",
    "visible": true,
  },
  {
    "name": "age",
    "visible": true
  }, {
    "name": "football",
    "visible": true
  }
];

const tableSearchModel = new Searchdata();
console.log(tableSearchModel.toString());
tableSearchModel.setFromJSON(permPageData);
console.log(tableSearchModel.toString());

output

{name:false,age:false,summer:false,winter:false,football:false,tennis:false}
{name:true,age:true,summer:false,winter:false,football:true,tennis:false}

Although it is quite different approach, I had found interface pretty interest.

.ts

interface Searchdata{
  name: boolean;
  age: boolean;
  summer: boolean;
  winter: boolean;
  football: boolean;
  tennis: boolean;
}

function searchDataNew(): Searchdata {
  return {
    name: false,
    age: false,
    summer: false,
    winter: false,
    football: false,
    tennis: false
  };
}

function searchDataToString(sd: Searchdata) {
  return `{name:${sd.name},age:${sd.age},summer:${sd.summer},winter:${sd.winter},football:${sd.football},tennis:${sd.tennis}}`;
}

function arrayDataToObjData(arr: Array<{name:string,visible:boolean}>): Searchdata {
  const obj: any = {};
  arr.forEach(element => {
    obj[element.name] = element.visible;
  });
  return obj;
}

const permPageData = [
  {
    "name": "name",
    "visible": true,
  },
  {
    "name": "age",
    "visible": true
  }, {
    "name": "football",
    "visible": true
  }
];

const tableSearchModel: Searchdata = {
  ...searchDataNew(),
  ...arrayDataToObjData(permPageData2)
};
console.log(searchDataToString(tableSearchModel));

result

{name:true,age:true,summer:false,winter:false,football:true,tennis:false}


问:
stdout and need to flush it C++
I have some C++ code that uses cout statements for debug purposes and for some reason I can't get all the data to print unless I do a std::cout.flush(); at the end.

I don't quite understand why this flush operation is needed.

Anyone have any insight?

答:
Are you using std::endl to terminate your lines.  This should be the
usual practice, until performance issues require otherwise, but for some
reason, I see a lot of code which uses '\n' instead.

Otherwise, you can always do:

```<code>std::cout.setf( std::ios_base::unitbuf );
</code>```

as one of the first things in main.  This will cause a flush at the
end of every <<, which is more than you need, but for diagnostic
output to the console, is probably quite acceptable.

Title: stdout and need to flush it C++

Body:
Are you using std::endl to terminate your lines.  This should be the
usual practice, until performance issues require otherwise, but for some
reason, I see a lot of code which uses '\n' instead.

Otherwise, you can always do:

std::cout.setf( std::ios_base::unitbuf );

as one of the first things in main.  This will cause a flush at the
end of every <<, which is more than you need, but for diagnostic
output to the console, is probably quite acceptable.


问:
Java Read Parquet File to JSON Output
Reading parquet file is working but getting indented format instead of a desired JSON output format. Any ideas? I was thinking that I may need to change GroupRecordConverter but wasn't able to find much documentation. If can point me to that, would also be helpful. Thanks very much for the help.

```<code>long num = numLines;
try {
  ParquetMetadata readFooter = ParquetFileReader.readFooter(conf, path, ParquetMetadataConverter.NO_FILTER);
  MessageType schema = readFooter.getFileMetaData().getSchema();
  ParquetFileReader r = new ParquetFileReader(conf,path,readFooter);

  PageReadStore pages = null;
  try{
    while(null != (pages = r.readNextRowGroup())) {
      final long rows = pages.getRowCount();
      System.out.println("Number of rows: " + rows);

      final MessageColumnIO columnIO = new ColumnIOFactory().getColumnIO(schema);
      final RecordReader recordReader = columnIO.getRecordReader(pages, new GroupRecordConverter(schema));
      String sTemp = "";
      for(int i=0; i<rows && num-->0; i++) {
        System.out.println(recordReader.read().toString())
      }
    }
  }
}
</code>```

Current indented output:

```<code>data1: value1
data2: value2
models
  map
    key: data3
    value
      array: value3
  map
    key: data4
    value
      array: value4
data5: value5
...
</code>```

Desired JSON output:

```<code>"data1": "value1",
"data2": "value2",
"models": {
    "data3": [
        "value3"
    ],
    "data4": [
        "value4"
    ]
},
"data5": "value5"
...
</code>```

答:
I modify the source code of SimpleRecord toJsonObject method </p>

```<code>
protected Object toJsonObject() {
    Map<String, Object> result = Maps.newLinkedHashMap();

    if (arrayElement()) {
      return handleArrayElement(result);
    }

    for (NameValue value : values) {
      result.put(value.getName(), toJsonValue(value.getValue()));
    }

    return result;
  }
</code>```

Title: Java Read Parquet File to JSON Output

Body:
Reading parquet file is working but getting indented format instead of a desired JSON output format. Any ideas? I was thinking that I may need to change GroupRecordConverter but wasn't able to find much documentation. If can point me to that, would also be helpful. Thanks very much for the help.

long num = numLines;
try {
  ParquetMetadata readFooter = ParquetFileReader.readFooter(conf, path, ParquetMetadataConverter.NO_FILTER);
  MessageType schema = readFooter.getFileMetaData().getSchema();
  ParquetFileReader r = new ParquetFileReader(conf,path,readFooter);

  PageReadStore pages = null;
  try{
    while(null != (pages = r.readNextRowGroup())) {
      final long rows = pages.getRowCount();
      System.out.println("Number of rows: " + rows);

      final MessageColumnIO columnIO = new ColumnIOFactory().getColumnIO(schema);
      final RecordReader recordReader = columnIO.getRecordReader(pages, new GroupRecordConverter(schema));
      String sTemp = "";
      for(int i=0; i<rows && num-->0; i++) {
        System.out.println(recordReader.read().toString())
      }
    }
  }
}

Current indented output:

data1: value1
data2: value2
models
  map
    key: data3
    value
      array: value3
  map
    key: data4
    value
      array: value4
data5: value5
...

Desired JSON output:

"data1": "value1",
"data2": "value2",
"models": {
    "data3": [
        "value3"
    ],
    "data4": [
        "value4"
    ]
},
"data5": "value5"
...

Body:
I modify the source code of SimpleRecord toJsonObject method

protected Object toJsonObject() {
    Map<String, Object> result = Maps.newLinkedHashMap();

    if (arrayElement()) {
      return handleArrayElement(result);
    }

    for (NameValue value : values) {
      result.put(value.getName(), toJsonValue(value.getValue()));
    }

    return result;
  }


问:
getLayoutInflater cannot resolve
This code belongs my arrayadapter for custom spinner.I'm getting error of cannot resolve method on getLayoutInflater() method and I don't know why.
Any help will be appreciated.

```<code>    public View getCustomView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater= getLayoutInflater();
    View mySpinner = inflater.inflate(R.layout.spinneritems, parent, false);

    TextView main_text = (TextView) mySpinner.findViewById(R.id.spinneritem);
    main_text.setText(spinnerValues[position]);
    return mySpinner;
}
</code>```

}

答:
Try this one works for me.

```<code>LayoutInflater inflater= LayoutInflater.from(context);
</code>```

Title: getLayoutInflater cannot resolve

Body:
This code belongs my arrayadapter for custom spinner.I'm getting error of cannot resolve method on getLayoutInflater() method and I don't know why.
Any help will be appreciated.

    public View getCustomView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater= getLayoutInflater();
    View mySpinner = inflater.inflate(R.layout.spinneritems, parent, false);

    TextView main_text = (TextView) mySpinner.findViewById(R.id.spinneritem);
    main_text.setText(spinnerValues[position]);
    return mySpinner;
}

}

Body:
Try this one works for me.

LayoutInflater inflater= LayoutInflater.from(context);


问:
How to send all members a message in on_ready event discord.py
When my bot starts up, I want it to send a message to all the members in each server, for example I want it to say Hello.

Any ideas?

@bot.event
async def on_ready():
    sentmessage.toallmember.allserver("Hello")
    print("[+] Bot is ready")
```

答:
Do not use this maliciously.

@bot.event
async def on_ready():
    for m in bot.get_all_members():
        try: # this can fail if a user has DMs disabled
            await m.send("Something here")
        except:
            pass
    print("[+] Bot is ready")
```

References:

Client.get_all_members()

Member.send()

Body:
Do not use this maliciously.

@bot.event
async def on_ready():
    for m in bot.get_all_members():
        try: # this can fail if a user has DMs disabled
            await m.send("Something here")
        except:
            pass
    print("[+] Bot is ready")

References:

Client.get_all_members()

Member.send()


Title: Forward fill NaN by id up to last value and 2 more times after last value

Body:
Task

I have the following df and want to forward fill the NaN by each id with the previous value. On the last value in each column, I want it to only forward fill 2 more times.

I currently use this:

df.set_index(['id', 'date'], inplace=True)
df = df.ffill().where(df.bfill().notnull())

However, it forward fills more than the desired 2 times. Any help would be super!

df

   id      date     compname   fyr
1   1   2016-02-29     a        5.0
2   1   2016-03-31    NaN       NaN
3   1   2016-04-30    NaN       NaN
4   1   2016-05-31     a        5.0
5   1   2016-06-30    NaN       NaN
6   1   2016-07-31    NaN       NaN
7   1   2016-08-31     a        5.0
8   1   2016-09-30    NaN       NaN
9   1   2016-10-31    NaN       NaN
10  1   2016-11-30     a        5.0
11  1   2016-12-31    NaN       NaN
12  1   2017-01-31    NaN       NaN
13  1   2017-02-28    NaN       NaN
14  1   2017-03-31    NaN       NaN
15  2   2016-02-29     b        5.0
16  2   2016-03-31    NaN       NaN
17  2   2016-04-30    NaN       NaN
18  2   2016-05-31     b        5.0
19  2   2016-06-30    NaN       NaN
20  2   2016-07-31    NaN       NaN
21  2   2016-08-31     b        5.0
22  2   2016-09-30    NaN       NaN
23  2   2016-10-31    NaN       NaN
24  2   2016-11-30     b        5.0
25  2   2016-12-31    NaN       NaN
26  2   2017-01-31    NaN       NaN
27  2   2017-02-28    NaN       NaN
28  2   2017-03-31    NaN       NaN

desired df

   id      date     compname   fyr
1   1   2016-02-29     a       5.0
2   1   2016-03-31     a       5.0
3   1   2016-04-30     a       5.0
4   1   2016-05-31     a       5.0
5   1   2016-06-30     a       5.0
6   1   2016-07-31     a       5.0
7   1   2016-08-31     a       5.0
8   1   2016-09-30     a       5.0
9   1   2016-10-31     a       5.0
10  1   2016-11-30     a       5.0
11  1   2016-12-31     a       5.0
12  1   2017-01-31     a       5.0
13  1   2017-02-28    NaN      NaN
14  1   2017-03-31    NaN      NaN
15  2   2016-02-29     b       5.0
16  2   2016-03-31     b       5.0
17  2   2016-04-30     b       5.0
18  2   2016-05-31     b       5.0
19  2   2016-06-30     b       5.0
20  2   2016-07-31     b       5.0
21  2   2016-08-31     b       5.0
22  2   2016-09-30     b       5.0
23  2   2016-10-31     b       5.0
24  2   2016-11-30     b       5.0
25  2   2016-12-31     b       5.0
26  2   2017-01-31     b       5.0
27  2   2017-02-28    NaN      NaN
28  2   2017-03-31    NaN      NaN

Body:
If need back and forward filling per groups only 2 values add parameter limit to bfill and ffill methods:

f = lambda x: x.bfill(limit=2).ffill(limit=2)
df[["compname","fyr"]] = df.groupby("id")[["compname","fyr"]].apply(f)
print (df)
    id        date compname  fyr
1    1  2016-02-29        a  5.0
2    1  2016-03-31        a  5.0
3    1  2016-04-30        a  5.0
4    1  2016-05-31        a  5.0
5    1  2016-06-30        a  5.0
6    1  2016-07-31        a  5.0
7    1  2016-08-31        a  5.0
8    1  2016-09-30        a  5.0
9    1  2016-10-31        a  5.0
10   1  2016-11-30        a  5.0
11   1  2016-12-31        a  5.0
12   1  2017-01-31        a  5.0
13   1  2017-02-28      NaN  NaN
14   1  2017-03-31      NaN  NaN
15   2  2016-02-29        b  5.0
16   2  2016-03-31        b  5.0
17   2  2016-04-30        b  5.0
18   2  2016-05-31        b  5.0
19   2  2016-06-30        b  5.0
20   2  2016-07-31        b  5.0
21   2  2016-08-31        b  5.0
22   2  2016-09-30        b  5.0
23   2  2016-10-31        b  5.0
24   2  2016-11-30        b  5.0
25   2  2016-12-31        b  5.0
26   2  2017-01-31        b  5.0
27   2  2017-02-28      NaN  NaN
28   2  2017-03-31      NaN  NaN


问:
Syntax error help
I seem to have a syntax error and can't see it myself, could someone run over it for me please?

Thanks.

```<code><script>
    var acurl_<?php echo $request_data['friendship_id']; ?> = "sn-include/create_bond_accept.php?friendship_id=<?php echo $request_data['friendship_id']; ?>&friend_id=<?php echo $fromuser['id']; ?>";
</script>
</code>```

答:
Because you got some answers that intended to show you how to improve your code, but actually don't do so (IMO), here is my attempt:

```<code><?php
    $acurl = array();
    $acurl[$request_data['friendship_id']] = sprintf('sn-include/create_bond_accept.php?friendship_id=%s&friend_id=%s', $request_data['friendship_id'], $fromuser['id']);
?>

<script>
    var acurl = <?php echo json_encode($acurl); ?>
</script>
</code>```

I would not create dynamic variable names. This code would create a JS object, where the properties are the friendship IDs, something like:

```<code>{
    '42': 'sn-include/create_bond_accept...'
}
</code>```

You can access these URLs more easily from JavaScript than if you have dynamic variable names.

Title: Syntax error help

Body:
Because you got some answers that intended to show you how to improve your code, but actually don't do so (IMO), here is my attempt:

<?php
    $acurl = array();
    $acurl[$request_data['friendship_id']] = sprintf('sn-include/create_bond_accept.php?friendship_id=%s&friend_id=%s', $request_data['friendship_id'], $fromuser['id']);
?>

<script>
    var acurl = <?php echo json_encode($acurl); ?>
</script>

I would not create dynamic variable names. This code would create a JS object, where the properties are the friendship IDs, something like:

{
    '42': 'sn-include/create_bond_accept...'
}

You can access these URLs more easily from JavaScript than if you have dynamic variable names.


问:
Is It possible to start a Group FaceTime call with URL schemes (FaceTime Links)?
I know I can start a FaceTime call from within my iOS app with URL Schemes like this:

facetime://user@example.com

I was wondering if it is also possible to start a FaceTime call with multiple users. Tried to separate it with a , or ; but it didn't work.

More information on FaceTime links:

https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/FacetimeLinks/FacetimeLinks.html#//apple_ref/doc/uid/TP40007899-CH2-SW1

答:
So I've been in contact with Apple and it turns out there is a URL scheme for group calls:

facetime-group://?remoteMembers=+12345678901;participant2@apple.com;+23456789012&isVideoEnabled=1 (make the last term 0 if you want to start with your camera off… works the same as tapping Audio when starting a Group FaceTime call)


问:
what is the difference between GtkImage and GdkPixbuf？
I want to insert an image to a GTKTextView. Should I use GtkImage or GdkPixbuf? there is no information about GdkPixbuf in Devhelp. </p>

答:
Gtk.Image is the GUI widget which allows you to "see" the image. That is display it. GdkPixbuf is a library for loading the image for processing (scaling, viewing etc.)

When you want to insert a widget into GtkTextView, use Gtk.Image.
The Python API for GdkPixbuf is here : https://lazka.github.io/pgi-docs/#GdkPixbuf-2.0
C Version : https://developer.gnome.org/gdk-pixbuf/


问:
Jupyter Notebook will not open on Mac (.zsh)
I know for this issue there are some solutions but they didn't work for me. And I don't understand how I can do. I guess I have to change PATH stuff, but I don't understand to be honest.

My terminal .zsh (I can't change this with .bash, because I have to use it.)
My system Mac OS Catalina

I installed Anaconda. When I try to launch Jupyter Notebook on Anaconda, Jupiter notebook doesn't open on the web browser, it says waiting for localhost.
And when I try to launch Jupyter Notebook in terminal with code 'jupyter notebook'. It says 'zsh: command not found: jupyter'

Please help, this thing drive me crazy.

答: I solved this problem. The reason for this was the Antivirus program. It blocks to open Jupyter Notebook on the web browser. If you have same problem, remove your antivirus program. </p>


问:
How to add a custom WooCommerce product type that extends WC_Product_Variable to the cart
I've created a custom WooCommerce product type that's based on the built-in variable product type. I want to have both product variations and custom characteristics and fields specific to my product type. This is all working and displaying fine in the admin and my custom front-end product page template.

Here's my custom product, for reference:

add_action( 'init', 'register_book_type' );
function register_book_type () {
    class WC_Product_Book extends WC_Product_Variable {
        public function __construct( $product ) {
            parent::__construct( $product );
        }

        public function get_type() {
            return 'book';
        }
    }
}
```

<p>However, when I post the product with its variation to the cart, the behavior messes up because the code <code>$adding_to_cart->get_type()</code> in <code>add_to_cart_action()</code> (in the <code>WC_Form_Handler</code> class) is identifying the product as my custom "book" type and not treating it as a "variable" product and falling back to treating it as a "simple" product type by default.</p>

<p>Here's that built-in WooCommerce area that's causing me trouble:</p>

```$add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->get_type(), $adding_to_cart );
if ( 'variable' === $add_to_cart_handler || 'variation' === $add_to_cart_handler ) {
    $was_added_to_cart = self::add_to_cart_handler_variable( $product_id );
} elseif ( 'grouped' === $add_to_cart_handler ) {
    $was_added_to_cart = self::add_to_cart_handler_grouped( $product_id );
} elseif ( has_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler ) ) {
    do_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler, $url ); // Custom handler.
} else {
    $was_added_to_cart = self::add_to_cart_handler_simple( $product_id );
}
```

The problem seems to be that my own get_type() method returns "book" when this code is expecting "variable." I need it to return "book" so the product edit page will recognize the type properly.

I know I can remove and replace the add_to_cart_action() function in my own code to override this behavior and add my custom type, but then I'm unable to call all the other private methods in the WC_Form_Handler class. Or is it okay to just override that entire class..?

Any other way to bypass all this to get my variable-based custom product into the shopping cart?

答:
This is how I solved this issue:

```<code>public function get_type()
{
    return get_current_screen()->id === 'product' ? 'book' : parent::get_type();
}
</code>```

This will return book on the edit product page however return variable everywhere else.

Body:
I've created a custom WooCommerce product type that's based on the built-in variable product type. I want to have both product variations and custom characteristics and fields specific to my product type. This is all working and displaying fine in the admin and my custom front-end product page template.

Here's my custom product, for reference:

add_action( 'init', 'register_book_type' );
function register_book_type () {
    class WC_Product_Book extends WC_Product_Variable {
        public function __construct( $product ) {
            parent::__construct( $product );
        }

        public function get_type() {
            return 'book';
        }
    }
}

However, when I post the product with its variation to the cart, the behavior messes up because the code $adding_to_cart->get_type() in add_to_cart_action() (in the WC_Form_Handler class) is identifying the product as my custom "book" type and not treating it as a "variable" product and falling back to treating it as a "simple" product type by default.

Here's that built-in WooCommerce area that's causing me trouble:

$add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->get_type(), $adding_to_cart );
if ( 'variable' === $add_to_cart_handler || 'variation' === $add_to_cart_handler ) {
    $was_added_to_cart = self::add_to_cart_handler_variable( $product_id );
} elseif ( 'grouped' === $add_to_cart_handler ) {
    $was_added_to_cart = self::add_to_cart_handler_grouped( $product_id );
} elseif ( has_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler ) ) {
    do_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler, $url ); // Custom handler.
} else {
    $was_added_to_cart = self::add_to_cart_handler_simple( $product_id );
}

The problem seems to be that my own get_type() method returns "book" when this code is expecting "variable." I need it to return "book" so the product edit page will recognize the type properly.

I know I can remove and replace the add_to_cart_action() function in my own code to override this behavior and add my custom type, but then I'm unable to call all the other private methods in the WC_Form_Handler class. Or is it okay to just override that entire class..?

Any other way to bypass all this to get my variable-based custom product into the shopping cart?

Body:
This is how I solved this issue:

public function get_type()
{
    return get_current_screen()->id === 'product' ? 'book' : parent::get_type();
}

This will return book on the edit product page however return variable everywhere else.


问:
Hide character with jQuery inside a span with a class
I've looked for the solution to this but nothing seems to be working.

I have an SKU within a span with a class of "sku". Some of the SKUs have periods before the SKU to allow for adding more than one product with the same SKU.

I'd like to hide the periods when the SKU is displayed though.

This is my code:

..THESKU

And this is the jQuery I am using:

```<code><script>
    $('span.sku').html($('span.sku').html().replace('.',''));
</script>
</code>```

Is the right, or am I missing something? Thanks.

答:
I just wanted to give an update with this. I still couldn't get the periods to hide, but I found a way to have duplicate SKUs so there was no longer a need for this. Thanks for all your help.

If anyone has a similar issue, the code I used is below which I added to the themes functions file.

add_filter( 'wc_product_has_unique_sku', '__return_false', PHP_INT_MAX );

Body:
I've looked for the solution to this but nothing seems to be working.

I have an SKU within a span with a class of "sku". Some of the SKUs have periods before the SKU to allow for adding more than one product with the same SKU.

I'd like to hide the periods when the SKU is displayed though.

This is my code:

..THESKU

And this is the jQuery I am using:

Is the right, or am I missing something? Thanks.


问:
How to send a message outside the controller?
I need to send information to the connected clients outside the HUB.

Here my class :

```<code>public static class Notification{
  public static void SendMessage(){
    //... Do some stuff
    MyHub.Clients.All.SendAsync("sendInfo");
  }
}
</code>```

How to instantiate HUB?

答:
You do as @Brando Zhang posted above or just inject the Hub in to your controller or manager like:

Controller

private IHubContext<YourHub, IYourHub> YourHub
{
    get
    {
        return this.HttpContext.RequestServices.GetRequiredService<IHubContext<YourHub, IYourHub>>();
    }
}
```

<p>Other</p>

<pre class="lang-cs prettyprint-override"><code>private IHubContext<YourHub, IYourHub> YourHub
{
    get
    {
        return this.serviceProvider.GetRequiredService<IHubContext<YourHub, IYourHub>>();
    }
}
</code>```

PS: It is recomended to inject the HubContext and not the hub directly.

Body:
I need to send information to the connected clients outside the HUB.

Here my class :

public static class Notification{
  public static void SendMessage(){
    //... Do some stuff
    MyHub.Clients.All.SendAsync("sendInfo");
  }
}

How to instantiate HUB?

Body:
You do as @Brando Zhang posted above or just inject the Hub in to your controller or manager like:

Controller

private IHubContext<YourHub, IYourHub> YourHub
{
    get
    {
        return this.HttpContext.RequestServices.GetRequiredService<IHubContext<YourHub, IYourHub>>();
    }
}

Other

private IHubContext<YourHub, IYourHub> YourHub
{
    get
    {
        return this.serviceProvider.GetRequiredService<IHubContext<YourHub, IYourHub>>();
    }
}

PS: It is recomended to inject the HubContext and not the hub directly.


问:
Preload fonts to speed up website, don't download them twice?
I want to preload the both fonts I am using from this file here: https://res.cloudinary.com/prodigy-official-de/raw/upload/v1581064331/www.prodigy-official.de%20resources/fonts/font.style.css

So what I tried is this code here:

```<code><link rel="preload" href="https://res.cloudinary.com/prodigy-official-de/raw/upload/v1578333925/www.prodigy-official.de%20resources/fonts/XRXV3I6Li01BKofINeaB.woff2" as="font">
<link rel="preload" href="https://res.cloudinary.com/prodigy-official-de/raw/upload/v1999999/www.prodigy-official.de%20resources/fonts/icomoon.woff2?10si43" as="font">
</code>```

But! He preloads the both fonts in the links, and downloads the fonts again in the font.style.css. So it don't work. The result is here:

How can I archive to still download the both fonts but only once? and use this prefetch cache in the font-face url?

答:
Try adding to the links

```<code>type="font/woff2" crossorigin
</code>```

so it will be for example

```<code><link rel="preload" href="https://res.cloudinary.com/prodigy-official-de/raw/upload/v1578333925/www.prodigy-official.de%20resources/fonts/XRXV3I6Li01BKofINeaB.woff2" as="font" type="font/woff2" crossorigin>
</code>```

It worked for me and the font file is being downloaded only once, I guess it need it to make sure those are exactly the same files...

CORRECTION!
The answer above is the right way to do that, meaning you must define the also the MIME type in order the file will not be downloaded twice.
BUT
Specifically for the question above, as FAIK, Cloudinary, supports only images and videos! meaning you can serve some raw file from it, but it will not be retrieved with the right MIME type, instead it will be downloaded as document and so, it will be downloaded twice...

Body:
I want to preload the both fonts I am using from this file here: https://res.cloudinary.com/prodigy-official-de/raw/upload/v1581064331/www.prodigy-official.de%20resources/fonts/font.style.css

So what I tried is this code here:

<link rel="preload" href="https://res.cloudinary.com/prodigy-official-de/raw/upload/v1578333925/www.prodigy-official.de%20resources/fonts/XRXV3I6Li01BKofINeaB.woff2" as="font">
<link rel="preload" href="https://res.cloudinary.com/prodigy-official-de/raw/upload/v1999999/www.prodigy-official.de%20resources/fonts/icomoon.woff2?10si43" as="font">

But! He preloads the both fonts in the links, and downloads the fonts again in the font.style.css. So it don't work. The result is here:

How can I archive to still download the both fonts but only once? and use this prefetch cache in the font-face url?

Body:
Try adding to the links

type="font/woff2" crossorigin

so it will be for example

<link rel="preload" href="https://res.cloudinary.com/prodigy-official-de/raw/upload/v1578333925/www.prodigy-official.de%20resources/fonts/XRXV3I6Li01BKofINeaB.woff2" as="font" type="font/woff2" crossorigin>

It worked for me and the font file is being downloaded only once, I guess it need it to make sure those are exactly the same files...

CORRECTION!
The answer above is the right way to do that, meaning you must define the also the MIME type in order the file will not be downloaded twice.
BUT
Specifically for the question above, as FAIK, Cloudinary, supports only images and videos! meaning you can serve some raw file from it, but it will not be retrieved with the right MIME type, instead it will be downloaded as document and so, it will be downloaded twice...


问:
How to display soft keyboard after AlertDialog show
I have Google this proplem, but none of the answers works for me.
This is the style of my AlertDialog

```<code><style name="dialog_full_screen">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowFrame">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:backgroundDimEnabled">true</item>
</style>
</code>```

This is the code to show it.

```<code>  val alertDialog = AlertDialog.Builder(this, R.style.dialog_full_screen).apply {
            setCancelable(true)
        }.create()
        alertDialog.apply {
            val wlp = window!!.attributes
            wlp.gravity = Gravity.BOTTOM
            wlp.flags = wlp.flags and WindowManager.LayoutParams.FLAG_DIM_BEHIND.inv()
            val displayMetrics = DisplayMetrics()
            windowManager.defaultDisplay.getMetrics(displayMetrics)
            wlp.width = displayMetrics.widthPixels
            wlp.height = WindowManager.LayoutParams.WRAP_CONTENT
            window!!.attributes = wlp
        }
        alertDialog.show()
</code>```

The following code is layout

```<code><LinearLayout
    android:id="@+id/linear_layout_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    style="@style/CenterInConstraintLayout"
    tools:ignore="MissingConstraints">

<ImageView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:src="@drawable/index_play_page_icon_comments_null"
    />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/homepage_no_comments"
    android:textColor="@color/color_gray_dark2"
    android:textSize="@dimen/font_size_14"
    />
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    android:gravity="center">
    <EditText
        android:id="@+id/edit_text_comment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:maxLength="150"
        android:hint="@string/homepage_hint_comment"
        android:textColorHint="@color/color_gray_dark2"
        android:background="@null"
        android:importantForAutofill="no" />
    <ImageView
        android:id="@+id/image_view_send"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginEnd="30dp"
        />
</LinearLayout>
</code>```

This AlertDialog can show properly, but i can't show soft keyboard

答:
Give the EditText the type of softkeyboard you want, otherwise default will get applied

```<code>// Get the Edit text box to put into the dialog
final EditText input = findViewById(R.id.edit_text_comment)
// set the type of input entered, this would be for entry of a number digit keyboard
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
...
input.requestFocus();
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

alertDialog.show();
</code>```

There is also  question posted for similar situation here:
when using AlertDialog.Builder with EditText, the Soft Keyboard doesn't pop
or else try this:
How to show soft-keyboard when edittext is focused

Body:
I have Google this proplem, but none of the answers works for me.
This is the style of my AlertDialog

This is the code to show it.

  val alertDialog = AlertDialog.Builder(this, R.style.dialog_full_screen).apply {
            setCancelable(true)
        }.create()
        alertDialog.apply {
            val wlp = window!!.attributes
            wlp.gravity = Gravity.BOTTOM
            wlp.flags = wlp.flags and WindowManager.LayoutParams.FLAG_DIM_BEHIND.inv()
            val displayMetrics = DisplayMetrics()
            windowManager.defaultDisplay.getMetrics(displayMetrics)
            wlp.width = displayMetrics.widthPixels
            wlp.height = WindowManager.LayoutParams.WRAP_CONTENT
            window!!.attributes = wlp
        }
        alertDialog.show()

The following code is layout

<LinearLayout
    android:id="@+id/linear_layout_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    style="@style/CenterInConstraintLayout"
    tools:ignore="MissingConstraints">

<ImageView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:src="@drawable/index_play_page_icon_comments_null"
    />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/homepage_no_comments"
    android:textColor="@color/color_gray_dark2"
    android:textSize="@dimen/font_size_14"
    />
</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    android:gravity="center">
    <EditText
        android:id="@+id/edit_text_comment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:maxLength="150"
        android:hint="@string/homepage_hint_comment"
        android:textColorHint="@color/color_gray_dark2"
        android:background="@null"
        android:importantForAutofill="no" />
    <ImageView
        android:id="@+id/image_view_send"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginEnd="30dp"
        />
</LinearLayout>

This AlertDialog can show properly, but i can't show soft keyboard

Body:
Give the EditText the type of softkeyboard you want, otherwise default will get applied

// Get the Edit text box to put into the dialog
final EditText input = findViewById(R.id.edit_text_comment)
// set the type of input entered, this would be for entry of a number digit keyboard
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
...
input.requestFocus();
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

alertDialog.show();

There is also  question posted for similar situation here:
when using AlertDialog.Builder with EditText, the Soft Keyboard doesn't pop
or else try this:
How to show soft-keyboard when edittext is focused


问:
spring data JPA - mysql - findById() empty unless findAll() called before
I'm struggling with this strange error: the findById() method of a CrudRepository returns Optional.empty, unless findAll() is called before when using mysql.

e.g.

User

```<code>@Entity
public class User {

    @Id
    @GeneratedValue
    private UUID id;

    public UUID getId() {
        return id;
    }

}
</code>```

UserRepository

```<code>public interface UserRepository extends CrudRepository<User, UUID> { }
</code>```

UserService

```<code>@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Transactional
    public UUID create() {
        final User user = new User();
        userRepository.save(user);
        return user.getId();
    }

    @Transactional
    public User find(@PathVariable UUID userId) {
        // userRepository.findAll(); TODO without this functin call, Optinoal.empty is returned by the repo
        return userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException(String.format("missing user:%s", userId)));
    }
}
</code>```

UserApp

```<code>@SpringBootApplication
public class UserApp {

    private static final Logger LOG = LoggerFactory.getLogger(UserApp.class);

    @Autowired
    private UserService userService;

    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        final UUID userId = userService.create();
        final User user = userService.find(userId);
        LOG.info("found user: {}", user.getId());
    }

    public static void main(String[] args) {
        SpringApplication.run(UserApp.class, args);
    }

}
</code>```

application.properties

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/db_test
spring.datasource.username=springuser
spring.datasource.password=ThePassword

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.database=mysql
</code>```

Why does the findAll() method call change the result of findById()?

Edit: Hibernate logs with findAll:

```<code>Hibernate: drop table if exists user
Hibernate: create table user (id binary(255) not null, primary key (id)) engine=MyISAM
Hibernate: insert into user (id) values (?)
Hibernate: select user0_.id as id1_0_ from user user0_
</code>```

Without:

```<code>Hibernate: drop table if exists user
Hibernate: create table user (id binary(255) not null, primary key (id)) engine=MyISAM
Hibernate: insert into user (id) values (?)
Hibernate: select user0_.id as id1_0_0_ from user user0_ where user0_.id=?
</code>```

答: As already written before (but more generically) after some tests my conclusion is that the issue occurs when there is a discrepancy of mandatory fields and database data in @ManyToOne relations. For example, imagine to have a table without constraints of mandatory fields, but at the same time your Hibernate model class with a @ManyToOne(optional = false) constraint. And imagine to populate the table (say with a SQL script), leaving the indicted field as null. When you will try to perform a findById(), a deleteById or whatever operation that implies a get by Id you will experience this (horrible) side effect.

Body:
I'm struggling with this strange error: the findById() method of a CrudRepository returns Optional.empty, unless findAll() is called before when using mysql.

e.g.

User

@Entity
public class User {

    @Id
    @GeneratedValue
    private UUID id;

    public UUID getId() {
        return id;
    }

}

UserRepository

public interface UserRepository extends CrudRepository<User, UUID> { }

UserService

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Transactional
    public UUID create() {
        final User user = new User();
        userRepository.save(user);
        return user.getId();
    }

    @Transactional
    public User find(@PathVariable UUID userId) {
        // userRepository.findAll(); TODO without this functin call, Optinoal.empty is returned by the repo
        return userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException(String.format("missing user:%s", userId)));
    }
}

UserApp

@SpringBootApplication
public class UserApp {

    private static final Logger LOG = LoggerFactory.getLogger(UserApp.class);

    @Autowired
    private UserService userService;

    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        final UUID userId = userService.create();
        final User user = userService.find(userId);
        LOG.info("found user: {}", user.getId());
    }

    public static void main(String[] args) {
        SpringApplication.run(UserApp.class, args);
    }

}

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/db_test
spring.datasource.username=springuser
spring.datasource.password=ThePassword

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.database=mysql

Why does the findAll() method call change the result of findById()?

Edit: Hibernate logs with findAll:

Hibernate: drop table if exists user
Hibernate: create table user (id binary(255) not null, primary key (id)) engine=MyISAM
Hibernate: insert into user (id) values (?)
Hibernate: select user0_.id as id1_0_ from user user0_

Without:

Hibernate: drop table if exists user
Hibernate: create table user (id binary(255) not null, primary key (id)) engine=MyISAM
Hibernate: insert into user (id) values (?)
Hibernate: select user0_.id as id1_0_0_ from user user0_ where user0_.id=?


问:
How to change the font color of a disabled TextBox?
Does anyone know which property sets the text color for disabled control?
I have to display some text in a disabled TextBox and I want to set its color to black.

答:
You can try this.
Override the OnPaint event of the TextBox.

```<code>    protected override void OnPaint(PaintEventArgs e)
{
     SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
     // Draw string to screen.
     e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}
</code>```

set the ControlStyles to "UserPaint"

```<code>public MyTextBox()//constructor
{
     // This call is required by the Windows.Forms Form Designer.
     this.SetStyle(ControlStyles.UserPaint,true);

     InitializeComponent();

     // TODO: Add any initialization after the InitForm call
}
</code>```

Refrence

Or you can try this hack

In Enter event set the focus

```<code>int index=this.Controls.IndexOf(this.textBox1);

this.Controls[index-1].Focus();
</code>```

So your control will not focussed and behave like disabled.

OwnerDisplayName: niko

Body:
You can try this.
Override the OnPaint event of the TextBox.

    protected override void OnPaint(PaintEventArgs e)
{
     SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
     // Draw string to screen.
     e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}

set the ControlStyles to "UserPaint"

public MyTextBox()//constructor
{
     // This call is required by the Windows.Forms Form Designer.
     this.SetStyle(ControlStyles.UserPaint,true);

     InitializeComponent();

     // TODO: Add any initialization after the InitForm call
}

Refrence

Or you can try this hack

In Enter event set the focus

int index=this.Controls.IndexOf(this.textBox1);

this.Controls[index-1].Focus();

So your control will not focussed and behave like disabled.


问:
NBuilder parameterless constructor error
We are using NBuilder for generating test data for our tests. We have a few models with private setters. So setting thos properties is only possible throughout the constructor. The problem is that we get the following error from NBuilder:

CompanyAddressViewModel does not have a default parameterless constructor

I understand the error. Do I really need to create a default constructor in my class?

Here is my NBuilder code:

```<code>Builder<CompanyAddressViewModel>.CreateNew().Build()
</code>```

答:
Former versions uses WithConstructor() method, but it's obsolete in these days, so you should use WithFactory() method:

```<code>Builder<CompanyAddressViewModel>
         .CreateNew()
         .WithFactory(() => new CompanyAddressViewModel("your", "parameter"))
         .Build()
</code>```

Body:
We are using NBuilder for generating test data for our tests. We have a few models with private setters. So setting thos properties is only possible throughout the constructor. The problem is that we get the following error from NBuilder:

CompanyAddressViewModel does not have a default parameterless constructor

I understand the error. Do I really need to create a default constructor in my class?

Here is my NBuilder code:

Builder<CompanyAddressViewModel>.CreateNew().Build()

Body:
Former versions uses WithConstructor() method, but it's obsolete in these days, so you should use WithFactory() method:

Builder<CompanyAddressViewModel>
         .CreateNew()
         .WithFactory(() => new CompanyAddressViewModel("your", "parameter"))
         .Build()


问:
Edit marker size and popup box size
I managed to get the marker and the popup box to appear in the Mapbox API

 However, I don't seem to be able to edit their size and popup size.

```<code>for (let i = 0; i < locations.length; i++) {
  let location = locations[i];

  let marker = new mapboxgl.Marker({ color: '#FF8C00' });

  marker.setLngLat(location.coordinates);

  let popup = new mapboxgl.Popup({ offset: 40 });
  popup.setHTML(location.description);

  marker.setPopup(popup);

  // Display the marker.
  marker.addTo(map);

  // Display the popup.
  popup.addTo(map);
}
</code>```

答:
Mapbox ususally recommends to use the Annotation Plugin to create markers and interact with these.

However, if you would like to stick to the example you have presented, you could follow this Mapbox example in which custom icons are used for the marker symbol. The size of these icons can be adjusted with the iconSize property:

```

Title: Edit marker size and popup box size

Body:
I managed to get the marker and the popup box to appear in the Mapbox API

 However, I don't seem to be able to edit their size and popup size.

for (let i = 0; i < locations.length; i++) {
  let location = locations[i];

  let marker = new mapboxgl.Marker({ color: '#FF8C00' });

  marker.setLngLat(location.coordinates);

  let popup = new mapboxgl.Popup({ offset: 40 });
  popup.setHTML(location.description);

  marker.setPopup(popup);

  // Display the marker.
  marker.addTo(map);

  // Display the popup.
  popup.addTo(map);
}

Body:
Mapbox ususally recommends to use the Annotation Plugin to create markers and interact with these.

However, if you would like to stick to the example you have presented, you could follow this Mapbox example in which custom icons are used for the marker symbol. The size of these icons can be adjusted with the iconSize property:

<script>
 mapboxgl.accessToken = 'access_token';
var geojson = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'message': 'Foo',
'iconSize': [60, 60]
},
'geometry': {
'type': 'Point',
'coordinates': [-66.324462890625, -16.024695711685304]
}
},
{
'type': 'Feature',
'properties': {
'message': 'Bar',
'iconSize': [50, 50]
},
'geometry': {
'type': 'Point',
'coordinates': [-61.2158203125, -15.97189158092897]
}
},
{
'type': 'Feature',
'properties': {
'message': 'Baz',
'iconSize': [40, 40]
},
'geometry': {
'type': 'Point',
'coordinates': [-63.29223632812499, -18.28151823530889]
}
}
]
};

var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-65.017, -16.457],
zoom: 5
});

// add markers to map
geojson.features.forEach(function(marker) {
// create a DOM element for the marker
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage =
'url(https://placekitten.com/g/' +
marker.properties.iconSize.join('/') +
'/)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';

el.addEventListener('click', function() {
window.alert(marker.properties.message);
});

// add marker to map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
</script>


问:
How to make countdown timer print result on single line in C?
I have code here which works as a countdown timer but it prints results on a new line
like this:

```<code>10
9
8
7
6
5
4
3
2
1
</code>```

here is my code:

```<code>int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \n", count);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}
</code>```

what I've tried so far is to change \n to \r to print on a single line but it did not work. I'm trying to make it clear the line and print the next number in the line then clear that and print the next one if that makes sense

答:
Try to add fflush(stdout) after using \r in your printf as mentioned by pmg:

int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \r", count);
                fflush(stdout);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}
```

Body:
I have code here which works as a countdown timer but it prints results on a new line
like this:

10
9
8
7
6
5
4
3
2
1

here is my code:

int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \n", count);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}

what I've tried so far is to change \n to \r to print on a single line but it did not work. I'm trying to make it clear the line and print the next number in the line then clear that and print the next one if that makes sense


问:
How to add custom attributes to mail in OWA?
I need to customize OWA's functionality, add custom properties to the mail, and set/display property values in the edit and read interface, as well as in the mailing list</p>

答:
You can show message details, see Internet message header in Outlook on the Web, OWA and Outlook.com for more information.

If you need to add or display any other information I'd suggest creating a web add-in, see Outlook add-ins overview to get started quickly.


问:
Wordpress - Use image from URL as a post thumbnail
I want to use an external image from URL as a post thumbnail, BUT I don't want to download and store the image in my server

I'm found this code in other guy question:

```<code>
        $filename = "thumbnail_".$post_id".jpg";
        $upload_file = wp_upload_bits( $filename, null, @file_get_contents('http://example.com/image.jpg') );

        if ( ! $upload_file['error'] ) {
          $filename = $upload_file['file'];
          $wp_filetype = wp_check_filetype($filename, null );

          $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_parent'    => $post_id,
            'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
            'post_content'   => '',
            'post_status'    => 'inherit'
          );

          $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
          file_put_contents('attachment_id.txt', print_r($attachment_id, true));

          if ( ! is_wp_error( $attachment_id ) ) {
              require_once(ABSPATH . 'wp-admin/includes/image.php');

              $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
              wp_update_attachment_metadata( $attachment_id, $attachment_data );
              set_post_thumbnail( $post_id, $attachment_id );
          }
        }

</code>```

It downloads the image to my server and also duplicates the image file in my uploads directory (I don't know why)

But I don't wanna download the image how can I achieve this?

答:
Assuming this image is just alternative to the featured image - you could store the URL of the image source in the custom field.

add_post_meta( $post_id, 'image', 'http://example.com/image.jpg' );

Then you can retrieve this URL anywhere you need to.

Body:
I want to use an external image from URL as a post thumbnail, BUT I don't want to download and store the image in my server

I'm found this code in other guy question:

        $filename = "thumbnail_".$post_id".jpg";
        $upload_file = wp_upload_bits( $filename, null, @file_get_contents('http://example.com/image.jpg') );

        if ( ! $upload_file['error'] ) {
          $filename = $upload_file['file'];
          $wp_filetype = wp_check_filetype($filename, null );

          $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_parent'    => $post_id,
            'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
            'post_content'   => '',
            'post_status'    => 'inherit'
          );

          $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
          file_put_contents('attachment_id.txt', print_r($attachment_id, true));

          if ( ! is_wp_error( $attachment_id ) ) {
              require_once(ABSPATH . 'wp-admin/includes/image.php');

              $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
              wp_update_attachment_metadata( $attachment_id, $attachment_data );
              set_post_thumbnail( $post_id, $attachment_id );
          }
        }

It downloads the image to my server and also duplicates the image file in my uploads directory (I don't know why)

But I don't wanna download the image how can I achieve this?


问:
Bearer error - invalid_token - The signature key was not found
I have an Angular 7 application interfacing with a .Net Core 2.2 API back-end.  This is interfacing with Azure Active Directory.

On the Angular 7 side, it is authenticating properly with AAD and I am getting a valid JWT back as verified on jwt.io.

On the .Net Core API side I created a simple test API that has [Authorize] on it.

When I call this method from Angular, after adding the Bearer token, I am getting (as seen in Chrome Debug Tools, Network tab, "Headers"):

WWW-Authenticate: Bearer error="invalid_token", error_description="The
  signature key was not found"

With a HTTP/1.1 401 Unauthorized.

The simplistic test API is:

```<code>    [Route("Secure")]
    [Authorize]
    public IActionResult Secure() => Ok("Secure works");
</code>```

The Angular calling code is also as simple as I can get it:

```<code>    let params : any = {
        responseType: 'text',
        headers: new HttpHeaders({
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        })
    }

    this.http
        .get("https://localhost:5001/api/azureauth/secure", params)
        .subscribe(
            data => { },
            error => { console.error(error); }
        );
</code>```

If I remove the [Authorize] attribute and just call this as a standard GET request from Angular it works fine.

My Startup.cs contains:

```<code>        services
            .AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureADBearer(options => this.Configuration.Bind("AzureAd", options));
</code>```

The options are all properly set (such as ClientId, TenantId, etc) in the appsettings.json and options here is populating as expected.

答:
I had this issue, and it was caused by jwtOptions.Authority not being set in config.

If you are using:

```<code>services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme,
</code>```

And jwtOptions.Authority is set to null or "" you can get this error message.

Body:
I have an Angular 7 application interfacing with a .Net Core 2.2 API back-end.  This is interfacing with Azure Active Directory.

On the Angular 7 side, it is authenticating properly with AAD and I am getting a valid JWT back as verified on jwt.io.

On the .Net Core API side I created a simple test API that has [Authorize] on it.

When I call this method from Angular, after adding the Bearer token, I am getting (as seen in Chrome Debug Tools, Network tab, "Headers"):

WWW-Authenticate: Bearer error="invalid_token", error_description="The
  signature key was not found"

With a HTTP/1.1 401 Unauthorized.

The simplistic test API is:

    [Route("Secure")]
    [Authorize]
    public IActionResult Secure() => Ok("Secure works");

The Angular calling code is also as simple as I can get it:

    let params : any = {
        responseType: 'text',
        headers: new HttpHeaders({
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        })
    }

    this.http
        .get("https://localhost:5001/api/azureauth/secure", params)
        .subscribe(
            data => { },
            error => { console.error(error); }
        );

If I remove the [Authorize] attribute and just call this as a standard GET request from Angular it works fine.

My Startup.cs contains:

        services
            .AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureADBearer(options => this.Configuration.Bind("AzureAd", options));

The options are all properly set (such as ClientId, TenantId, etc) in the appsettings.json and options here is populating as expected.

Body:
I had this issue, and it was caused by jwtOptions.Authority not being set in config.

If you are using:

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme,

And jwtOptions.Authority is set to null or "" you can get this error message.


问:
Android can't find any BLE devices
Here's he problem. I've developed an app for iOS to control an BLE LED device (and a few other things). Everything works fine and smooth. Now I wanted develop the same app for android and I already fail at the scanning of BLE devices. I have tried a few tutorials and sample codes but whatever I do I can't find any devices. I work on a Moto G4 Play. The bluetooth works and I can pair devices in the settings but it won't work with any sample code/tutorial I've tried.
For example this one:
https://github.com/kaviles/BLE_Tutorials

I build this app as it is and it can't find anything.

So I downloaded a BLE Scanner from the Playstore and that works fine to and finds all devices.

I know it's hard to say without any sample code but I've tried so many and I'm not sure if I miss something completely basic.

答: I think that there is a problem with Motorola devices. Motorola devices has location and gps combined into one single option called "location". In other devices ble scanning works when your app has access to location and that's all but if you have Motorola we need also to enable location (gps). It's guite strange and confusing. </p>

Title: Android can't find any BLE devices


问:
Bert Tokenizer is not working despite importing all packages. Is there a new syntax change to this?
Trying to run the tokenizer for Bert but I keep getting errors. Can anyone help where I am going wrong.

```<code>FullTokenizer = bert.bert_tokenization.FullTokenizer
bert_layer = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1", trainable=False)
vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy()
do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()
tokenizer = FullTokenizer(vocab_file, do_lower_case)
</code>```

Error: AttributeError Traceback (most recent call last) in () ----> 1 FullTokenizer = bert.bert_tokenization.FullTokenizer 2 bert_layer = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1", 3 trainable=False) 4 vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy() 5 do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()

AttributeError: module 'bert' has no attribute 'bert_tokenization'

All the below have been imported for reference.

```<code>!pip install bert-for-tf2
!pip install sentencepiece
!pip install bert-tensorflow
!pip install tensorflow==2.0

try:
    %tensorflow_version 2.x
except Exception:
    pass
import tensorflow as to
import tensorflow_hub as hub
from tensorflow.keras import layers
import bert
from bert import tokenization
</code>```

答:
I was caught up in a similar situation before.

Try looking for a folder named "bert" in the directory where your script/notebook is being run. Delete that folder or rename it to something other than "bert". There is a very likely possibility that when you import bert, it tries to access that folder intead of the bert-for-tf2 which you installed in the Python site packages.

If still that doesn't work, try

from bert import tokenization

Body:
Trying to run the tokenizer for Bert but I keep getting errors. Can anyone help where I am going wrong.

FullTokenizer = bert.bert_tokenization.FullTokenizer
bert_layer = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1", trainable=False)
vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy()
do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()
tokenizer = FullTokenizer(vocab_file, do_lower_case)

Error: AttributeError Traceback (most recent call last) in () ----> 1 FullTokenizer = bert.bert_tokenization.FullTokenizer 2 bert_layer = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1", 3 trainable=False) 4 vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy() 5 do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()

AttributeError: module 'bert' has no attribute 'bert_tokenization'

All the below have been imported for reference.

!pip install bert-for-tf2
!pip install sentencepiece
!pip install bert-tensorflow
!pip install tensorflow==2.0

try:
    %tensorflow_version 2.x
except Exception:
    pass
import tensorflow as to
import tensorflow_hub as hub
from tensorflow.keras import layers
import bert
from bert import tokenization


问:
Permissions for Custom Alexa skill says - "This voice model does not support permissions"
I have made a custom Alexa skill from scratch in python but I am not able to change any permissions because that page says - "This voice model does not support permissions " . Can someone please guide me how to resolve this issue.

But in the Alexa document it has shown provision for permissions for custom alexa skill.

here is the link for the above picture- https://developer.amazon.com/en-US/docs/alexa/devconsole/build-your-skill.html#custom-model

答: Amazon resolved the issue now it is showing the options. I guess they might have changed something.</p>


问:
FLEX 4: How do you add a single horizontal line in a Chart/Graph
Here is my question:
I have a hybrid chart that uses bars and lines
I want to add to the right vertical axis a horizontal line that represents a break even

```<code><mx:ColumnChart id="cvpaOpenCloseRatio" x="79" y="107"
                dataProvider="{CF_Closed_to_Opened_by_MonthResult.lastResult}"
                showDataTips="true">
    <mx:horizontalAxis>
        <mx:CategoryAxis id="categoryAxis" categoryField="Month"/>
    </mx:horizontalAxis>
    <mx:verticalAxisRenderers>
        <mx:AxisRenderer placement="left" axis="{v1}"/>
        <mx:AxisRenderer placement="right" axis="{v2}"/>
    </mx:verticalAxisRenderers>

    <mx:series>
        <mx:ColumnSeries id="columnSeries"
                         displayName="Total Closed"
                         yField="ClosedCount"
                         xField="Month"
                         >
            <mx:verticalAxis>
                <mx:LinearAxis id="v1" minimum="0" maximum="300"/>
            </mx:verticalAxis>
        </mx:ColumnSeries>

        <mx:ColumnSeries id="columnSeries2"
                         displayName="Total Opened"
                         yField="OpenCount"
                         xField="Month"
        ></mx:ColumnSeries>

        <mx:LineSeries id="columnSeries3" displayName="Closed/OpenRatio" yField="ClosedToOpenRatio" xField="Month"
                       >
            <mx:verticalAxis>
                <mx:LinearAxis id="v2" minimum="0" maximum="3" />
            </mx:verticalAxis>
        </mx:LineSeries>

            <!--mx:LineSeries id="columnSeries4" displayName="Target" xField="Month" yField="1.5" verticalAxis="{v2}" horizontalAxis="{categoryAxis}"  /-->

    </mx:series>

</mx:ColumnChart>
<mx:Legend dataProvider="{cvpaOpenCloseRatio}"/>
</code>```

I was trying to achieve this with

```<code><mx:LineSeries id="columnSeries4" displayName="Target" xField="Month" yField="1.5" verticalAxis="{v2}" horizontalAxis="{categoryAxis}"  />
</code>```

so to clarify the break even line is a horisontal line located at 1.5 with respect to the right side verticalAxis.

Thanks in advance
Nate

答: You were almost there, you just need to specify a custom item renderer for the line in the LineSeries.  Example here.</p>

Body:
Here is my question:
I have a hybrid chart that uses bars and lines
I want to add to the right vertical axis a horizontal line that represents a break even

<mx:ColumnChart id="cvpaOpenCloseRatio" x="79" y="107"
                dataProvider="{CF_Closed_to_Opened_by_MonthResult.lastResult}"
                showDataTips="true">
    <mx:horizontalAxis>
        <mx:CategoryAxis id="categoryAxis" categoryField="Month"/>
    </mx:horizontalAxis>
    <mx:verticalAxisRenderers>
        <mx:AxisRenderer placement="left" axis="{v1}"/>
        <mx:AxisRenderer placement="right" axis="{v2}"/>
    </mx:verticalAxisRenderers>

    <mx:series>
        <mx:ColumnSeries id="columnSeries"
                         displayName="Total Closed"
                         yField="ClosedCount"
                         xField="Month"
                         >
            <mx:verticalAxis>
                <mx:LinearAxis id="v1" minimum="0" maximum="300"/>
            </mx:verticalAxis>
        </mx:ColumnSeries>

        <mx:ColumnSeries id="columnSeries2"
                         displayName="Total Opened"
                         yField="OpenCount"
                         xField="Month"
        ></mx:ColumnSeries>

        <mx:LineSeries id="columnSeries3" displayName="Closed/OpenRatio" yField="ClosedToOpenRatio" xField="Month"
                       >
            <mx:verticalAxis>
                <mx:LinearAxis id="v2" minimum="0" maximum="3" />
            </mx:verticalAxis>
        </mx:LineSeries>

    </mx:series>

</mx:ColumnChart>
<mx:Legend dataProvider="{cvpaOpenCloseRatio}"/>

I was trying to achieve this with

<mx:LineSeries id="columnSeries4" displayName="Target" xField="Month" yField="1.5" verticalAxis="{v2}" horizontalAxis="{categoryAxis}"  />

so to clarify the break even line is a horisontal line located at 1.5 with respect to the right side verticalAxis.

Thanks in advance
Nate