问:
Errors during downloading metadata for repository 'remi' & Errors during downloading metadata for repository 'remi-modular':
I am trying to configure a server with nginx and php but it turns out that when downloading or updating the metadata of the remi and remi-modular repository or simply when doing a dnf upgrade I get the error. Errors during downloading metadata for repository 'remi': y Errors during downloading metadata for repository 'remi-modular': and to top it off when installing MariaDB it throws me an error that says it needs gallery-4 so it doesn't let it update or nothing and throws the message.

```<code>Dropping packages with dependency conflicts: MariaDB-server x86_64 10.4.17-1.fc31 mariadb 17 M
  galley-4 x86_64 26.4.3-1.fc31.fc31 mariadb 13M
  galley-4 x86_64 26.4.4-1.fc31.fc31 mariadb 14M
  galley-4 x86_64 26.4.5-1.fc31 mariadb 14 M
  galley-4 x86_64 26.4.6-1.fc31 mariadb 14 M
</code>```

please help.

enter image description here

I have already tried the commands to delete the history and everything but still nothing

sudo dnf clean all
sudo rm -r /var/cache/dnf
```

Body:
I am trying to configure a server with nginx and php but it turns out that when downloading or updating the metadata of the remi and remi-modular repository or simply when doing a dnf upgrade I get the error. Errors during downloading metadata for repository 'remi': y Errors during downloading metadata for repository 'remi-modular': and to top it off when installing MariaDB it throws me an error that says it needs gallery-4 so it doesn't let it update or nothing and throws the message.

Dropping packages with dependency conflicts: MariaDB-server x86_64 10.4.17-1.fc31 mariadb 17 M
  galley-4 x86_64 26.4.3-1.fc31.fc31 mariadb 13M
  galley-4 x86_64 26.4.4-1.fc31.fc31 mariadb 14M
  galley-4 x86_64 26.4.5-1.fc31 mariadb 14 M
  galley-4 x86_64 26.4.6-1.fc31 mariadb 14 M

please help.

enter image description here

I have already tried the commands to delete the history and everything but still nothing

sudo dnf clean all
sudo rm -r /var/cache/dnf


来源: stackexchange

问:
Can we wrap an interceptor around a JAX-RS ExceptionMapper?
In my application, I have exception mappers for handling different exceptions. I need to somehow enforce the developers to pass the exception message from the toResponse(Exception e) method into a @RequestScoped Bean attribute for further use in the response filter chain.

Perhaps the interceptor may do the trick. However, the interceptor simply isn't getting invoked. Can someone help me understand why this is happening? Making the mapper a stateless session bean did not help either.

```<code>@Provider
@Interceptors(XYZInterceptor.class)
//@Stateless
public class ABCExceptionMapper implements ExceptionMapper<ABCException> {
   public Response toResponse(ABCException exception) {
      // When building response I want to force the developers to set the exception message to an attribute in a @RequestScoped Bean
   }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my application, I have exception mappers for handling different exceptions. I need to somehow enforce the developers to pass the exception message from the toResponse(Exception e) method into a @RequestScoped Bean attribute for further use in the response filter chain.

Perhaps the interceptor may do the trick. However, the interceptor simply isn't getting invoked. Can someone help me understand why this is happening? Making the mapper a stateless session bean did not help either.

@Provider
@Interceptors(XYZInterceptor.class)
//@Stateless
public class ABCExceptionMapper implements ExceptionMapper<ABCException> {
   public Response toResponse(ABCException exception) {
      // When building response I want to force the developers to set the exception message to an attribute in a @RequestScoped Bean
   }
}


问:
call a containerized rest api from another container
I am developing a solution where exists two application running on same host, lets say AppA and AppB. Both are containerized application .

AppA : its is flask based python rest api application with endpoint /hello , exposed on port 3000

AppB : Its is python application that invokes endpoint /hello from AppA.
Please note that for some reason, the App-B is constrained to run with  --network="host". else I would have created both app in same container network.

I am able to invoke the endpoint using curl operation from the host.

```<code>curl http://localhost:3000/hello
</code>```

I tried to call the endpoint from AppB using below endpoint

```<code>try:
   REST_ENDPOINT="http://AppA:3000/hello"
   response = requests.get(REST_ENDPOINT)
except HTTPError as http_err:
   logging.error("HTTP error occurred:{}".format(http_err))
except Exception as err:
   logging.error("Other error occurred: {}".format(err))
</code>```

and I am getting below error.

Other error occurred: HTTPConnectionPool(host='hsec-ml-blacklist-service', port=3000): Max retries exceeded with url: /hello (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7febc5fa8f40>: Failed to establish a new connection: [Errno -2] Name or service not known'))

I found some solutions but they suggest to run the application in same docker network and use the container name as domain for the rest api. But as my AppB is constrained to run on host, I cannot do it.
So kindly help me with some suggestions ?

Body:
I am developing a solution where exists two application running on same host, lets say AppA and AppB. Both are containerized application .

AppA : its is flask based python rest api application with endpoint /hello , exposed on port 3000

AppB : Its is python application that invokes endpoint /hello from AppA.
Please note that for some reason, the App-B is constrained to run with  --network="host". else I would have created both app in same container network.

I am able to invoke the endpoint using curl operation from the host.

curl http://localhost:3000/hello

I tried to call the endpoint from AppB using below endpoint

try:
   REST_ENDPOINT="http://AppA:3000/hello"
   response = requests.get(REST_ENDPOINT)
except HTTPError as http_err:
   logging.error("HTTP error occurred:{}".format(http_err))
except Exception as err:
   logging.error("Other error occurred: {}".format(err))

and I am getting below error.

Other error occurred: HTTPConnectionPool(host='hsec-ml-blacklist-service', port=3000): Max retries exceeded with url: /hello (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7febc5fa8f40>: Failed to establish a new connection: [Errno -2] Name or service not known'))

I found some solutions but they suggest to run the application in same docker network and use the container name as domain for the rest api. But as my AppB is constrained to run on host, I cannot do it.
So kindly help me with some suggestions ?


问:
react native navigation does not navigate to desired screen on button press
I have a main navigator and two navigators nested in it: Auth Navigator and a Root navigator that renders a different screen depending on whether a user exists or not. But It returns this error when I try to navigate to either of the screens:

```<code>The action 'NAVIGATE' with payload {"name":"UserType1"} was not handled by any navigator
</code>```

This is my main Navigator:

```<code>function _Navigation({
  colorScheme,
  tokenRedux,
}: {
  colorScheme: ColorSchemeName;
  tokenRedux: any;
}) {
  const [userExists, setUserExists] = React.useState<boolean>(false);
  const [user, setUser] = React.useState<any>();

  const getUser = async () => {
    const user = await getDataInStorage("USER_AUTH");

    if (user?.data?.username) {
      setUserExists(true);
    } else {
      setUserExists(false);
    }
    setUser(user);
    return user;
  };

  React.useEffect(() => {
    getUser();
  }, [tokenRedux]);
  return (
    <NavigationContainer
      linking={LinkingConfiguration}
      theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
    >
      {userExists ? <RootNavigator user={user} /> : <AuthNavigator />}
    </NavigationContainer>
  );
}
</code>```

This is my Root Navigator(Where the problem lies):

```<code>function RootNavigator(user: any) {
  const currentUser = user?.user?.data;
  return (
    <Stack.Navigator>
      {currentUser && currentUser?.userType === "influencer" ? (
        <Stack.Screen
          name="UserType1"
          component={UserType1BottomTabNavigator}
          options={{ headerShown: false }}
        />
      ) : (
        <Stack.Screen
          name="UserType2"
          component={UserType2BottomTabNavigator}
          options={{ headerShown: false }}
        />
      )}

      <Stack.Screen
        name="Profile"
        component={ProfileOverview}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="BioData"
        component={BioData}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="NotFound"
        component={NotFoundScreen}
        options={{ title: "Oops!" }}
      />
      {/* <Stack.Group screenOptions={{ presentation: "modal" }}>
        <Stack.Screen name="Modal" component={ModalScreen} />
      </Stack.Group> */}
    </Stack.Navigator>
  );
}
</code>```

When I try to navigate to either the userType1 or userType2 screen, it returns an error:

```<code>The action 'NAVIGATE' with payload {"name":"UserType1"} was not handled by any navigator
</code>```

Body:
I have a main navigator and two navigators nested in it: Auth Navigator and a Root navigator that renders a different screen depending on whether a user exists or not. But It returns this error when I try to navigate to either of the screens:

The action 'NAVIGATE' with payload {"name":"UserType1"} was not handled by any navigator

This is my main Navigator:

function _Navigation({
  colorScheme,
  tokenRedux,
}: {
  colorScheme: ColorSchemeName;
  tokenRedux: any;
}) {
  const [userExists, setUserExists] = React.useState<boolean>(false);
  const [user, setUser] = React.useState<any>();

  const getUser = async () => {
    const user = await getDataInStorage("USER_AUTH");

    if (user?.data?.username) {
      setUserExists(true);
    } else {
      setUserExists(false);
    }
    setUser(user);
    return user;
  };

  React.useEffect(() => {
    getUser();
  }, [tokenRedux]);
  return (
    <NavigationContainer
      linking={LinkingConfiguration}
      theme={colorScheme === "dark" ? DarkTheme : DefaultTheme}
    >
      {userExists ? <RootNavigator user={user} /> : <AuthNavigator />}
    </NavigationContainer>
  );
}

This is my Root Navigator(Where the problem lies):

function RootNavigator(user: any) {
  const currentUser = user?.user?.data;
  return (
    <Stack.Navigator>
      {currentUser && currentUser?.userType === "influencer" ? (
        <Stack.Screen
          name="UserType1"
          component={UserType1BottomTabNavigator}
          options={{ headerShown: false }}
        />
      ) : (
        <Stack.Screen
          name="UserType2"
          component={UserType2BottomTabNavigator}
          options={{ headerShown: false }}
        />
      )}

      <Stack.Screen
        name="Profile"
        component={ProfileOverview}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="BioData"
        component={BioData}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="NotFound"
        component={NotFoundScreen}
        options={{ title: "Oops!" }}
      />
      {/* <Stack.Group screenOptions={{ presentation: "modal" }}>
        <Stack.Screen name="Modal" component={ModalScreen} />
      </Stack.Group> */}
    </Stack.Navigator>
  );
}

When I try to navigate to either the userType1 or userType2 screen, it returns an error:

The action 'NAVIGATE' with payload {"name":"UserType1"} was not handled by any navigator


问:
Xamarin Forms Error: Default constructor not found for type Xamarin.Forms.ImageSource
I have been building on a Xamarin.Forms app and have just now noticed a strange issue in the App.xaml file where I am declaring the global resources in the ResourceDirectory. Even just after removing extra lines of space in the App.xaml file it gives this error after doing a rebuild:

Default constructor not found for type Xamarin.Forms.ImageSource

on the first line GreekNavBarImage:

<ImageSource x:Key="GreekNavBarImage">greek_temp.png</ImageSource>

<ImageSource x:Key="LatinNavBarImage">latin_temp.png</ImageSource>

<ImageSource x:Key="CurrentNavBarImage">greek_temp.png</ImageSource>
```

I think the namespace it is using xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" is okay even though when you click on it it says it is out of date. It is still in all of the official Microsoft Xamarin docs.

I cannot find much else about this error and keep having to delete and redownload the project from
git in order to fix this anytime I even touch this file. It is becoming tedious and getting I am needing to edit this App.xaml file locally.

I have tried reading the ImageSource docs but it still seems like it should have a default constructor that works as it is not any custom class but just the default Xamarin.Forms.ImageSource.

Body:
I have been building on a Xamarin.Forms app and have just now noticed a strange issue in the App.xaml file where I am declaring the global resources in the ResourceDirectory. Even just after removing extra lines of space in the App.xaml file it gives this error after doing a rebuild:

Default constructor not found for type Xamarin.Forms.ImageSource

on the first line GreekNavBarImage:

<ImageSource x:Key="GreekNavBarImage">greek_temp.png</ImageSource>

<ImageSource x:Key="LatinNavBarImage">latin_temp.png</ImageSource>

<ImageSource x:Key="CurrentNavBarImage">greek_temp.png</ImageSource>

I think the namespace it is using xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" is okay even though when you click on it it says it is out of date. It is still in all of the official Microsoft Xamarin docs.

I cannot find much else about this error and keep having to delete and redownload the project from
git in order to fix this anytime I even touch this file. It is becoming tedious and getting I am needing to edit this App.xaml file locally.

I have tried reading the ImageSource docs but it still seems like it should have a default constructor that works as it is not any custom class but just the default Xamarin.Forms.ImageSource.


问:
Find earliest Azure DevOps pipeline release containing a work item
In Azure DevOps, is there a way to show the earliest release(s) only in which a work item is integrated, along with their full release names?

In a work item's Links tab there is the "Integrated in release stage" section which shows e.g. the following:

The work item shown involved changes to two projects, resulting in builds and releases in two different pipelines. The first problem with this display is that it's not possible to discern which release pipelines contain the changes, without following the links.

Secondly, it can be seen in the highlighted entries that there has been a subsequent release on one of the pipelines, and so the list also contains Release-250 of that pipeline - I don't want to see this, I need to be able to see just the earliest release containing the work item (Release 249).

Is there a way to easily discover the earliest releases that must be deployed in order to deploy changes for this work item?

All other questions seem to revolve around how to find which work items are contained in a release. I want to know how to do the opposite: given a work item to deploy, which releases would need to go out?


问:
Redhat 8 readonly partition issue
Good morning.
I have a platform with redhat 8.
I'm trying to create a readonly root partition, supporting graphical login.

I followed the steps proposed in

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/managing_file_systems/setting-read-only-permissions-for-the-root-file-system_managing-file-systems

However when logging in graphical mode, I get an error, and the GUI login page restart. Obviously the login and password are the right one.
Checking, through the console login page, the logs using the command

cat /var/log/messages

I found an error related to:
IceLockAuthFile failed: Read-Only file system

therefore I tried modifying the /etc/rwtab file to allow write access to this file.
My approach was adding the user home folder as

dirs /home/user/

in the list of folder.
However this works fine, but each time the user login, it acts as a new user, selecting the user keyboard and so on.

Is there anyone that can provide me a clean approach to the problem?

Please note that in fact, next step of my project is to start a custom application in kiosk mode (so automatic login and startup of a custom application).
Any help will be appreciated.

Best regards
Giovanni

Title: Redhat 8 readonly partition issue


问:
Sending email feature not working when run using Docker. Showing Error : 530, b'5.7.0 Authentication Required. But runs perfectly without docker
I am making a Django App using GraphQl APIs in which I am trying to make an email sending feature for changing and sending user password if they forget while login.

This feature is perfectly working when I am running it from my laptop's localhost:8000, but when I pushed it to dockerhub using github actions, and pulled it and tried to run, it didn't work. The error is: "(530, b'5.7.0 Authentication Required. Learn more at\n5.7.0  https://support.google.com/mail/?p=WantAuthError w13-20020aa7954d000000b00574c54423d3sm14276612pfq.145 - gsmtp', 'webmaster@localhost')"
Now it is saying "webmaster@localhost", this cannot happen as I am using smpt.gmail.com, also I have made the feature for creating environment variables in .github/workflows/main.yml file. This means somehow my docker-image is not able to access the .envvariables.

All my secret credentials are correct as they work when I use it from my laptop's localhost server, but not in docker localhost server. Can anybody shed some light on this?

Below is my main.yml files

I firstly tried this

```<code>name: Publish Docker Image to Docker Hub

on:
  push:
    branches: ['master']
  pull_request:
    branches: ['master']

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: 'Create env file'
        run: |
          echo "${{ secrets.ENV_FILE }}" > .env
      - uses: actions/checkout@v3
      - name: Log in to Docker Hub
        uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
      - name: Build the Docker image
        run: docker build . --file Dockerfile --tag ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image
      - name: Check running containers
        run: docker ps -a
      - name: Docker Push
        run: docker push ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image

</code>```

Then this:

```<code>name: Publish Docker Image to Docker Hub

on:
  push:
    branches: ['master']
  pull_request:
    branches: ['master']

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: 'Create env file'
        run: |
          touch .env
          echo "EMAIL_HOST_USERNAME = ${{ secrets.EMAIL_HOST_USERNAME }}" >> .env
          echo "EMAIL_HOST_PASSWORD = ${{ secrets.EMAIL_HOST_PASSWORD }}" >> .env
          cat .env

      - uses: actions/checkout@v3
      - name: Log in to Docker Hub
        uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
      - name: Build the Docker image
        run: docker build . --file Dockerfile --tag ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image
      - name: Check running containers
        run: docker ps -a
      - name: Docker Push
        run: docker push ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image

</code>```

Then this as well

```<code>name: Publish Docker Image to Docker Hub

on:
  push:
    branches: ['master']
  pull_request:
    branches: ['master']

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Log in to Docker Hub
        uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
      - name: Push to Docker Hub
        uses: docker/build-push-action@v2
        with:
          push: true
          tags: ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image:latest
          secrets: |
            "EMAIL_HOST_USERNAME=${{ secrets.EMAIL_HOST_USERNAME }}"
            "EMAIL_HOST_PASSWORD=${{ secrets.EMAIL_HOST_PASSWORD }}"

</code>```

Nothing works. I want an email to be sent from secrets.EMAIL_HOST_USERNAME to the user's email. All my secret credentials are correct as they work when I use it from my laptop's localhost server, but not in docker localhost server.

This is my Email Settings in Settings file:

```<code>EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USERNAME")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
</code>```

This is my send_email function call in mutation file

```<code>send_mail(
            subject="Your New Password",
            message=f"New Password {new_password}",
            from_email=EMAIL_HOST_USER,
            recipient_list=[email,],
            fail_silently=False
        )
</code>```

Can anybody shed some light on this?

Body:
I am making a Django App using GraphQl APIs in which I am trying to make an email sending feature for changing and sending user password if they forget while login.

This feature is perfectly working when I am running it from my laptop's localhost:8000, but when I pushed it to dockerhub using github actions, and pulled it and tried to run, it didn't work. The error is: "(530, b'5.7.0 Authentication Required. Learn more at\n5.7.0  https://support.google.com/mail/?p=WantAuthError w13-20020aa7954d000000b00574c54423d3sm14276612pfq.145 - gsmtp', 'webmaster@localhost')"
Now it is saying "webmaster@localhost", this cannot happen as I am using smpt.gmail.com, also I have made the feature for creating environment variables in .github/workflows/main.yml file. This means somehow my docker-image is not able to access the .envvariables.

All my secret credentials are correct as they work when I use it from my laptop's localhost server, but not in docker localhost server. Can anybody shed some light on this?

Below is my main.yml files

I firstly tried this

name: Publish Docker Image to Docker Hub

on:
  push:
    branches: ['master']
  pull_request:
    branches: ['master']

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: 'Create env file'
        run: |
          echo "${{ secrets.ENV_FILE }}" > .env
      - uses: actions/checkout@v3
      - name: Log in to Docker Hub
        uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
      - name: Build the Docker image
        run: docker build . --file Dockerfile --tag ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image
      - name: Check running containers
        run: docker ps -a
      - name: Docker Push
        run: docker push ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image

Then this:

name: Publish Docker Image to Docker Hub

on:
  push:
    branches: ['master']
  pull_request:
    branches: ['master']

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: 'Create env file'
        run: |
          touch .env
          echo "EMAIL_HOST_USERNAME = ${{ secrets.EMAIL_HOST_USERNAME }}" >> .env
          echo "EMAIL_HOST_PASSWORD = ${{ secrets.EMAIL_HOST_PASSWORD }}" >> .env
          cat .env

      - uses: actions/checkout@v3
      - name: Log in to Docker Hub
        uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
      - name: Build the Docker image
        run: docker build . --file Dockerfile --tag ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image
      - name: Check running containers
        run: docker ps -a
      - name: Docker Push
        run: docker push ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image

Then this as well

name: Publish Docker Image to Docker Hub

on:
  push:
    branches: ['master']
  pull_request:
    branches: ['master']

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Log in to Docker Hub
        uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
      - name: Push to Docker Hub
        uses: docker/build-push-action@v2
        with:
          push: true
          tags: ${{ secrets.DOCKER_USERNAME }}/photo-lib-docker-image:latest
          secrets: |
            "EMAIL_HOST_USERNAME=${{ secrets.EMAIL_HOST_USERNAME }}"
            "EMAIL_HOST_PASSWORD=${{ secrets.EMAIL_HOST_PASSWORD }}"

Nothing works. I want an email to be sent from secrets.EMAIL_HOST_USERNAME to the user's email. All my secret credentials are correct as they work when I use it from my laptop's localhost server, but not in docker localhost server.

This is my Email Settings in Settings file:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USERNAME")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")

This is my send_email function call in mutation file

send_mail(
            subject="Your New Password",
            message=f"New Password {new_password}",
            from_email=EMAIL_HOST_USER,
            recipient_list=[email,],
            fail_silently=False
        )

Can anybody shed some light on this?


问:
Does lazy_static run more than once when used in a parallel iterator?
I have a utility function that does some regex stuff and am using a lazy_static within it as per the documentation of Regex. However, this function is only called in a par_iter loop like so:

```<code>fn some_regex_thing(&str) -> String {
   lazy_static! {
        static ref RE: Regex = ...
   }
   RE.replace_all(...)
}

fn main() {
// SNIP

   let output = my_par_vec.par_iter().map(|f| {
                some_regex_thing(f)
               }).collect();
}

</code>```

Does the benefit of lazy_static still apply here? Or because this is spawned to different threads, each thread still compiles this, negating the benefit of lazy_static?

Body:
I have a utility function that does some regex stuff and am using a lazy_static within it as per the documentation of Regex. However, this function is only called in a par_iter loop like so:

fn some_regex_thing(&str) -> String {
   lazy_static! {
        static ref RE: Regex = ...
   }
   RE.replace_all(...)
}

fn main() {
// SNIP

   let output = my_par_vec.par_iter().map(|f| {
                some_regex_thing(f)
               }).collect();
}

Does the benefit of lazy_static still apply here? Or because this is spawned to different threads, each thread still compiles this, negating the benefit of lazy_static?


问:
Displaying a list or Map in Visualforce page
I have a controller which has a method which populates a list and map.

```<code>Public class A
 { public Map<string,Book__c> map1 {get;set;}
   public List<String> Lst {get;set;}
 public A()
 {
  ..... do something...
 }
 public refresh()
 {
  Lst= new List<String>();
  map1=new Map<string,Book__c>;
  // Populating the map and List in this method
  }
 }
</code>```

In my VF page
i am calling the refresh method on change of a inputfield, the method get called and the maps and Lists get populated. But they are not showing in the VF page

VF Code

```<code><apex:pageblocksection id="tableApp" >

<table id="apppp">
<tr>
<th>Name</th>
</tr>
 <apex:repeat var="d" value="{!Lst}">
<tr>
    <td><apex:outputText value="{!d}"/></td>

</tr>

 </apex:repeat>
 </table>
 </apex:pageblocksection>
</code>```

Is there anything wrong in this code? I am rerendering the pageblocksection tableApp on change of the inputfield

ContentLicense: CC BY-SA 3.0

Body:
I have a controller which has a method which populates a list and map.

Public class A
 { public Map<string,Book__c> map1 {get;set;}
   public List<String> Lst {get;set;}
 public A()
 {
  ..... do something...
 }
 public refresh()
 {
  Lst= new List<String>();
  map1=new Map<string,Book__c>;
  // Populating the map and List in this method
  }
 }

In my VF page
i am calling the refresh method on change of a inputfield, the method get called and the maps and Lists get populated. But they are not showing in the VF page

VF Code

<apex:pageblocksection id="tableApp" >

Name

 <apex:repeat var="d" value="{!Lst}">

    <apex:outputText value="{!d}"/>

 </apex:repeat>

 </apex:pageblocksection>

Is there anything wrong in this code? I am rerendering the pageblocksection tableApp on change of the inputfield


问:
How to invoke OAuth2 protected web service using WebClient through a non web API
I want to invoke a REST OAuth protected web service from an existing application (A).
I want to make all invocations possible into an API that I will include as maven dependency into my application (A).
I want to do that without spring boot because there is no need.
So, I want make all HTTP request into my API.
I see I can use WebClient. But WebClient need dependency injection and I do not know how to proceed into an API as all properties come from application A which have no application.properties file?

How can I specify properties ?

```<code>spring:
  security:
    oauth2:
      client:
        registration:
          mywebclient:
           client-id: myclient
</code>```

How can I inject below variables ?

```<code>ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository
</code>```

Thanks

Body:
I want to invoke a REST OAuth protected web service from an existing application (A).
I want to make all invocations possible into an API that I will include as maven dependency into my application (A).
I want to do that without spring boot because there is no need.
So, I want make all HTTP request into my API.
I see I can use WebClient. But WebClient need dependency injection and I do not know how to proceed into an API as all properties come from application A which have no application.properties file?

How can I specify properties ?

spring:
  security:
    oauth2:
      client:
        registration:
          mywebclient:
           client-id: myclient

How can I inject below variables ?

ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository

Thanks


问:
Communiacting with USB device on linux
I need to communicate with a USB device. The communication is wrapped in both Windows and Linux by file I/O, and the tricky part seems to be deducing the device path name.

On Windows I use Setup API (SetupDiEnumDeviceInfo and friends), discover the path to my device, and the communication seems to work as expected.

On Linux I use udev API (udev_enumerate_add_match_subsystem and friends), and it seems to find my device. At least I correctly deduce its parameters (idVendor, idProduct, and etc.).

However I can't communicate with it. The path I deduce is of the form like /dev/bus/usb/001/078, and I can open it (via open function).

But it doesn't behave like the target device. The USB device is expected to communicate in terms of so-called USB reports (i.e. kind of messages).
In practice I see that when I open it I can read 82 bytes of data (which is not expected), and I can't send anything (although I've opened the file with O_RDWR flag).
After some investigation I discovered that those 82 bytes is in fact the USB_DEVICE_DESCRIPTOR structure.

So, it looks that the file I've opened is actually a file which contains the device parameters, and has nothing to do about communicating with the device itself.

What is the correct way of deducing the path to the device?

Title: Communiacting with USB device on linux


问:
Android TextInputLayouts passwordToggleEnabled causing TextInputEditText to expand indefinitely
I am trying to set vertical margins manually in a custom TextInputEditText class. I have used this class all over my app but for some reason if I set passwordToggleEnabled to true, it causes the text box to expand vertically forever, filling up parent view and pushing other views out. This isn't an instant thing, you can visibly see the view at the right height when you first enter the screen, and then the height slowly grows over time.

```<code>public final class CustomEditText extends TextInputEditText {

    public CustomEditText(Context context) {
        super(context);
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(
                attrs, R.styleable.CustomEditText, 0, 0);
        typedArray.recycle();

        init();
    }

    private void init() {
        setPadding((int) getPx(5), (int) getPx(5), 0, (int) getPx(5));
        setTranslationY(getPx(2));
    }

    @Override
    public void setLayoutParams(ViewGroup.LayoutParams params) {
        ViewGroup.MarginLayoutParams marginLayoutParams =
                (ViewGroup.MarginLayoutParams) params;
        marginLayoutParams.setMargins(0, (int) getPx(2), 0, (int) getPx(2));
        super.setLayoutParams(params);
    }
</code>```

And the XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="8dp"
    android:orientation="vertical">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/current_password_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        app:passwordToggleEnabled="true">

        <com.test.views.custom.CustomEditText
            android:id="@+id/current_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/current_password"
            android:imeOptions="actionNext"
            android:inputType="textPassword"
            android:maxLines="1"/>

    </com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
</code>```

I have tried setting the margin in the onLayout, onDraw, onAttachedToWindow, nothing seems to work. It is very odd that the parent view (TextInputLayout) would be causing the issue as well.
A solution I found was to hardcode the layout_height to a specific value, but that doesn't work in my case due to other issues. Has anyone seen this before and know what is going on?

Body:
I am trying to set vertical margins manually in a custom TextInputEditText class. I have used this class all over my app but for some reason if I set passwordToggleEnabled to true, it causes the text box to expand vertically forever, filling up parent view and pushing other views out. This isn't an instant thing, you can visibly see the view at the right height when you first enter the screen, and then the height slowly grows over time.

public final class CustomEditText extends TextInputEditText {

    public CustomEditText(Context context) {
        super(context);
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(
                attrs, R.styleable.CustomEditText, 0, 0);
        typedArray.recycle();

        init();
    }

    private void init() {
        setPadding((int) getPx(5), (int) getPx(5), 0, (int) getPx(5));
        setTranslationY(getPx(2));
    }

    @Override
    public void setLayoutParams(ViewGroup.LayoutParams params) {
        ViewGroup.MarginLayoutParams marginLayoutParams =
                (ViewGroup.MarginLayoutParams) params;
        marginLayoutParams.setMargins(0, (int) getPx(2), 0, (int) getPx(2));
        super.setLayoutParams(params);
    }

And the XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="8dp"
    android:orientation="vertical">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/current_password_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        app:passwordToggleEnabled="true">

        <com.test.views.custom.CustomEditText
            android:id="@+id/current_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/current_password"
            android:imeOptions="actionNext"
            android:inputType="textPassword"
            android:maxLines="1"/>

    </com.google.android.material.textfield.TextInputLayout>
</LinearLayout>

I have tried setting the margin in the onLayout, onDraw, onAttachedToWindow, nothing seems to work. It is very odd that the parent view (TextInputLayout) would be causing the issue as well.
A solution I found was to hardcode the layout_height to a specific value, but that doesn't work in my case due to other issues. Has anyone seen this before and know what is going on?


问:
CSV file writing / pandas exporting to csv: Why is this appending?
I have several txt files. I am reading them in and I want to store them in a single file. My code so far that works is:

```<code>import pandas as pd
import glob
import csv
import os

col_lengths = {'Column1': range(0, 2),
                   'Column2': range(3, 11),
              }
col_lengths = {k: set(v) for k, v in col_lengths.items()}

path = r"C:\myfolder"
all_files = glob.glob(os.path.join(path, "*.txt"))

with open(os.path.join(path, "output_file.csv"), "wb") as f:
    for i, filename in enumerate(all_files):
        print(filename)
        df = pd.read_fwf(
            filename,
            colspecs=[(min(x), max(x)+1) for x in col_lengths.values()],
            header=None,
            names=col_lengths,
            converters={'Column1':lambda x : str(x),
                          'Column2':lambda x : str(x),
                       }
        )
        df.to_csv(
        f,
        header=(i == 0),
        sep=";",
        decimal=",",
        mode="wb",
        quoting=csv.QUOTE_MINIMAL)
</code>```

The code works so far. When I thought about it I wasn't sure about the df.to_csv statement. I have a with open before, but why is it actually appending the data? It is not something like mode='a'. So does it append the data because the file is still open due to the with open before? If I wouldn't have it, but still the loop over the filenames, then it would just rewrite the csv each time? So in final just store one dataframe with the data of the last file?

And what about the differences to the approach of not having a with open and a wb mode, but instead have the appending mode in the df.to_csv statement? Especially with regards to very large files and limited RAM. Is it correct, that append basically each time opens the file and in case the file is already really large, as some files where processed this could throw a memory error, as the append mode needs to open the file again? While as with with open and just writing to it this would not occur? But why exactly would it not occur, because the file itself is stored on the disk and not so much RAM is needed, as the data is not read into the RAM? I have troubles understanding or imaging this, because with open I also have at some point a really large csv file? But probably not inside the RAM?

Body:
I have several txt files. I am reading them in and I want to store them in a single file. My code so far that works is:

import pandas as pd
import glob
import csv
import os

col_lengths = {'Column1': range(0, 2),
                   'Column2': range(3, 11),
              }
col_lengths = {k: set(v) for k, v in col_lengths.items()}

path = r"C:\myfolder"
all_files = glob.glob(os.path.join(path, "*.txt"))

with open(os.path.join(path, "output_file.csv"), "wb") as f:
    for i, filename in enumerate(all_files):
        print(filename)
        df = pd.read_fwf(
            filename,
            colspecs=[(min(x), max(x)+1) for x in col_lengths.values()],
            header=None,
            names=col_lengths,
            converters={'Column1':lambda x : str(x),
                          'Column2':lambda x : str(x),
                       }
        )
        df.to_csv(
        f,
        header=(i == 0),
        sep=";",
        decimal=",",
        mode="wb",
        quoting=csv.QUOTE_MINIMAL)

The code works so far. When I thought about it I wasn't sure about the df.to_csv statement. I have a with open before, but why is it actually appending the data? It is not something like mode='a'. So does it append the data because the file is still open due to the with open before? If I wouldn't have it, but still the loop over the filenames, then it would just rewrite the csv each time? So in final just store one dataframe with the data of the last file?

And what about the differences to the approach of not having a with open and a wb mode, but instead have the appending mode in the df.to_csv statement? Especially with regards to very large files and limited RAM. Is it correct, that append basically each time opens the file and in case the file is already really large, as some files where processed this could throw a memory error, as the append mode needs to open the file again? While as with with open and just writing to it this would not occur? But why exactly would it not occur, because the file itself is stored on the disk and not so much RAM is needed, as the data is not read into the RAM? I have troubles understanding or imaging this, because with open I also have at some point a really large csv file? But probably not inside the RAM?


问:
Cummulative Percentage of Total by Multiple Categories
I am looking to calculate the cummulative percentage of refunds for each # of days from sale by the month in which the sale occured:

Where refund days from sale should cummulate from 0 to Max.

My attempt:

```<code>    =
VAR Refunds =
    CALCULATE (
        SUM ( 'My Table'[Amount USD] ),
        FILTER (
            ALLSELECTED ( 'My Table'[Refund Days from Sale] ),
            ISONORAFTER ( 'My Table'[Refund Days from Sale], MAX ( 'My Table'[Refund Days from Sale] ), DESC )
        )
    )
VAR TotalRefunds =
    CALCULATE ( SUM ( 'My Table'[Amount USD] ), ALLSELECTED ( 'My Table' ) )
RETURN
    DIVIDE ( Refunds, TotalRefunds )
</code>```

My Data:

```<code>| Month of Sale | Refund Days from Sale | USD Amount |
|---------------|-----------------------|------------|
| 01-2022       | 0                     | 100        |
| 02-2022       | 4                     | 50         |
| 01-2022       | 2                     | 20         |
| 01-2022       | 3                     | 10         |
| 01-2022       | 4                     | 40         |
| 01-2022       | 5                     | 60         |
| 01-2022       | 6                     | 10         |
| 02-2022       | 7                     | 5          |
| 01-2022       | 8                     | 15         |
| 02-2022       | 9                     | 30         |
| 02-2022       | 8                     | 60         |
| 01-2022       | 12                    | 10         |
| 02-2022       | 4                     | 5          |
| 02-2022       | 7                     | 15         |
| 01-2022       | 3                     | 30         |
| 02-2022       | 1                     | 30         |
</code>```

Table has thousands of rows - want this to be measure not a calculated column if possible.

Body:
I am looking to calculate the cummulative percentage of refunds for each # of days from sale by the month in which the sale occured:

Where refund days from sale should cummulate from 0 to Max.

My attempt:

    =
VAR Refunds =
    CALCULATE (
        SUM ( 'My Table'[Amount USD] ),
        FILTER (
            ALLSELECTED ( 'My Table'[Refund Days from Sale] ),
            ISONORAFTER ( 'My Table'[Refund Days from Sale], MAX ( 'My Table'[Refund Days from Sale] ), DESC )
        )
    )
VAR TotalRefunds =
    CALCULATE ( SUM ( 'My Table'[Amount USD] ), ALLSELECTED ( 'My Table' ) )
RETURN
    DIVIDE ( Refunds, TotalRefunds )

My Data:

| Month of Sale | Refund Days from Sale | USD Amount |
|---------------|-----------------------|------------|
| 01-2022       | 0                     | 100        |
| 02-2022       | 4                     | 50         |
| 01-2022       | 2                     | 20         |
| 01-2022       | 3                     | 10         |
| 01-2022       | 4                     | 40         |
| 01-2022       | 5                     | 60         |
| 01-2022       | 6                     | 10         |
| 02-2022       | 7                     | 5          |
| 01-2022       | 8                     | 15         |
| 02-2022       | 9                     | 30         |
| 02-2022       | 8                     | 60         |
| 01-2022       | 12                    | 10         |
| 02-2022       | 4                     | 5          |
| 02-2022       | 7                     | 15         |
| 01-2022       | 3                     | 30         |
| 02-2022       | 1                     | 30         |

Table has thousands of rows - want this to be measure not a calculated column if possible.


问:
iOS - today extension strange error / warning
In my iOS today extension (widget) I am getting this error (?) in th console during debugging

```<code>[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to prepare place info. (placeInfo = <GEOPDPlaceInfo: 0x281cfeca0> {
}, latLng = <GEOLatLng: 0x283662d00> {
    lat = "10.0";
    lng = "13.0";
})
[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to prepare component value. (componentValue = <GEOPDComponentValue: 0x10400ecb0> {
 }, placeInfo = <GEOPDPlaceInfo: 0x281cfeca0> {
 })
[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to prepare component value. (componentValue = <GEOPDComponentValue: 0x10400f3f0> {
}, entity = <GEOPDEntity: 0x2804f6300> {
    name =     (
                {
            "string_value" = "Hello World";
        }
    );
})
[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to prepare component. (component = <GEOPDComponent: 0x281cfeb80> {
}, componentValue = <GEOPDComponentValue: 0x10400f3f0> {
})
[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to set type on component. (component = <GEOPDComponent: 0x281cfeb80> {
})
</code>```

I dont have any idea what is this and if I should be concerned. However, widget itself seems to be running OK.

I am not able to google any usefull information regarding this.

Body:
In my iOS today extension (widget) I am getting this error (?) in th console during debugging

[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to prepare place info. (placeInfo = <GEOPDPlaceInfo: 0x281cfeca0> {
}, latLng = <GEOLatLng: 0x283662d00> {
    lat = "10.0";
    lng = "13.0";
})
[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to prepare component value. (componentValue = <GEOPDComponentValue: 0x10400ecb0> {
 }, placeInfo = <GEOPDPlaceInfo: 0x281cfeca0> {
 })
[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to prepare component value. (componentValue = <GEOPDComponentValue: 0x10400f3f0> {
}, entity = <GEOPDEntity: 0x2804f6300> {
    name =     (
                {
            "string_value" = "Hello World";
        }
    );
})
[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to prepare component. (component = <GEOPDComponent: 0x281cfeb80> {
}, componentValue = <GEOPDComponentValue: 0x10400f3f0> {
})
[Intents] __INGEOPDPlaceCreateFromCoordinate Failed to set type on component. (component = <GEOPDComponent: 0x281cfeb80> {
})

I dont have any idea what is this and if I should be concerned. However, widget itself seems to be running OK.

I am not able to google any usefull information regarding this.


问:
Socket.io emit to Sockets matching multiple rooms
It seems simple to me, but if haven't figured out how or if it is doable with socket.io.
I want to send a message to sockets which are in multiple rooms

io.to(['room-1', 'room-2']).emit()

io.to('room-1').to('room-2').emit()

both versions send messages to sockets either in room-1 and/or room-2, but i would like to send this message only to sockets which are in both rooms.

I saw this question, but it is fairly old and used socket.io v1. I was wondering if there is a more recent solution to this problem.
socket.io broadcast only to users who are in room A and B

Is there a way to achieve this?


问:
ElasticSearch/OpenSearch: The limit of the length of keyword field?
I'm quite new to ElasticSearch/OpenSearch, so if I overlook something basic, please forgive me.

I was trying to index a super long text(like 500,000 character length), into a keyword type field. Before that, I increased the ignore_above parameter of the field to 147483647.

However, the following error occurred and indexing failed.

```<code>[400] {"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"Document contains at least one immense term in field=\"content\" (whose UTF8 encoding is longer than the max length 32766), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '[12, 12, 12, 50, 48, 50, 50, 46, 49, 48, 10, 86, 111, 108, 46, 55, 55, 47, 78, 111, 46, 49, 49, 47, 49, 49, 48, 48, 10, 10]...', original message: bytes can be at most 32766 in length; got 474312"}],"type":"illegal_argument_exception","reason":"Document contains at least one immense term in field=\"content\" (whose UTF8 encoding is longer than the max length 32766), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '[12, 12, 12, 50, 48, 50, 50, 46, 49, 48, 10, 86, 111, 108, 46, 55, 55, 47, 78, 111, 46, 49, 49, 47, 49, 49, 48, 48, 10, 10]...', original message: bytes can be at most 32766 in length; got 474312","caused_by":{"type":"max_bytes_length_exceeded_exception","reason":"bytes can be at most 32766 in length; got 474312"}},"status":400}
</code>```

My take of this is the following:

Lucene, which works under the hood of ElasticSearch, can't process a term longer than 32766 character length. And the long sentence I tried to index into keyword type field is treated as one big term, because it isn't divided by tokenizer.

So, what this error message actually says is; do not index a text longer than 32766 character length into keyword field.

Is my understanding correct? I'd appreciate it if you would shed some lights on it.

Incidentally, I'm using opensearch1.2.4 on docker.

Body:
I'm quite new to ElasticSearch/OpenSearch, so if I overlook something basic, please forgive me.

I was trying to index a super long text(like 500,000 character length), into a keyword type field. Before that, I increased the ignore_above parameter of the field to 147483647.

However, the following error occurred and indexing failed.

[400] {"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"Document contains at least one immense term in field=\"content\" (whose UTF8 encoding is longer than the max length 32766), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '[12, 12, 12, 50, 48, 50, 50, 46, 49, 48, 10, 86, 111, 108, 46, 55, 55, 47, 78, 111, 46, 49, 49, 47, 49, 49, 48, 48, 10, 10]...', original message: bytes can be at most 32766 in length; got 474312"}],"type":"illegal_argument_exception","reason":"Document contains at least one immense term in field=\"content\" (whose UTF8 encoding is longer than the max length 32766), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '[12, 12, 12, 50, 48, 50, 50, 46, 49, 48, 10, 86, 111, 108, 46, 55, 55, 47, 78, 111, 46, 49, 49, 47, 49, 49, 48, 48, 10, 10]...', original message: bytes can be at most 32766 in length; got 474312","caused_by":{"type":"max_bytes_length_exceeded_exception","reason":"bytes can be at most 32766 in length; got 474312"}},"status":400}

My take of this is the following:

Lucene, which works under the hood of ElasticSearch, can't process a term longer than 32766 character length. And the long sentence I tried to index into keyword type field is treated as one big term, because it isn't divided by tokenizer.

So, what this error message actually says is; do not index a text longer than 32766 character length into keyword field.

Is my understanding correct? I'd appreciate it if you would shed some lights on it.

Incidentally, I'm using opensearch1.2.4 on docker.


问:
Spring cloud config server - file named by profile olny
I have separate repository per application so in server configuration I'm using

```<code>spring:
  cloud:
    config:
      server:
        git:
          uri: https://address/scm/arch/poc_configserver_teamglobal.git
          repos:
            sharka:
              pattern: sharka
              uri: https://address/scm/arch/poc_configserver_team_a.git
            sharkb:
              pattern: sharkb
              uri: https://address/scm/arch/poc_configserver_team_b.git
            sharkc:
              pattern: sharkc
              uri: https://address/scm/arch/poc_configserver_team_c.git
              search-paths: areas/shark/.k8s/.config/
</code>```

for now on each repository I have files. for example

sharka-dev.yml

sharka-uat.yml

sharka-prod.yml

I'm wonder if I could somehow skip application name and use only profile name like:

dev.yml

uat.yml

prod.yml

Body:
I have separate repository per application so in server configuration I'm using

spring:
  cloud:
    config:
      server:
        git:
          uri: https://address/scm/arch/poc_configserver_teamglobal.git
          repos:
            sharka:
              pattern: sharka
              uri: https://address/scm/arch/poc_configserver_team_a.git
            sharkb:
              pattern: sharkb
              uri: https://address/scm/arch/poc_configserver_team_b.git
            sharkc:
              pattern: sharkc
              uri: https://address/scm/arch/poc_configserver_team_c.git
              search-paths: areas/shark/.k8s/.config/

for now on each repository I have files. for example

sharka-dev.yml

sharka-uat.yml

sharka-prod.yml

I'm wonder if I could somehow skip application name and use only profile name like:

dev.yml

uat.yml

prod.yml


问:
How can stop angular to convert my font file into base64 in build?
When I am building my angular lib, My TTF file getting converted into base64.
But I want to transfer my ttf file in build and css should point to that only.


问:
Survival analysis in R
I am trying to do a survival analysis on R. I installed survival, survminer, and dplyr functions. Then I run library(survival) and library(survminer). After executing the command I found this

Loading required package: ggplot2
Need help getting started? Try the R Graphics Cookbook: https://r-graphics.org
Loading required package: ggpubr
Error: package or namespace load failed for ‘survminer’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
there is no package called ‘KMsurv’

Is there anyone who help me?

I have tried to install the packages that were showing an error. Finally, it says Try the R Graphics Cookbook: https://r-graphics.org.

Fixing the problem and analyse my data

Title: Survival analysis in R


问:
Prefix has no namespace binding Error while using transform module in MarkLogic
I am using transform module to change the document uri of files while doing mlcp ingestion.

But I am getting below error -

```<code>23/01/13 15:10:37 INFO contentpump.FileAndDirectoryInputFormat: Total input paths to process : 1
23/01/13 15:10:38 ERROR contentpump.TransformWriter: Batch 361007023.0: Document failed permanently: /opt/mlcp-10.0.9-bin/mlcp-10.0.9/bin/data/EDI_22000041.xml
23/01/13 15:10:38 WARN contentpump.TransformWriter: <error:format-string xmlns:error="http://marklogic.com/xdmp/error" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">XDMP-UNBPRFX: (err:XPST0081) Prefix doc has no namespace binding</error:format-string>
23/01/13 15:10:38 INFO contentpump.LocalJobRunner:  completed 100%
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: com.marklogic.mapreduce.MarkLogicCounter:
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: INPUT_RECORDS: 1
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: OUTPUT_RECORDS: 1
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: OUTPUT_RECORDS_COMMITTED: 0
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: OUTPUT_RECORDS_FAILED: 1
</code>```

This is the transform module -

```<code>xquery version "1.0-ml";
module namespace doc = "http://marklogic.com/example";

declare function doc:uri(
  $content as map:map,
  $context as map:map
) as map:map*
{
  let $changeduri := map:get($content, "value")/EDILogFile/DateCreated
  return
    (
      map:put(
          $content, "/EDI"||"_"||$changeduri||".xml")
    )
};
</code>```

This is the custom xquery transformation

```<code>xquery version "1.0-ml";
xdmp:document-load("/opt/urichange.xqy",
    <options xmlns="xdmp:document-load">
      <uri>/opt/urichange.xqy</uri>
      <repair>none</repair>
      <permissions>{xdmp:default-permissions()}</permissions>
    </options>)
</code>```

And this is the file which I am trying to ingest -

```<code><?xml version="1.0" encoding="UTF-8"?>
    <EDILogFile xsi:noNamespaceSchemaLocation="file:///Projects/test/schema/LogFile.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <ID>****</ID>
        <SystemRef>22000041</SystemRef>
        <DateCreated>2022-09-06T19:07:46.3492849+01:00</DateCreated>
        <TimeSaved>240</TimeSaved>
        <Production>true</Production>
        <Partner>test</Partner>
        <MessageType>test</MessageType>
        <Fail>false</Fail>
        <ManyReasons/>
        <SubmissionUser>test</SubmissionUser>
        <InternalBusinessUnit>test</InternalBusinessUnit>
        <Direction>Inbound</Direction>
    </EDILogFile>
</code>```

Body:
I am using transform module to change the document uri of files while doing mlcp ingestion.

But I am getting below error -

23/01/13 15:10:37 INFO contentpump.FileAndDirectoryInputFormat: Total input paths to process : 1
23/01/13 15:10:38 ERROR contentpump.TransformWriter: Batch 361007023.0: Document failed permanently: /opt/mlcp-10.0.9-bin/mlcp-10.0.9/bin/data/EDI_22000041.xml
23/01/13 15:10:38 WARN contentpump.TransformWriter: <error:format-string xmlns:error="http://marklogic.com/xdmp/error" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">XDMP-UNBPRFX: (err:XPST0081) Prefix doc has no namespace binding</error:format-string>
23/01/13 15:10:38 INFO contentpump.LocalJobRunner:  completed 100%
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: com.marklogic.mapreduce.MarkLogicCounter:
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: INPUT_RECORDS: 1
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: OUTPUT_RECORDS: 1
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: OUTPUT_RECORDS_COMMITTED: 0
23/01/13 15:10:38 INFO contentpump.LocalJobRunner: OUTPUT_RECORDS_FAILED: 1

This is the transform module -

xquery version "1.0-ml";
module namespace doc = "http://marklogic.com/example";

declare function doc:uri(
  $content as map:map,
  $context as map:map
) as map:map*
{
  let $changeduri := map:get($content, "value")/EDILogFile/DateCreated
  return
    (
      map:put(
          $content, "/EDI"||"_"||$changeduri||".xml")
    )
};

This is the custom xquery transformation

xquery version "1.0-ml";
xdmp:document-load("/opt/urichange.xqy",
    <options xmlns="xdmp:document-load">
      <uri>/opt/urichange.xqy</uri>
      <repair>none</repair>
      <permissions>{xdmp:default-permissions()}</permissions>
    </options>)

And this is the file which I am trying to ingest -

<?xml version="1.0" encoding="UTF-8"?>
    <EDILogFile xsi:noNamespaceSchemaLocation="file:///Projects/test/schema/LogFile.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <ID>****</ID>
        <SystemRef>22000041</SystemRef>
        <DateCreated>2022-09-06T19:07:46.3492849+01:00</DateCreated>
        <TimeSaved>240</TimeSaved>
        <Production>true</Production>
        <Partner>test</Partner>
        <MessageType>test</MessageType>
        <Fail>false</Fail>
        <ManyReasons/>
        <SubmissionUser>test</SubmissionUser>
        <InternalBusinessUnit>test</InternalBusinessUnit>
        <Direction>Inbound</Direction>
    </EDILogFile>


问:
Stop opening Vtk PyQt Win32OpenGL window
I am generating and saving Saggital Reconstuction of the Dicom CBCT images by using Vtk and PyQt application. During the Flow of Program it open the Vtk PyQT win32 Open GL window for some seconds and then save the file in png. But I donot want to open that window during the flow of program. I just want to save the image, donot want to render it.

```<code>import sys
import vtkmodules.all as vtk
from PyQt5 import QtCore, QtWidgets
from vtkmodules.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
import pydicom
import os
from vtkmodules.vtkIOImage import (
    vtkBMPWriter,
    vtkJPEGWriter,
    vtkPNGWriter,
    vtkPNMWriter,
    vtkPostScriptWriter,
    vtkTIFFWriter
)
from datetime import datetime
from vtkmodules.vtkRenderingCore import (
    vtkActor,
    vtkPolyDataMapper,
    vtkRenderWindow,
    vtkRenderWindowInteractor,
    vtkRenderer,
    vtkWindowToImageFilter
)
from flask import Flask, request, send_file
import base64

app = Flask(__name__)

savePath = r'F:\Nixaam\Jan 2023\Saggital View'
savePath = savePath + '\\'

def create_reader(dir):

    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(dir)
    reader.Update()

    return reader

def create_center(reader):

    (xMin, xMax, yMin, yMax, zMin, zMax) = reader.GetExecutive().GetWholeExtent(reader.GetOutputInformation(0))
    (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing()
    (x0, y0, z0) = reader.GetOutput().GetOrigin()

    center = [x0 + xSpacing * 0.5 * (xMin + xMax),
            y0 + ySpacing * 0.5 * (yMin + yMax),
            z0 + zSpacing * 0.5 * (zMin + zMax)]

    return center

def create_sagittal_slice_matrix(center):

    #Create Sagittal Slice Matrix
    sagittal = vtk.vtkMatrix4x4()
    sagittal.DeepCopy((0, 0, -1, center[0],
                        1, 0, 0, center[1],
                        0, -1, 0, center[2],
                        0, 0, 0, 1))

    return sagittal

def create_resliced_image(reader, sagittal, frame):

    # Reslice image
    widget = QVTKRenderWindowInteractor(frame)
    slice = vtk.vtkImageReslice()
    slice.SetInputConnection(reader.GetOutputPort())
    slice.SetOutputDimensionality(2)
    slice.SetResliceAxes(sagittal)
    slice.SetInterpolationModeToLinear()

    return widget, slice

def create_display_image_actor(slice):

    # Display the image
    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputConnection(slice.GetOutputPort())
    # renderer = vtk.vtkRenderer()

    return actor

def adjust_renderer_settings(renderer, widget, actor):

    # Remove Renderer And Reset
    renderer.RemoveAllViewProps()
    renderer.ResetCamera()
    widget.GetRenderWindow().Render()
    renderer.AddActor(actor)

    widget.GetRenderWindow().AddRenderer(renderer)
    return widget

def setup_interaction(widget):
    # Set up the interaction
    slice_interactorStyle = vtk.vtkInteractorStyleImage()
    slice_interactor = widget.GetRenderWindow().GetInteractor()
    slice_interactor.SetInteractorStyle(slice_interactorStyle)
    widget.GetRenderWindow().SetInteractor(slice_interactor)
    widget.GetRenderWindow().Render()

    return slice_interactor
    # Start interaction
    # slice_interactor.Start()

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, path, parent = None):
        QtWidgets.QMainWindow.__init__(self, parent)

        self.frame = QtWidgets.QFrame()
        self.vl = QtWidgets.QVBoxLayout()

        reader = create_reader(path)

        center = create_center(reader)
        sagittal = create_sagittal_slice_matrix(center)

        self.vtkWidget, slice = create_resliced_image(reader, sagittal, self.frame)
        self.vl.addWidget(self.vtkWidget)

        vtk_out = vtk.vtkOutputWindow()
        vtk_out.SetInstance(vtk_out)

        # create renderer
        renderer = vtk.vtkRenderer()

        # create actor
        actor = create_display_image_actor(slice)

        self.vtkWidget = adjust_renderer_settings(renderer, self.vtkWidget, actor)

        slice_interactor = setup_interaction(self.vtkWidget)

        renWin = vtkRenderWindow()
        renWin.AddRenderer(renderer)
        slice_interactor.SetRenderWindow(renWin)

        renWin.SetSize(1366,768)
        # renWin.SetWindowName('Window')
        # renWin.Render()

        windowto_image_filter = vtkWindowToImageFilter()
        windowto_image_filter.SetInput(renWin)
        windowto_image_filter.SetScale(1)  # image quality
        windowto_image_filter.SetInputBufferTypeToRGB()
        # # Read from the front buffer.
        # windowto_image_filter.ReadFrontBufferOff()
        # windowto_image_filter.Update()

        writer = vtkPNGWriter()
        path = r'F:\Nixaam\Jan 2023\Saggital View'
        path = path + '\\'
        writer.SetFileName(f'{path}saggital_view.png')
        writer.SetInputConnection(windowto_image_filter.GetOutputPort())
        writer.Write()

seriesFilePath = r'F:\Nixaam\Jan 2023\Saggital View\Decompressed\2023-01-13 21-10-32'
app = QtWidgets.QApplication(sys.argv)
window = MainWindow(seriesFilePath)
</code>```

I donot want this window during the program.

Body:
I am generating and saving Saggital Reconstuction of the Dicom CBCT images by using Vtk and PyQt application. During the Flow of Program it open the Vtk PyQT win32 Open GL window for some seconds and then save the file in png. But I donot want to open that window during the flow of program. I just want to save the image, donot want to render it.

import sys
import vtkmodules.all as vtk
from PyQt5 import QtCore, QtWidgets
from vtkmodules.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
import pydicom
import os
from vtkmodules.vtkIOImage import (
    vtkBMPWriter,
    vtkJPEGWriter,
    vtkPNGWriter,
    vtkPNMWriter,
    vtkPostScriptWriter,
    vtkTIFFWriter
)
from datetime import datetime
from vtkmodules.vtkRenderingCore import (
    vtkActor,
    vtkPolyDataMapper,
    vtkRenderWindow,
    vtkRenderWindowInteractor,
    vtkRenderer,
    vtkWindowToImageFilter
)
from flask import Flask, request, send_file
import base64

app = Flask(__name__)

savePath = r'F:\Nixaam\Jan 2023\Saggital View'
savePath = savePath + '\\'

def create_reader(dir):

    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(dir)
    reader.Update()

    return reader

def create_center(reader):

    (xMin, xMax, yMin, yMax, zMin, zMax) = reader.GetExecutive().GetWholeExtent(reader.GetOutputInformation(0))
    (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing()
    (x0, y0, z0) = reader.GetOutput().GetOrigin()

    center = [x0 + xSpacing * 0.5 * (xMin + xMax),
            y0 + ySpacing * 0.5 * (yMin + yMax),
            z0 + zSpacing * 0.5 * (zMin + zMax)]

    return center

def create_sagittal_slice_matrix(center):

    #Create Sagittal Slice Matrix
    sagittal = vtk.vtkMatrix4x4()
    sagittal.DeepCopy((0, 0, -1, center[0],
                        1, 0, 0, center[1],
                        0, -1, 0, center[2],
                        0, 0, 0, 1))

    return sagittal

def create_resliced_image(reader, sagittal, frame):

    # Reslice image
    widget = QVTKRenderWindowInteractor(frame)
    slice = vtk.vtkImageReslice()
    slice.SetInputConnection(reader.GetOutputPort())
    slice.SetOutputDimensionality(2)
    slice.SetResliceAxes(sagittal)
    slice.SetInterpolationModeToLinear()

    return widget, slice

def create_display_image_actor(slice):

    # Display the image
    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputConnection(slice.GetOutputPort())
    # renderer = vtk.vtkRenderer()

    return actor

def adjust_renderer_settings(renderer, widget, actor):

    # Remove Renderer And Reset
    renderer.RemoveAllViewProps()
    renderer.ResetCamera()
    widget.GetRenderWindow().Render()
    renderer.AddActor(actor)

    widget.GetRenderWindow().AddRenderer(renderer)
    return widget

def setup_interaction(widget):
    # Set up the interaction
    slice_interactorStyle = vtk.vtkInteractorStyleImage()
    slice_interactor = widget.GetRenderWindow().GetInteractor()
    slice_interactor.SetInteractorStyle(slice_interactorStyle)
    widget.GetRenderWindow().SetInteractor(slice_interactor)
    widget.GetRenderWindow().Render()

    return slice_interactor
    # Start interaction
    # slice_interactor.Start()

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, path, parent = None):
        QtWidgets.QMainWindow.__init__(self, parent)

        self.frame = QtWidgets.QFrame()
        self.vl = QtWidgets.QVBoxLayout()

        reader = create_reader(path)

        center = create_center(reader)
        sagittal = create_sagittal_slice_matrix(center)

        self.vtkWidget, slice = create_resliced_image(reader, sagittal, self.frame)
        self.vl.addWidget(self.vtkWidget)

        vtk_out = vtk.vtkOutputWindow()
        vtk_out.SetInstance(vtk_out)

        # create renderer
        renderer = vtk.vtkRenderer()

        # create actor
        actor = create_display_image_actor(slice)

        self.vtkWidget = adjust_renderer_settings(renderer, self.vtkWidget, actor)

        slice_interactor = setup_interaction(self.vtkWidget)

        renWin = vtkRenderWindow()
        renWin.AddRenderer(renderer)
        slice_interactor.SetRenderWindow(renWin)

        renWin.SetSize(1366,768)
        # renWin.SetWindowName('Window')
        # renWin.Render()

        windowto_image_filter = vtkWindowToImageFilter()
        windowto_image_filter.SetInput(renWin)
        windowto_image_filter.SetScale(1)  # image quality
        windowto_image_filter.SetInputBufferTypeToRGB()
        # # Read from the front buffer.
        # windowto_image_filter.ReadFrontBufferOff()
        # windowto_image_filter.Update()

        writer = vtkPNGWriter()
        path = r'F:\Nixaam\Jan 2023\Saggital View'
        path = path + '\\'
        writer.SetFileName(f'{path}saggital_view.png')
        writer.SetInputConnection(windowto_image_filter.GetOutputPort())
        writer.Write()

seriesFilePath = r'F:\Nixaam\Jan 2023\Saggital View\Decompressed\2023-01-13 21-10-32'
app = QtWidgets.QApplication(sys.argv)
window = MainWindow(seriesFilePath)

I donot want this window during the program.


问:
Python bypass SSL verification
I am using the below code to get the information from ssl certificates:

```<code>import urllib.parse
from urllib.request import Request, urlopen, ssl, socket
from urllib.error import URLError, HTTPError
import json

hostname = target
context = ssl.create_default_context()

with socket.create_connection((hostname, "443"),timeout=1) as sock:
  with context.wrap_socket(sock, server_hostname=hostname) as ssock:
    print(ssock.version())
    data = json.dumps(ssock.getpeercert())

json_object = json.loads(data)
</code>```

However, some of the certificates may be expired or could be self signed. When I point this code at a server with a self signed certificate, I get [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1124)

Is there a way to adapt this code to not verify the SSL cert?

I have tried looking at the ssl documentation but cant see anything obvious.

Title: Python bypass SSL verification

Body:
I am using the below code to get the information from ssl certificates:

import urllib.parse
from urllib.request import Request, urlopen, ssl, socket
from urllib.error import URLError, HTTPError
import json

hostname = target
context = ssl.create_default_context()

with socket.create_connection((hostname, "443"),timeout=1) as sock:
  with context.wrap_socket(sock, server_hostname=hostname) as ssock:
    print(ssock.version())
    data = json.dumps(ssock.getpeercert())

json_object = json.loads(data)

However, some of the certificates may be expired or could be self signed. When I point this code at a server with a self signed certificate, I get [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1124)

Is there a way to adapt this code to not verify the SSL cert?

I have tried looking at the ssl documentation but cant see anything obvious.


问:
How use unicode in rename in VScode?
When i rename (by f2) header or link in MD file, vscode change all non-latin symbols to percent-code.

```<code>[some link](ссылка)
</code>```

become

```<code>[some link](%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B0)
</code>```

I need then it use unicode. I cant find anything about it in properties and google. May be i bad searching or exist some extension?

Title: How use unicode in rename in VScode?

Body:
When i rename (by f2) header or link in MD file, vscode change all non-latin symbols to percent-code.

[some link](ссылка)

become

[some link](%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B0)

I need then it use unicode. I cant find anything about it in properties and google. May be i bad searching or exist some extension?


问:
Reload page after a change in a modal
I have a page: customers,  where I have a list of customers.

There I have a button to edit the informations'customers.
When I click on this edit button I open a modal in another page: CustomerDetail.

So clicking in editing button I can modify the data in the modal, and when I save date I have a problem. Basically the info in the page customers are not update until I refresh the page.

So in my customerDetail.page.ts, when I click on save:

```<code>onUpdateCustomer(customer){
  //...code...
            updateCustomer.pipe(untilDestroyed(this)).subscribe(
                (data) => {
                    this.loading = false;
                    this.showingUpdateMessage = true
                    this.goToCustomers();
                },
                (error) => {
                    console.log("error - update customer ", error);
                }
            );
}
</code>```

I have tried using goToCustomers but it doesn't work properly

```<code>goToCustomers(){
 this.router.navigate(["/customers"])
}
</code>```

I Would not use window.location.reload() but I don't know how to do to have updated data without reload the page.

Imagine to have a page with a table (customers page), when click on edit button I call the other page CustomerDetail as:

```<code>openCreateCustomerPage() {
    this.router.navigate(["/customerDetails"], {
      queryParams: { customerCreate: true },
    });
</code>```

So I open the modal.

Title: Reload page after a change in a modal

Body:
I have a page: customers,  where I have a list of customers.

There I have a button to edit the informations'customers.
When I click on this edit button I open a modal in another page: CustomerDetail.

So clicking in editing button I can modify the data in the modal, and when I save date I have a problem. Basically the info in the page customers are not update until I refresh the page.

So in my customerDetail.page.ts, when I click on save:

onUpdateCustomer(customer){
  //...code...
            updateCustomer.pipe(untilDestroyed(this)).subscribe(
                (data) => {
                    this.loading = false;
                    this.showingUpdateMessage = true
                    this.goToCustomers();
                },
                (error) => {
                    console.log("error - update customer ", error);
                }
            );
}

I have tried using goToCustomers but it doesn't work properly

goToCustomers(){
 this.router.navigate(["/customers"])
}

I Would not use window.location.reload() but I don't know how to do to have updated data without reload the page.

Imagine to have a page with a table (customers page), when click on edit button I call the other page CustomerDetail as:

openCreateCustomerPage() {
    this.router.navigate(["/customerDetails"], {
      queryParams: { customerCreate: true },
    });

So I open the modal.


问:
How to set a conditional template render if the browser is Firefox?
I'm trying to display a PDF with an "" tag. In Chrome the PDF displays like I want it to. In Firefox nothing is displayed, and the PDF is insta-downloaded instead.

I want to continue to display the PDF in "iframe" if the browser is Chrome, but render an "" tag instead if the browser is Firefox, so I figured I'd set up a conditional property/template like this:

```<code>const PDFviewer = () => {
  const [isFirefox, setIsFirefox] = useState(false);

  useEffect(() => {
    window.onload = function () {
      if (navigator.userAgent.indexOf("Firefox") > 0) {
        setIsFirefox(true);
      }
    };
  }, []);

  return (
    <>
        <Navbar />
        {isFirefox && <h1>Firefox</h1>}

        {!isFirefox && (
          <div className="pdf-wrapper">
            <div className="pdf-viewer">
              <iframe
                src={samplePDF}
                className="i-frame"
              />
            </div>
          </div>
        )}
      </>
    </>
  );
};
</code>```

This doesn't work. When I open the page in Firefox it correctly displays "
Firefox
", but the PDF gets downloaded anyways which I'm trying to avoid.

I also tried:

```<code>    {isFirefox ? <h1>Firefox</h1> :
    <div className="pdf-wrapper">
      <div className="pdf-viewer">
        <iframe
          src={samplePDF}
          className="i-frame"
        />
      </div>
    </div>
  }
</code>```

but the same thing happens and the PDF downloads anyways.

I thought maybe the problem was the slight delay in "useEffect" was causing the page to render "not firefox" before it gets a chance to recognize that it IS Firefox.

So I put the return in a "setTimeout()" like this:

```<code>  setTimeout(()=>{
    return (
    <>
        {isFirefox && <h1>Firefox</h1>}

        {!isFirefox && (
          <div className="pdf-wrapper">
            <div className="pdf-viewer">
              <iframe
                src={samplePDF}
                className="i-frame"
                style={{ height: "100vh", width: "100vw" }}
              />
            </div>
          </div>
        )}
    </>
  );

  }, 1000)
</code>```

but that doesn't work.

Then I tried switching the hooks to

```<code>const [isNotFirefox, setIsNotFirefox] = useState(false)
</code>```

so that Firefox is the default and it wouldn't render the  unless the function determines its NOT Firefox first. But this didn't work either.

I'm running out of ideas on how to potentially fix this. Can somebody help? I want to make it so if the browser is Chrome, it renders the ""; but if the browser is Firefox, it renders an "" tag instead. Is this possible to do?

How can I accomplish that?

If it's not possible, how can I render a PDF without ""? I already tried this React package, "react-pdf":

https://www.npmjs.com/package/react-pdf

but it's giving me nothing but problems and not displaying correctly. It's appearing as a jpeg on a canvas with unneccessary text under it instead of simply showing the PDF. Problems outlined here if anybody knows how to fix this instead

"react-pdf" displaying text found inside the PDF instead of the PDF itself?

Help?

Body:
I'm trying to display a PDF with an "" tag. In Chrome the PDF displays like I want it to. In Firefox nothing is displayed, and the PDF is insta-downloaded instead.

I want to continue to display the PDF in "iframe" if the browser is Chrome, but render an "" tag instead if the browser is Firefox, so I figured I'd set up a conditional property/template like this:

const PDFviewer = () => {
  const [isFirefox, setIsFirefox] = useState(false);

  useEffect(() => {
    window.onload = function () {
      if (navigator.userAgent.indexOf("Firefox") > 0) {
        setIsFirefox(true);
      }
    };
  }, []);

  return (
    <>
        <Navbar />
        {isFirefox &&
Firefox
}

        {!isFirefox && (

        )}
      </>
    </>
  );
};

This doesn't work. When I open the page in Firefox it correctly displays "
Firefox
", but the PDF gets downloaded anyways which I'm trying to avoid.

I also tried:

    {isFirefox ?
Firefox
 :

  }

but the same thing happens and the PDF downloads anyways.

I thought maybe the problem was the slight delay in "useEffect" was causing the page to render "not firefox" before it gets a chance to recognize that it IS Firefox.

So I put the return in a "setTimeout()" like this:

  setTimeout(()=>{
    return (
    <>
        {isFirefox &&
Firefox
}

        {!isFirefox && (

        )}
    </>
  );

  }, 1000)

but that doesn't work.

Then I tried switching the hooks to

const [isNotFirefox, setIsNotFirefox] = useState(false)

so that Firefox is the default and it wouldn't render the  unless the function determines its NOT Firefox first. But this didn't work either.

I'm running out of ideas on how to potentially fix this. Can somebody help? I want to make it so if the browser is Chrome, it renders the ""; but if the browser is Firefox, it renders an "" tag instead. Is this possible to do?

How can I accomplish that?

If it's not possible, how can I render a PDF without ""? I already tried this React package, "react-pdf":

https://www.npmjs.com/package/react-pdf

but it's giving me nothing but problems and not displaying correctly. It's appearing as a jpeg on a canvas with unneccessary text under it instead of simply showing the PDF. Problems outlined here if anybody knows how to fix this instead

"react-pdf" displaying text found inside the PDF instead of the PDF itself?

Help?


问:
How do I include a custom class file from the terminal in Java?
The question seems simple and I used to know how to do this, but I've been looking everywhere to find how to do it again and the search seems fruitless so I thought I'd ask it myself. So I have two .java files in the same directory, Main.java and Car.java. I compile Car.java into Car.class. Then, I go to run the Main.java program using java Main.java, and then I'm given an error that the Car class wasn't found. I don't have any packages or anything like that. All of the files are in the same directory. I'm running a Linux machine and I'm using JDK 19.

Edit:

```<code>Main.java

public class Main {
    public static void main(String[] args) {
    Car car1 = new Car("Chevrolet", "Monte Carlo SS", "Red", 2001, 5000.00F);
    Car car2 = new Car("Ford", "F150", "Black", 2018, 15000.00F);

    System.out.printf("Make of car1: %s\n", car1.make);
    System.out.printf("Model of car1: %s\n", car1.model);
    car1.drive();

    System.out.printf("Make of car2: %s\n", car2.make);
    System.out.printf("Price of car2: $%.2f\n", car2.price);
    car2.horn();
    car2.light();
    }
}
</code>```
```<code>Car.java

public class Car {
    String make, model, color;
    int year;
    float price;

    public Car(String make, String model, String color, int year, float price) {
    this.make = make;
    this.model = model;
    this.color = color;
    this.year = year;
    this.price = price;
    }

    public void driveCar() {
    System.out.println("You drive the car");
    }

    public void breakCar() {
    System.out.println("You break the car");
    }

    public void hornCar() {
    System.out.println("You honk the cars horn");
    }

    public void lightCar() {
    System.out.println("You turn on the cars lights");
    }
}
</code>```

Body:
The question seems simple and I used to know how to do this, but I've been looking everywhere to find how to do it again and the search seems fruitless so I thought I'd ask it myself. So I have two .java files in the same directory, Main.java and Car.java. I compile Car.java into Car.class. Then, I go to run the Main.java program using java Main.java, and then I'm given an error that the Car class wasn't found. I don't have any packages or anything like that. All of the files are in the same directory. I'm running a Linux machine and I'm using JDK 19.

Edit:

Main.java

public class Main {
    public static void main(String[] args) {
    Car car1 = new Car("Chevrolet", "Monte Carlo SS", "Red", 2001, 5000.00F);
    Car car2 = new Car("Ford", "F150", "Black", 2018, 15000.00F);

    System.out.printf("Make of car1: %s\n", car1.make);
    System.out.printf("Model of car1: %s\n", car1.model);
    car1.drive();

    System.out.printf("Make of car2: %s\n", car2.make);
    System.out.printf("Price of car2: $%.2f\n", car2.price);
    car2.horn();
    car2.light();
    }
}

Car.java

public class Car {
    String make, model, color;
    int year;
    float price;

    public Car(String make, String model, String color, int year, float price) {
    this.make = make;
    this.model = model;
    this.color = color;
    this.year = year;
    this.price = price;
    }

    public void driveCar() {
    System.out.println("You drive the car");
    }

    public void breakCar() {
    System.out.println("You break the car");
    }

    public void hornCar() {
    System.out.println("You honk the cars horn");
    }

    public void lightCar() {
    System.out.println("You turn on the cars lights");
    }
}


问:
How to rollout to all gmail users changing a sender's emails categorisation from the Promotions tab to the Primary tab in the default gmail layout?
Our company uses gsuite, and the standard gmail default layout has the tabs for Primary, Promotions, etc. It can be changed (I perfer to) but some keep the default layout.

Our mailing tool with email editor etc is external, and so has a different domain. It gets flagged as Promotions. This is an issue for all those with the default layout as they have to keep looking through Promotions for internal news.

How does an admin / IT department change where a sepcific sender's emails are categorised in these tabs in google's business suite for all users?

Things we've looked at:
I asked our IT department, and they have not found an easy setting or way to control where domains / senders are categorised.

We added the IP ranges our mailing tool sends from, however this only stops the emails being marked as Spam / suspicious. Good to have, but not a solution to tabs.

There is plenty of ways to control it for your personal inbox, and move it manually or set up rules etc as an end user. However we can't expect everytone to do this, we need a way of the admin being able to make the change and roll it out to everyone in the business.

For a seperate issue regarding rolling out email signatures to all users automatically in their inbox settings, there was a solution but required using their API and delving in code rather than an admin setting. If there's a way to somehow do it with that we're happy to explore.

Apparently this is easy to do in other ecosystems such as Microsoft, but we are yet to find an easy way to do this in Google's system. Any ideas?


问:
azure form recognizer doesn't works on airflow
Hi am trying to use azure form recognizer with airflow but when i run the process am getting this error:

```<code>File "/usr/local/lib/python3.9/site-packages/azure/core/pipeline/_base.py", line 103, in send
    self._sender.send(request.http_request, **request.context.options),
  File "/usr/local/lib/python3.9/site-packages/azure/core/pipeline/transport/_requests_basic.py", line 382, in send
    raise error
azure.core.exceptions.ServiceRequestError: read
</code>```

does anyone knows what that error means?

I've try to run locally and it works perfect but once i deploy the dag that error appears

Body:
Hi am trying to use azure form recognizer with airflow but when i run the process am getting this error:

File "/usr/local/lib/python3.9/site-packages/azure/core/pipeline/_base.py", line 103, in send
    self._sender.send(request.http_request, **request.context.options),
  File "/usr/local/lib/python3.9/site-packages/azure/core/pipeline/transport/_requests_basic.py", line 382, in send
    raise error
azure.core.exceptions.ServiceRequestError: read

does anyone knows what that error means?

I've try to run locally and it works perfect but once i deploy the dag that error appears


问:
print list only printing last item

This is the code:

```<code>public static void main(String[] args) {
listOne.add(new Data("Credit Card", "100.00", "1"));
listOne.add(new Data("Medical", "200.00", "2"));
listOne.add(new Data("Alcohol", "100.00", "3"));
listOne.add(new Data("Credit Card", "50.00", "4"));
listOne.add(new Data("Medical", "200.00", "5"));
listOne.add(new Data("Gas", "50.00", "6"));
listOne.add(new Data("Tabacco", "50.00", "7"));
listOne.add(new Data("Gas", "50.00", "8"));

for( int c = 0; c < listOne.size(); c++){
  Data d = listOne.get(c);
  System.out.println(d.getName() + " " + d.getSpent() + " " + d.getIndex());
}
</code>```

This is the output:

Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8

It is only printing the last entry, why? I just can not see what is wrong. I am sure it is right in front of me. Any help would be appreciated.
Thanks,
Rich

Title: print list only printing last item

Body:
This is the code:

public static void main(String[] args) {
listOne.add(new Data("Credit Card", "100.00", "1"));
listOne.add(new Data("Medical", "200.00", "2"));
listOne.add(new Data("Alcohol", "100.00", "3"));
listOne.add(new Data("Credit Card", "50.00", "4"));
listOne.add(new Data("Medical", "200.00", "5"));
listOne.add(new Data("Gas", "50.00", "6"));
listOne.add(new Data("Tabacco", "50.00", "7"));
listOne.add(new Data("Gas", "50.00", "8"));

for( int c = 0; c < listOne.size(); c++){
  Data d = listOne.get(c);
  System.out.println(d.getName() + " " + d.getSpent() + " " + d.getIndex());
}

This is the output:

Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8
Gas 50.00 8

It is only printing the last entry, why? I just can not see what is wrong. I am sure it is right in front of me. Any help would be appreciated.
Thanks,
Rich


问:
Is there a way to extract data from a picture in JPG/PNG? (i.e world map with climate info)
I have a picture in JPG which shows the world and projections of a climate variable by 2050. I need to extract the data (as if the picture was a .tif image) underpinning the view.

I tried to convert the picture from JPG to tiff format and then used the raster function in R to visualize the result, however the chart is not reproduced correctly 100%. The second step I attempted was to then convert raster values back into the original color scale of he legend to obtain real values.
Has anyone a better idea? Thanks!


问:
NodeJS net.socket pipeline transform while loop not wait
My transform pipeline not wait until message buffer loop end and not receive message from destination.

It can send out only when another message trigger and send as two messages together. The destination can receive two messages at that time.

How will I make it await until message buffer read until the end to able to send out individual messages, please ?

Start.js

```<code>import Proxy from "./Proxy.js";

const proxy = Proxy();
  proxy.listen('4000');
</code>```

Proxy.js

```<code>import net from "net";
import {filter} from '../utils/transformStream.js';

export default () =>
    net.createServer((con1) => {
        const con2 = net.connect(
          '1234',
          '127.0.0.1'
        );

        pipeline(con1, con2, filter(), con1, (err) => {
          console.log("pipeline closed", err);
        });

        con2.on("data", async (data) => {
          try {
                console.log("sent from con2:", data);
               }
          }
        }
        con1.on("data", async (data) => {
          try {
                console.log("sent from con1:", data);
               }
          }
        }
</code>```

transformStream.js

```<code>import { Transform } from 'stream';
import { messageBuffer2 } from './msgBuffer2.js';

const filter = () => {
  return new Transform({
    async transform(chunk, encoding, cb) {
        if (chunk.toString("utf-8").includes("Unprocessed")) {
          cb(null, '');
        } else {
          messageBuffer2.push(chunk.toString("utf-8"));
          while (!messageBuffer2.isFinished()) {
            const message = messageBuffer2.handleData();
            cb(null, message);
          }
        }
      }
  });
};

export { filter };
</code>```

Thanks.

Body:
My transform pipeline not wait until message buffer loop end and not receive message from destination.

It can send out only when another message trigger and send as two messages together. The destination can receive two messages at that time.

How will I make it await until message buffer read until the end to able to send out individual messages, please ?

Start.js

import Proxy from "./Proxy.js";

const proxy = Proxy();
  proxy.listen('4000');

Proxy.js

import net from "net";
import {filter} from '../utils/transformStream.js';

export default () =>
    net.createServer((con1) => {
        const con2 = net.connect(
          '1234',
          '127.0.0.1'
        );

        pipeline(con1, con2, filter(), con1, (err) => {
          console.log("pipeline closed", err);
        });

        con2.on("data", async (data) => {
          try {
                console.log("sent from con2:", data);
               }
          }
        }
        con1.on("data", async (data) => {
          try {
                console.log("sent from con1:", data);
               }
          }
        }

transformStream.js

import { Transform } from 'stream';
import { messageBuffer2 } from './msgBuffer2.js';

const filter = () => {
  return new Transform({
    async transform(chunk, encoding, cb) {
        if (chunk.toString("utf-8").includes("Unprocessed")) {
          cb(null, '');
        } else {
          messageBuffer2.push(chunk.toString("utf-8"));
          while (!messageBuffer2.isFinished()) {
            const message = messageBuffer2.handleData();
            cb(null, message);
          }
        }
      }
  });
};

export { filter };

Thanks.


问:
do process.env.NODE_ENV also works for web app that is being deploing through railway ?? or is this only for heroku deployment?
learning MERN stack . When i try to run my google OAuth from my localhost ,it works completely fine. but when i try to run it from link of my web-app provided by railway (production environment) gives me following error: { Access blocked: This app’s request is invalid. You can’t sign in because this app sent an invalid request. You can try again later, or contact the developer about this issue. Learn more about this error
If you are a developer of this app, see error details.
Error 400: redirect_uri_mismatch }

i was expecting as it runs smoothly through my localhost, also work from production environment


问:
Add if not exist SortableJs
How can you add a elm to a list only if it not exist in the list with sortable.

I try to delete from the list if it exist in the list with the onEnd option, but sortable put the elm on the list before drop, so when i drop the elm it's deleted instantly.
Is there an option in sortable to add the elm to the DOM onDrop only ?

Title: Add if not exist SortableJs


问:
can I have instances of classes with different namespace in owl
Hi can I create instances of classes with different namespace in owl?
I have a class performance with name space="http://w3id.org/gbo/" which is different from my namespace .Can I create instances/namedIndividuals of that class?</p>


问:
How to provide drop-down list of a specific resource types to choose from with ARM template
I'm trying to create an ARM template which queries the list of resources (i.e. Cosmos DB instances) in the selected resource group so the user can pick from the list. I then want to use the selected resource to get a property and use it elsewhere in the template.

I don't want the user to have to know the resource name and type it in, rather I'd prefer to produce a list to choose from.

I've tried using a parameter type of string or array along with the [list(resourceId('<id>', resourceGroup().name, '<date>')] but it doesn't produce a drop-down list.

Is this even possible?


问:
Pandas eval returns error on date arithmetic using Timedelta
When I try to use basic date arithmetic in Pandas' eval(), it gives the following error:

Cannot convert input [1 days 00:00:00] of type <class 'pandas._libs.tslibs.timedeltas.Timedelta'> to Timestamp

The same expression run against the data frame works fine, though. Is this a feature of eval() or am I missing something?

A minimal example:

```<code>import pandas as pd

df = pd.DataFrame(data={
    "date": pd.date_range(start="2020-01-01", periods=10, freq='D')
})

# works fine
df.date + pd.Timedelta('1D')

# errors out
df.eval("date + @pd.Timedelta('1D')")
</code>```

Incidentally, the expression complains about undefined "pd", even if it's included in the local_dict parameter to eval(). The only way I found to get around it is with the @ prefix. For what it's worth, I'm using the latest version of pandas==1.5.2.

Body:
When I try to use basic date arithmetic in Pandas' eval(), it gives the following error:

Cannot convert input [1 days 00:00:00] of type <class 'pandas._libs.tslibs.timedeltas.Timedelta'> to Timestamp

The same expression run against the data frame works fine, though. Is this a feature of eval() or am I missing something?

A minimal example:

import pandas as pd

df = pd.DataFrame(data={
    "date": pd.date_range(start="2020-01-01", periods=10, freq='D')
})

# works fine
df.date + pd.Timedelta('1D')

# errors out
df.eval("date + @pd.Timedelta('1D')")

Incidentally, the expression complains about undefined "pd", even if it's included in the local_dict parameter to eval(). The only way I found to get around it is with the @ prefix. For what it's worth, I'm using the latest version of pandas==1.5.2.