问:
SQL Request with LEFT JOIN not able to find data
I'm working on my C# project and I have to get data from database thanks to .sql procedures.

Synthesis :

Table ProprietesCourantes is linked to table Entite.

Table Archive is linked to table EntiteArchive

==> I would like to make a link between ProprietesCourantes and Archive thanks to field Libellé

Table ProprietesCourantes

I have several tables in my case :

```<code>SELECT TOP (1000) [IdEntite]
      ,[Libelle]
      ,[EstActif]
      , ...
      , ...
  FROM [Database].[dbo].[ProprietesCourantes]
  WHERE [Libelle] = 'DELTA SERVICE AUTO';
</code>```

Table Entite

```<code>SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[TypeCodeEntite]
  FROM [Database].[dbo].[Entite]
  WHERE IdEntite = '165';
</code>```

Table Archive

```<code>SELECT TOP (1000) [IdArchive]
      ,[IdEntite]
      ,[NoteFinale]
      ,[EstValide]
  FROM [Database].[dbo].[Archive]
  WHERE IdEntite = '33' and EstValide = '1';
</code>```

Table EntiteArchive

```<code>SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[Libelle]
      ,...
  FROM [Database].[dbo].[EntiteArchive]
</code>```

MY SQL REQUEST :

```<code>SELECT
            ProprietesCourantes.IdEntite                                                                    as IdEntite,
            ProprietesCourantes.Libelle                                                                     as RaisonSociale,
            Entite.CodeEntite                                                                               as IdCMCIC,
            ProprietesCourantes.NomParent                                                                   as NomGN,
            Archive.NoteFinale                                                                              as Cotation,
            Archive.DateValiditeQuestionnaireDeSoutien                                                      as DateValiditeQuestionnaireDeSoutien,
            ProprietesCourantes.CodePays                                                                    as Pays,
            ProprietesCourantes.EstActif                                                                    as Statut,
            CAST(CASE WHEN Entite.CodeEntite = ProprietesCourantes.IdSocMere THEN 1 ELSE 0 END AS BIT)      as EstMaisonMere,
            ProprietesCourantes.IdCMCICParent                                                               as IdCMCICParent,
            ProprietesCourantesGN.CodeAlgo                                                                  as CodeAlgoParent

    FROM ProprietesCourantes

    LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite and Archive.EstValide=1)
    LEFT JOIN Entite ON Entite.IdEntite = ProprietesCourantes.IdEntite
    LEFT JOIN Entite as EntiteGN ON EntiteGN.CodeEntite = ProprietesCourantes.IdCMCICParent
    LEFT JOIN ProprietesCourantes as ProprietesCourantesGN ON ProprietesCourantesGN.IdEntite = EntiteGN.IdEntite

    WHERE Entite.TypeEntite = 1
        AND   (ProprietesCourantes.Libelle LIKE '%'+'DELTA SERVICE'+'%' )
</code>```

As you can see : Cotation and DateValiditeQuestionnaireDeSoutien are NULL because LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite can't work (different IDEntite).

I tried to replace by this, but it doesn't work, any idea ?

```<code>LEFT JOIN Archive   ON ((select EntiteArchive.Libelle from EntiteArchive LEFT JOIN Archive ON (EntiteArchive.IdEntite = Archive.IdEntite)) = ProprietesCourantes.Libelle and Archive.EstValide=1)
</code>```

答:
Is CodeEntite usable as a join?

```<code>JOIN [EntiteArchive] ON [Entite].[CodeEntite] =  [EntiteArchive].[CodeEntite]
JOIN [Archive] ON [EntiteArchive].[IdEntite]  = [Archive].[IdEntite]
</code>```

Body:
I'm working on my C# project and I have to get data from database thanks to .sql procedures.

Synthesis :

Table ProprietesCourantes is linked to table Entite.

Table Archive is linked to table EntiteArchive

==> I would like to make a link between ProprietesCourantes and Archive thanks to field Libellé

Table ProprietesCourantes

I have several tables in my case :

SELECT TOP (1000) [IdEntite]
      ,[Libelle]
      ,[EstActif]
      , ...
      , ...
  FROM [Database].[dbo].[ProprietesCourantes]
  WHERE [Libelle] = 'DELTA SERVICE AUTO';

Table Entite

SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[TypeCodeEntite]
  FROM [Database].[dbo].[Entite]
  WHERE IdEntite = '165';

Table Archive

SELECT TOP (1000) [IdArchive]
      ,[IdEntite]
      ,[NoteFinale]
      ,[EstValide]
  FROM [Database].[dbo].[Archive]
  WHERE IdEntite = '33' and EstValide = '1';

Table EntiteArchive

SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[Libelle]
      ,...
  FROM [Database].[dbo].[EntiteArchive]

MY SQL REQUEST :

SELECT
            ProprietesCourantes.IdEntite                                                                    as IdEntite,
            ProprietesCourantes.Libelle                                                                     as RaisonSociale,
            Entite.CodeEntite                                                                               as IdCMCIC,
            ProprietesCourantes.NomParent                                                                   as NomGN,
            Archive.NoteFinale                                                                              as Cotation,
            Archive.DateValiditeQuestionnaireDeSoutien                                                      as DateValiditeQuestionnaireDeSoutien,
            ProprietesCourantes.CodePays                                                                    as Pays,
            ProprietesCourantes.EstActif                                                                    as Statut,
            CAST(CASE WHEN Entite.CodeEntite = ProprietesCourantes.IdSocMere THEN 1 ELSE 0 END AS BIT)      as EstMaisonMere,
            ProprietesCourantes.IdCMCICParent                                                               as IdCMCICParent,
            ProprietesCourantesGN.CodeAlgo                                                                  as CodeAlgoParent

    FROM ProprietesCourantes

    LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite and Archive.EstValide=1)
    LEFT JOIN Entite ON Entite.IdEntite = ProprietesCourantes.IdEntite
    LEFT JOIN Entite as EntiteGN ON EntiteGN.CodeEntite = ProprietesCourantes.IdCMCICParent
    LEFT JOIN ProprietesCourantes as ProprietesCourantesGN ON ProprietesCourantesGN.IdEntite = EntiteGN.IdEntite

    WHERE Entite.TypeEntite = 1
        AND   (ProprietesCourantes.Libelle LIKE '%'+'DELTA SERVICE'+'%' )

As you can see : Cotation and DateValiditeQuestionnaireDeSoutien are NULL because LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite can't work (different IDEntite).

I tried to replace by this, but it doesn't work, any idea ?

LEFT JOIN Archive   ON ((select EntiteArchive.Libelle from EntiteArchive LEFT JOIN Archive ON (EntiteArchive.IdEntite = Archive.IdEntite)) = ProprietesCourantes.Libelle and Archive.EstValide=1)

Body:
Is CodeEntite usable as a join?

JOIN [EntiteArchive] ON [Entite].[CodeEntite] =  [EntiteArchive].[CodeEntite]
JOIN [Archive] ON [EntiteArchive].[IdEntite]  = [Archive].[IdEntite]


来源: stackexchange

问:
EMR spark not honoring number of executor conf
I'm using --num-executor with EMR spark-submit but the conf is not getting honored. The job runs with multiple executors even if I set it --num-executor 1. I tried it with different EC2 instance type and the number of executors it runs by default seems to vary by instance types.

答:
I guess dynamic allocation is active. You must inactive this parameter on spark configurations or send in spark-submit line like this: </p>

```<code>spark-submit --conf spark.dynamicAllocation.enabled=false --class ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I guess dynamic allocation is active. You must inactive this parameter on spark configurations or send in spark-submit line like this:

spark-submit --conf spark.dynamicAllocation.enabled=false --class ...


问:
With react-native-router-flux, how can I have a tab bar click specify which tab to switch to?
I have a tab bar, with a user profile tab. I want it to redirect to signup if a user is not logged in, but if they are logged in, to go to to the userProfile tab.

here's the code:

```<code>         <Tabs
           key="tabbar"
         >
           {/* Main Screen */}
           <Scene
             key="main"
             component={MainScreen}
             title="Main"
             tab
           />
           {/* User Profile */}
           <Scene
             key="profile"
             component={ProfileScreen}
             title="Profile"
             tab
             type="reset"
             tabBarOnPress={() => {
               if (this.props.userIsLoggedIn) {
                 // how to show the correct tab. tried this didn't
                 // work:
                 // return NavigationActions.tabbar({routes: 1});
               }
               return NavigationActions.loginSignup();
             }}
           />
         </Tabs>
</code>```

I have it so that if user is NOT logged in, it indeed navigates to the correct screen to sign up, but I do not know how to make it show the tab if the user is logged in.

EDIT: * we have tried doing

```<code>onEnter={() => {
  if (!this.props.userIsLoggedIn) {
    NavigationActions.loginSignup();
  }
});
</code>```

however we very briefly see the profile screen, would ideally go directly to signup, without showing any of the profile screen.

答:
Nikolai Answer is old.
You can follow below answer.</p>

```<code>tabBarOnPress={(props) => {
  const routeName = props.navigation.state.key;
  props.navigation.navigate(routeName)
}}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a tab bar, with a user profile tab. I want it to redirect to signup if a user is not logged in, but if they are logged in, to go to to the userProfile tab.

here's the code:

         <Tabs
           key="tabbar"
         >
           {/* Main Screen */}
           <Scene
             key="main"
             component={MainScreen}
             title="Main"
             tab
           />
           {/* User Profile */}
           <Scene
             key="profile"
             component={ProfileScreen}
             title="Profile"
             tab
             type="reset"
             tabBarOnPress={() => {
               if (this.props.userIsLoggedIn) {
                 // how to show the correct tab. tried this didn't
                 // work:
                 // return NavigationActions.tabbar({routes: 1});
               }
               return NavigationActions.loginSignup();
             }}
           />
         </Tabs>

I have it so that if user is NOT logged in, it indeed navigates to the correct screen to sign up, but I do not know how to make it show the tab if the user is logged in.

EDIT: * we have tried doing

onEnter={() => {
  if (!this.props.userIsLoggedIn) {
    NavigationActions.loginSignup();
  }
});

however we very briefly see the profile screen, would ideally go directly to signup, without showing any of the profile screen.

Body:
Nikolai Answer is old.
You can follow below answer.

tabBarOnPress={(props) => {
  const routeName = props.navigation.state.key;
  props.navigation.navigate(routeName)
}}


问:
Find string in string
I trying to write function that searching string in some string.
exmaple:
"qwerty" => key to search
"qasazqertyqwerty"
the program return 1 because qwerty found in the string.

my code function is:

```<code>int normal(char *str, char *str2)
{
    int temp=0;
    while(*str)
    {
        while(*str2)
        {
            if(*str == *str2)
            {
                temp+=1;
            }
            else if(temp == strlen(str2))
            {
                printf("%d", temp/strlen(str2));
            }
            str2++;
            str++;
        }
    }
return 0;
}
</code>```

What the hell the problem in the program(logically)?

答:
Yes, you should use strstr(). But to explain why your function does not work:

Your function always returns 0, simply because there's only one return statement that is always reached.

You will segfault if str is smaller then str2 because you forward both pointers in the inner loop.

The condition temp == strlen(str2) will never be reached, because temp increments and the length of str2 decrements

Title: Find string in string

Body:
I trying to write function that searching string in some string.
exmaple:
"qwerty" => key to search
"qasazqertyqwerty"
the program return 1 because qwerty found in the string.

my code function is:

int normal(char *str, char *str2)
{
    int temp=0;
    while(*str)
    {
        while(*str2)
        {
            if(*str == *str2)
            {
                temp+=1;
            }
            else if(temp == strlen(str2))
            {
                printf("%d", temp/strlen(str2));
            }
            str2++;
            str++;
        }
    }
return 0;
}

What the hell the problem in the program(logically)?


问:
Asking for user input between 2 genders using a while loop and to be stored in a variable?
Want to create a small program that can ask a user a question. Do you want your character to be Male or Female? And output the result. However as you can tell the results are poor from my side.

Can someone give me a hand in fixing this mess as I feel I have over complicated it.

Just some general rules that the program must have:

It must accept both "Male" and "male" as input and vice versa for
female

The user input must be stored in the variable created.

If the user types anything else that is not: 'female' 'Female' 'male' or 'Male' they must try the question again (which is why I put in a while loop)

It's strange but this should be simple for me normally but I've made a bit of a mess of it.

Any help would be appreciated :)

```<code>gender = None

gender = str(input("Enter your Gender1: "))
while gender != 'Male' or 'male' or 'female' or 'Female':
    gender = input("Enter your Gender2: ")
if gender in ['Male', 'male']:
    print("You have chosen Male")
if gender in ['Female', 'female']:
    print("You have chosen Female")

print(gender)
</code>```

I don't mind the whole method changing where options can be used such as:

Press 1 for 'Male' or 2 for 'Female'

Would be of a help :)

答:
With python 3.8, you can do:

def ask_gender() -> str:
  return str(input("Enter your Gender: ")).lower()

valid_genders = ["male", "female"]
gender = None

gender = ask_gender()
while gender not in valid_genders:
  print("Unknown gender, try again")
  gender = ask_gender()

print(f"You have chosen {gender}")
```

Body:
Want to create a small program that can ask a user a question. Do you want your character to be Male or Female? And output the result. However as you can tell the results are poor from my side.

Can someone give me a hand in fixing this mess as I feel I have over complicated it.

Just some general rules that the program must have:

It must accept both "Male" and "male" as input and vice versa for
female

The user input must be stored in the variable created.

If the user types anything else that is not: 'female' 'Female' 'male' or 'Male' they must try the question again (which is why I put in a while loop)

It's strange but this should be simple for me normally but I've made a bit of a mess of it.

Any help would be appreciated :)

gender = None

gender = str(input("Enter your Gender1: "))
while gender != 'Male' or 'male' or 'female' or 'Female':
    gender = input("Enter your Gender2: ")
if gender in ['Male', 'male']:
    print("You have chosen Male")
if gender in ['Female', 'female']:
    print("You have chosen Female")

print(gender)

I don't mind the whole method changing where options can be used such as:

Press 1 for 'Male' or 2 for 'Female'

Would be of a help :)


问:
angular multidimensional array assignment
Working with Angular 5.

What I am trying to do is to assign in array a multidimensional array.

What is working with PHP?

```<code>$arM = array();
$arM["20/02/2020"][1] = ["name"=> 'my name', "id"=> 1];
</code>```

the output of this is:

```<code>Array
(
    [20/02/2020] => Array
        (
            [1] => Array
                (
                    [name] => my name
                    [id] => 1
                )

        )

)
</code>```

In angular when I am doing this is not working. Example:

```<code>let data:any = [];
data["20/02/2020"][1] = myArray;
</code>```

How can I achieve the same result of PHP's?

Body:
Working with Angular 5.

What I am trying to do is to assign in array a multidimensional array.

What is working with PHP?

$arM = array();
$arM["20/02/2020"][1] = ["name"=> 'my name', "id"=> 1];

the output of this is:

Array
(
    [20/02/2020] => Array
        (
            [1] => Array
                (
                    [name] => my name
                    [id] => 1
                )

        )

)

In angular when I am doing this is not working. Example:

let data:any = [];
data["20/02/2020"][1] = myArray;

How can I achieve the same result of PHP's?

Body:
let data:Object = {
      "20/02/2020":[
         {"name":"my name", "id": 1},
         {"name":"my name2", "id": 2},
         {"name":"my name3", "id": 3}
      ]
 };


问:
How to change order of a drag and drop list in Angular Material with up or down buttons?
How to change order of a drag and drop list in Angular Material with up or down buttons? So I want to move an item up or down.

template.html

      <button class="up">Up</button>
      <button class="down">Down</button>

```

<p>component.ts</p>

<pre class="lang-js prettyprint-override"><code>public drop(event: CdkDragDrop<string[]>) {
  moveItemInArray(this.categories, event.previousIndex, event.currentIndex);
}
</code>```

答:
There is a solution If you want to swap in-place without temp variable:

function moveItemInArray(categories, previousIndex, currentIndex){
   categories = categories || [1,2,3,4,5,6]; // you wont here in your solution
   previousIndex = previousIndex || 1; // you wont here in your solution
   currentIndex = currentIndex || 2; // you wont here in your solution

 console.log(categories.toString());
 categories[currentIndex] = categories[previousIndex] + (categories[previousIndex] =  categories[currentIndex]) - categories[currentIndex];
 console.log(categories.toString());
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="moveItemInArray()"></body></code>```

Body:
How to change order of a drag and drop list in Angular Material with up or down buttons? So I want to move an item up or down.

template.html

      <button class="up">Up</button>
      <button class="down">Down</button>

component.ts

public drop(event: CdkDragDrop<string[]>) {
  moveItemInArray(this.categories, event.previousIndex, event.currentIndex);
}

Body:
There is a solution If you want to swap in-place without temp variable:

function moveItemInArray(categories, previousIndex, currentIndex){
   categories = categories || [1,2,3,4,5,6]; // you wont here in your solution
   previousIndex = previousIndex || 1; // you wont here in your solution
   currentIndex = currentIndex || 2; // you wont here in your solution

 console.log(categories.toString());
 categories[currentIndex] = categories[previousIndex] + (categories[previousIndex] =  categories[currentIndex]) - categories[currentIndex];
 console.log(categories.toString());
}

<body onload="moveItemInArray()"></body>


问:
Mirrormaker2.0 vs confluent replicator
Apache Kafka introduced Mirrormaker2(MM2) with the release of Kafka 2.4. MM2 is significantly better than MM1.

I know that from the architecture standpoint, MM1 used to work using producer and consumer API whereas MM2 uses connect API. I believe that the design of MM2 was inspired from Confluent Replicator. Confluent Replicator is finely integrated with Confluent tools. But apart from that, what is the difference between MM2 and confluent Replicator?

答:
At a high level, it's open source and the main difference is how it handles "true" active-active Kafka clusters, not just one way replication or questionable two-way offset manipulation (due to the fact that Replicator is not open source).

Thus the other difference - the support model is wider for MM2 than Confluent specific products

believe that the design of MM2 was inspired from Confluent Replicator.

False. A Cloudera/ex-LinkedIn (now Twitter) engineer developed MM2, not Confluent. Since Replicator isn't open source, it'd be hard to gather inspiration off it, other than the general idea of producing data to another cluster. Multiple open source Kafka Connect plugins already accomplish this.
MM2 is architecturally different (refer KIP-382). If anything, it more closely matches Brooklin but specifically for Kafka rather than external systems

Confluent Replicator is finely integrated with Confluent tools

As of 5.4.x, so is MM2, as the Connect plugin itself is included in Kafka, and therefore any interceptors or converters that Confluent Platform also has on the classpath, would be available as well

Title: Mirrormaker2.0 vs confluent replicator


问:
What's the best way to monitor rabbitmq to make sure everything is running smoothly?
Many times, I get:

-Frozen, load goes to 5.0. Can't use my box.
-Just doesn't work.

答:
This cmd will help you service rabbitmq-server status
OR try theseservice rabbitmq-server stop and service rabbitmq-server start then service rabbitmq-server status.

ContentLicense: CC BY-SA 2.5


问:
Update value of a nested dictionary of varying depth
I'm looking for a way to update dict dictionary1 with the contents of dict update wihout overwriting levelA

dictionary1 = {
    "level1": {
        "level2": {"levelA": 0, "levelB": 1}
    }
}
update = {
    "level1": {
        "level2": {"levelB": 10}
    }
}
dictionary1.update(update)
print(dictionary1)
```
<pre class="lang-py prettyprint-override"><code>{
    "level1": {
        "level2": {"levelB": 10}
    }
}
</code>```

I know that update deletes the values in level2 because it's updating the lowest key level1.

How could I tackle this, given that dictionary1 and update can have any length?

答:
The code below should solve the update({'k1': 1}, {'k1': {'k2': 2}}) issue in @Alex Martelli's answer the right way.

def deepupdate(original, update):
    """Recursively update a dict.

    Subdict's won't be overwritten but also updated.
    """
    if not isinstance(original, abc.Mapping):
        return update
    for key, value in update.items():
        if isinstance(value, abc.Mapping):
            original[key] = deepupdate(original.get(key, {}), value)
        else:
            original[key] = value
    return original
```

Body:
I'm looking for a way to update dict dictionary1 with the contents of dict update wihout overwriting levelA

dictionary1 = {
    "level1": {
        "level2": {"levelA": 0, "levelB": 1}
    }
}
update = {
    "level1": {
        "level2": {"levelB": 10}
    }
}
dictionary1.update(update)
print(dictionary1)

{
    "level1": {
        "level2": {"levelB": 10}
    }
}

I know that update deletes the values in level2 because it's updating the lowest key level1.

How could I tackle this, given that dictionary1 and update can have any length?


问:
Preventing truncation of long strings in pytest
I have written a test harness for system tests of our code using pytest. These tests are used in our continuous integration system so I am using the junit xml output option. The truncation of long strings by pytest is causing me problems. I know I can prevent it using the -vv option but then that gives verbose output for the results of each test which is difficult to read. Essentially I want a different way to prevent the truncation of the long string at least in the junit xml file. If it also worked in the console output, that would be better but not essential.

Our code produces reports with a large number of values and I compare the output to a set of output known to be correct. I am reporting all fields that are in error not just the first error. So I am generating a list of strings with one error per string. I then join the strings with newlines to create one long string and long string that contains all the errors. If the assertion fails I need to see the entire contents of the string which could be several hundred lines.

```<code>errors = []
error.extend(get_report_errors())
s = '\n'.join(errors)
assert (s == '')
</code>```

Any suggestions

I am using python 2.6 and 2.7 and pytest 2.3.5. I can upgrade the version of pytest of needed.

答:
A simple hack that works with higher versions of pytest (e.g. 5) is to modify the values that control how much of the diff is truncated.

```<code># conftest.py
from _pytest.assertion import truncate
truncate.DEFAULT_MAX_LINES = 9999
truncate.DEFAULT_MAX_CHARS = 9999
</code>```

This allows you to leave verbosity at 0 but still see what failed for long comparisons. Just make sure to check whenever you update pytest to make sure the internals didn't change since this is mucking around inside there.

Edit
As Cecil Curry points out, this hack is not intended as a complete solution. Hopefully
this feature gets added to Pytest so we can get what we want without breaking encapsulation. :)

Body:
I have written a test harness for system tests of our code using pytest. These tests are used in our continuous integration system so I am using the junit xml output option. The truncation of long strings by pytest is causing me problems. I know I can prevent it using the -vv option but then that gives verbose output for the results of each test which is difficult to read. Essentially I want a different way to prevent the truncation of the long string at least in the junit xml file. If it also worked in the console output, that would be better but not essential.

Our code produces reports with a large number of values and I compare the output to a set of output known to be correct. I am reporting all fields that are in error not just the first error. So I am generating a list of strings with one error per string. I then join the strings with newlines to create one long string and long string that contains all the errors. If the assertion fails I need to see the entire contents of the string which could be several hundred lines.

errors = []
error.extend(get_report_errors())
s = '\n'.join(errors)
assert (s == '')

Any suggestions

I am using python 2.6 and 2.7 and pytest 2.3.5. I can upgrade the version of pytest of needed.

Body:
A simple hack that works with higher versions of pytest (e.g. 5) is to modify the values that control how much of the diff is truncated.

# conftest.py
from _pytest.assertion import truncate
truncate.DEFAULT_MAX_LINES = 9999
truncate.DEFAULT_MAX_CHARS = 9999

This allows you to leave verbosity at 0 but still see what failed for long comparisons. Just make sure to check whenever you update pytest to make sure the internals didn't change since this is mucking around inside there.

Edit
As Cecil Curry points out, this hack is not intended as a complete solution. Hopefully
this feature gets added to Pytest so we can get what we want without breaking encapsulation. :)


问:
How to use progress bar in wpf without multithreading?
Help please.

I want to see the progress bar change with the IsIndeterminate= true property while reading from the database.

I know that I can use Task and BackgroundWorker to create another thread. But for me, it is very important that I do not leave the method in which the long-term operation takes place until it is finished. What can be done in this case?

P.S. Sorry for my English :)

答:
You can't. The UI thread needs to run to display the change to the progress bar, at the same time as your method is running.

Run your method in a background thread, but disable everything in the window before you start so the user can't change anything, and set the mouse pointer to an hourglass so they don't try.

Use try/catch/finally to re-enable everything at the end and reset the mouse pointer.


问:
Can i substract 2 column given some conditions pandas
I have a df that looks like this

I want to subtract  EndTime - StartTime only if channel is 1000
smth like this: df.loc[df['Channel'] == 1000]['X channel view time']=df['EndTime']-df['StartTime']
this should be the fastest but does not appear to be working so

```<code>def watch_time(row,channel):
    val=0
    if row['Channel']==channel:
        val=row['EndTime']-row['StartTime']

    return val
df['BTV_view_time'] = df.apply(watch_time,args=250,axis=1)
</code>```

but this is a lot slower?

答:
You could try something like this:</p>

```<code>import numpy as np
df['X channel view time'] = np.where(df['channel'] == 1000, df['EndTime'] - df['StartTime'], 0)
</code>```

Body:
I have a df that looks like this

I want to subtract  EndTime - StartTime only if channel is 1000
smth like this: df.loc[df['Channel'] == 1000]['X channel view time']=df['EndTime']-df['StartTime']
this should be the fastest but does not appear to be working so

def watch_time(row,channel):
    val=0
    if row['Channel']==channel:
        val=row['EndTime']-row['StartTime']

    return val
df['BTV_view_time'] = df.apply(watch_time,args=250,axis=1)

but this is a lot slower?

Body:
You could try something like this:

import numpy as np
df['X channel view time'] = np.where(df['channel'] == 1000, df['EndTime'] - df['StartTime'], 0)


问:
What is meant by the term "local object variable"?
Are "local object variables" the variables that are used or initialized in a method, or are they the arguments taken in? I can't find this term in Xcode's documentation or Google.

I found this in the Objective-C book that I'm using. The full quote is

Local variables that are basic C data types have no default initial value, so you must set them to some value before using them. The three local variables in the reduce method are set to values before they are used, so that's not a problem here. Local object variables are initialized to nil by default. Unlike your instance variables (which retain their values through method calls), these local variables have no memory. Therefore, after the method returns, the values of these variables disappear. Every time a method is called, each local variable defined in that method is reinitialized to the value specified (if any) with the variable's declaration."

答: Local variables are defined in the method and scope of the variables that have existed inside the method itself.</p>


问:
Get users from an AD group
I have this code to work with users from a group

```<code>DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);
myGroupSearcher.PropertiesToLoad.Add("member");

SearchResult myGroupSearchResult = myGroupSearcher.FindOne();

if (myGroupSearchResult != null)
{
    ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];

    int intMemberCount = myUsersInGroup.Count;

    for (int i = 0; i < intMemberCount; i++)
    {
        //Split the current result
        string[] strProperites = myUsersInGroup[i].ToString().Split(',');

        //Get the CN
        string strUsername = strProperites[0].Substring(3);

        DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry);
        myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
        myUserSearcher.PropertiesToLoad.Add("memberOf");

        SearchResult myUserSearchResult = myUserSearcher.FindOne();

        //Do some work
    }
}
</code>```

This works for most users, but for some, the strUsername gets turncated depending on how the customers AD looks like (if the user have a CN containing ,). So this solution isnt the most optimal to use. Is there a way to get the samaccount name when searching for members in a group? Or is there a better way?

答:
```<code>string[] strProperites = myUsersInGroup[i].ToString().Split(new string[] { "cn=" }, StringSplitOptions.RemoveEmptyEntries);
</code>```

Title: Get users from an AD group

Body:
I have this code to work with users from a group

DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);
myGroupSearcher.PropertiesToLoad.Add("member");

SearchResult myGroupSearchResult = myGroupSearcher.FindOne();

if (myGroupSearchResult != null)
{
    ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];

    int intMemberCount = myUsersInGroup.Count;

    for (int i = 0; i < intMemberCount; i++)
    {
        //Split the current result
        string[] strProperites = myUsersInGroup[i].ToString().Split(',');

        //Get the CN
        string strUsername = strProperites[0].Substring(3);

        DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry);
        myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
        myUserSearcher.PropertiesToLoad.Add("memberOf");

        SearchResult myUserSearchResult = myUserSearcher.FindOne();

        //Do some work
    }
}

This works for most users, but for some, the strUsername gets turncated depending on how the customers AD looks like (if the user have a CN containing ,). So this solution isnt the most optimal to use. Is there a way to get the samaccount name when searching for members in a group? Or is there a better way?


问:
Cypress, read the data from API response
All of the example I found are with calling the API and defining method and URL. For example

```<code>  cy.server()

  cy.route({
    method: 'GET',
    url: 'https://www.something.com',
  }).as('get_jobs')

  cy.get('[data-cy="job-search-input"] button').click()

  cy.wait('@get_jobs').then((xhr) => {
     cy.log(xhr.response.body.data)
  })
</code>```

What I want is just to select the button, press click and read the response that it gives me. I don't wanna define url and method  again, but use the one that is already used in the code and just check the response that it gives me after pressing the button.

How can I do that?

答:
If you just want to read the response, you can use onReponse in cy.server:

cy.server({
  onResponse(response) {
    // Log every response
    console.log("response", response);
    // Using the response URL from OP's question
    if (response.url.includes("https://www.something.com")) {
      // etc.
    }
  }
});
```

Body:
All of the example I found are with calling the API and defining method and URL. For example

  cy.server()

  cy.route({
    method: 'GET',
    url: 'https://www.something.com',
  }).as('get_jobs')

  cy.get('[data-cy="job-search-input"] button').click()

  cy.wait('@get_jobs').then((xhr) => {
     cy.log(xhr.response.body.data)
  })

What I want is just to select the button, press click and read the response that it gives me. I don't wanna define url and method  again, but use the one that is already used in the code and just check the response that it gives me after pressing the button.

How can I do that?


问:
Create / write files on Pepper QISDK
We want to take a picture on a Pepper Robot and save it (somehow) -> The first idea is to compress to .jpg file.

TakePicture action is taken from QISDK tutorial, then we create the File as given below:

```

    File file = new File("image.jpg");
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        FileOutputStream out = new FileOutputStream(file);
        getPicture().compress(Bitmap.CompressFormat.JPEG, 100, out);
    // getPicture() is The Bitmap we get from TakePicture Action.
        Log.i("COMPRESSED", "SUCCES");
        out.close();
    } catch (IOException e) {
        Log.i("COMPRESSED", "FAIL");
        e.printStackTrace();
    }

```

But the code throws exception IOException Read-only file system. That means, that the Robot environment prevents from creating/writing files, which I believe is for the safety reasons.  But the picture in Bitmap format is not what we want.

Is there any possible work-around or solutions to this problem?

答:
I have found a solution, I just made a file with

```

        file = File.createTempFile("image", ".jpg", this.getCacheDir());

```

This way it allows to make a fully writable temporary file, that can afterward be compressed, edited etc.

Using absolute path to the /temp android folder might also work, but that depends on Android version.

Title: Create / write files on Pepper QISDK

Body:
We want to take a picture on a Pepper Robot and save it (somehow) -> The first idea is to compress to .jpg file.

TakePicture action is taken from QISDK tutorial, then we create the File as given below:

    File file = new File("image.jpg");
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        FileOutputStream out = new FileOutputStream(file);
        getPicture().compress(Bitmap.CompressFormat.JPEG, 100, out);
    // getPicture() is The Bitmap we get from TakePicture Action.
        Log.i("COMPRESSED", "SUCCES");
        out.close();
    } catch (IOException e) {
        Log.i("COMPRESSED", "FAIL");
        e.printStackTrace();
    }

But the code throws exception IOException Read-only file system. That means, that the Robot environment prevents from creating/writing files, which I believe is for the safety reasons.  But the picture in Bitmap format is not what we want.

Is there any possible work-around or solutions to this problem?

Body:
I have found a solution, I just made a file with

        file = File.createTempFile("image", ".jpg", this.getCacheDir());

This way it allows to make a fully writable temporary file, that can afterward be compressed, edited etc.

Using absolute path to the /temp android folder might also work, but that depends on Android version.


问:
how to get String from Observable<any> in Angular
I have a backend Rest service that returns a string:

```<code>@GetMapping("/role/{id}")
    public String trouverRole (@PathVariable("id") String username) {
    User u= userrepository.findByUsername(username);
    return u.getRoles().get(0).getName();

    }
</code>```

I'm trying to get the string and use it in angular .ts file:
My service code:

```<code>getrole(name: string): Observable<any> {

    return this.http.get('http://localhost:8080/api/role/'+name);

  }
</code>```

My .ts code:

```<code>login(){
    this.loginService.authentificate(this.credentials,()=>{

     this.loginService.getrole(this.credentials.username).subscribe(
      data => {
      this.role=JSON.stringify(data);
   });

      if ( this.role=="ROLE_ADMIN" )
          { this.router.navigateByUrl('/home/(contentOutlet:produit)');}

          else console.log(this.role);
          /*
      else
      { this.router.navigateByUrl('/home/(contentOutlet:dashboard)')}*/
    })

  }
</code>```

I'm getting this error:

"Unexpected token R in JSON at position 0"

答:
First of all, you have some errors in your code:

```<code>login(){
    this.loginService.authentificate(this.credentials,()=>{
        this.loginService
               .getrole(this.credentials.username)
               .subscribe(data => {
                  this.role = data // No need to stringify, your response (i am asuming) is a text
        });

    // This will allways return false as this.role is still undefined
      if (this.role === "ROLE_ADMIN")
         this.router.navigateByUrl('/home/(contentOutlet:produit)');
      else
         console.log(this.role);
    })

  }
</code>```

So to start, Unexpected token R in JSON at position 0 is thrown because you are using JSON.stringfy() which is fundtion that takes a json object and return a json string. your back-end retruns a string so this function will throw an Error.

then, for the part where you check the this.role, the this.role will not be set until the REST API response. so you should write your code like this.

```<code>.subscribe(data => {
    this.role = data;
    // here you are sure that the role is set to what you are expecting
    // TODO: <-- HERE YOU PUT YOUR CODE THAT DEPENDS ON "ROLE"
});
</code>```

Body:
I have a backend Rest service that returns a string:

@GetMapping("/role/{id}")
    public String trouverRole (@PathVariable("id") String username) {
    User u= userrepository.findByUsername(username);
    return u.getRoles().get(0).getName();

    }

I'm trying to get the string and use it in angular .ts file:
My service code:

getrole(name: string): Observable<any> {

    return this.http.get('http://localhost:8080/api/role/'+name);

  }

My .ts code:

login(){
    this.loginService.authentificate(this.credentials,()=>{

     this.loginService.getrole(this.credentials.username).subscribe(
      data => {
      this.role=JSON.stringify(data);
   });

      if ( this.role=="ROLE_ADMIN" )
          { this.router.navigateByUrl('/home/(contentOutlet:produit)');}

          else console.log(this.role);
          /*
      else
      { this.router.navigateByUrl('/home/(contentOutlet:dashboard)')}*/
    })

  }

I'm getting this error:

"Unexpected token R in JSON at position 0"

Body:
First of all, you have some errors in your code:

login(){
    this.loginService.authentificate(this.credentials,()=>{
        this.loginService
               .getrole(this.credentials.username)
               .subscribe(data => {
                  this.role = data // No need to stringify, your response (i am asuming) is a text
        });

    // This will allways return false as this.role is still undefined
      if (this.role === "ROLE_ADMIN")
         this.router.navigateByUrl('/home/(contentOutlet:produit)');
      else
         console.log(this.role);
    })

  }

So to start, Unexpected token R in JSON at position 0 is thrown because you are using JSON.stringfy() which is fundtion that takes a json object and return a json string. your back-end retruns a string so this function will throw an Error.

then, for the part where you check the this.role, the this.role will not be set until the REST API response. so you should write your code like this.

.subscribe(data => {
    this.role = data;
    // here you are sure that the role is set to what you are expecting
    // TODO: <-- HERE YOU PUT YOUR CODE THAT DEPENDS ON "ROLE"
});


问:
autocomplete="off" is not working on chrome for select box with no form tag
I have found N-Number of post on this and i tried all. For example: nope, false, and some random number but it didn't work for me. I am not using any form tag but i am using select box and mozilla is working good with autocomplete off but chrome is not working at all.

```<code><select name="qty" class="qty" data-id="" autocomplete="off"></select>
</code>```

This is working for mozilla but not for chrome.

答:
Try add each one as needed:</p>

```<code>autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" aria-autocomplete="none"
</code>```

Body:
I have found N-Number of post on this and i tried all. For example: nope, false, and some random number but it didn't work for me. I am not using any form tag but i am using select box and mozilla is working good with autocomplete off but chrome is not working at all.

<select name="qty" class="qty" data-id="" autocomplete="off"></select>

This is working for mozilla but not for chrome.

Body:
Try add each one as needed:

autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" aria-autocomplete="none"


问:
SharePoint Formula: [Created]+60 days = Extension Date (but need it to be a weekday)
I need help with a formula that will add [Extension], a choice field of 30, 45, or 60, to [Created], and return a date [Extension Weekday].

BUT, that future date must be a weekday.

Example: [Created] + [Extension] = [Extension Weekday], but if the result is a Saturday or Sunday, calculate it as the next Monday.

Thanks!

答:
You might use following functions:

```<code>TEXT() : =TEXT(20/02/2020;"dddd") shows the name of that day.
IF(condition;result)
OR(condition1;condition2)
</code>```

So you'll need something like:

```<code>=IF(OR(TEXT(<date>;"dddd")="Saturday";TEXT(<date>;"dddd")="Sunday");"Monday";TEXT(<date>;"dddd"))
</code>```

The formatting, day naming, ... might be language dependent, so I'll advise you to do some experimenting, but this gives you a start.

Body:
You might use following functions:

TEXT() : =TEXT(20/02/2020;"dddd") shows the name of that day.
IF(condition;result)
OR(condition1;condition2)

So you'll need something like:

=IF(OR(TEXT(<date>;"dddd")="Saturday";TEXT(<date>;"dddd")="Sunday");"Monday";TEXT(<date>;"dddd"))

The formatting, day naming, ... might be language dependent, so I'll advise you to do some experimenting, but this gives you a start.


问:
Regular expression to extract first word + first character of all following words
I am (newbie) using R and regular Regular expression to write the regex for manipulating strings in a data.frame column. My data look like this in R:

```<code>c1
Peter Parker
Hawk & Dove
J Jonah Jameson
3JPX spo
Bruce Wayne
</code>```

What I am trying to get is 2nd column "c2" that consists of the following strings:

```<code>c2
PeterP
Hawk&D
JJJ
3JPXs
BruceW
</code>```

Basically I want the entire first word of the string (regardless of length) and the first alphanumeric element of every word after. I have not been able to find any function or logic for this. Is it possible to do so with regex?

Thanks in Advance

答:
The development version of unglue features a multiple argument, which can be a function to apply to identically named matches (here we'd want to concatenate them with paste0()). In our case we want to match the full first word, then the first character of all sequences separated by space, and we have either 1 or 2 of such sequences following the first word:

```<code># remotes::install_github("moodymudskipper/unglue")
library(unglue)
patterns <- c(
  "{c2} {c2=\\S}{=\\S*} {c2=\\S}{=\\S*}",
  "{c2} {c2=\\S}{=\\S*}")

unglue_data(df$c1, patterns, multiple = paste0)
#>       c2
#> 1 PeterP
#> 2 Hawk&D
#> 3    JJJ
#> 4  3JPXs
#> 5 BruceW
</code>```

Body:
I am (newbie) using R and regular Regular expression to write the regex for manipulating strings in a data.frame column. My data look like this in R:

c1
Peter Parker
Hawk & Dove
J Jonah Jameson
3JPX spo
Bruce Wayne

What I am trying to get is 2nd column "c2" that consists of the following strings:

c2
PeterP
Hawk&D
JJJ
3JPXs
BruceW

Basically I want the entire first word of the string (regardless of length) and the first alphanumeric element of every word after. I have not been able to find any function or logic for this. Is it possible to do so with regex?

Thanks in Advance

Body:
The development version of unglue features a multiple argument, which can be a function to apply to identically named matches (here we'd want to concatenate them with paste0()). In our case we want to match the full first word, then the first character of all sequences separated by space, and we have either 1 or 2 of such sequences following the first word:

# remotes::install_github("moodymudskipper/unglue")
library(unglue)
patterns <- c(
  "{c2} {c2=\\S}{=\\S*} {c2=\\S}{=\\S*}",
  "{c2} {c2=\\S}{=\\S*}")

unglue_data(df$c1, patterns, multiple = paste0)
#>       c2
#> 1 PeterP
#> 2 Hawk&D
#> 3    JJJ
#> 4  3JPXs
#> 5 BruceW


问:
Unable to load script from assets index.android.bundle on windows
I'm trying to run my first React Native project for first time on my device (Android 4.2.2).

And I get:

unable to load script from assets index.android.bundle

Commands that I used:

cd (project directory)

react-native start

react-native run-android

答:
This problem also happens if you define an android:networkSecurityConfig in your main AndroidManifest.xml. The android:usesCleartextTraffic="true" in your debug AndroidManifest.xml will be ignored.

To fix this issue, you have to configure the app to allow http traffic to localhost.

Create a file android/src/debug/res/xml/network_security_config.xml:

```<code><?xml version="1.0" encoding="utf-8" ?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>
</code>```

And reference it in android/src/debug/AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8" ?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:networkSecurityConfig="@xml/network_security_config"
        tools:targetApi="28"
        tools:ignore="GoogleAppIndexingWarning" />
</manifest>
</code>```

Further infos here: https://medium.com/astrocoders/i-upgraded-to-android-p-and-my-react-native-wont-connect-to-my-computer-to-download-index-delta-42580377e1d3

Body:
This problem also happens if you define an android:networkSecurityConfig in your main AndroidManifest.xml. The android:usesCleartextTraffic="true" in your debug AndroidManifest.xml will be ignored.

To fix this issue, you have to configure the app to allow http traffic to localhost.

Create a file android/src/debug/res/xml/network_security_config.xml:

<?xml version="1.0" encoding="utf-8" ?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

And reference it in android/src/debug/AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8" ?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:networkSecurityConfig="@xml/network_security_config"
        tools:targetApi="28"
        tools:ignore="GoogleAppIndexingWarning" />
</manifest>

Further infos here: https://medium.com/astrocoders/i-upgraded-to-android-p-and-my-react-native-wont-connect-to-my-computer-to-download-index-delta-42580377e1d3


问:
JPA & Hibernate: Eager loading performing subsequent queries to fetch all data, instead of doing it in just one query
I have the following doubt. I would like to know why when using JPA and Hibernate, when performing an Eager loading in a ManyToOne or OneToMany relationship, it calls the DB in order to obtain the Entity information but additionally, produces subsequent queries to fetch every child.

On the other side, when using a query with JOIN FETCH it performs the query as I would expect it to be, taking the information all at once, since the fetchType is denoted as "EAGER".

Here it is a simple example:

I have the Class Student which has ManyToOne relationship with the Class Classroom.

```<code>@Entity
@Table(name = "STUDENT")
public class Student {

@ManyToOne(optional = true, fetch = FetchType.EAGER)
        @JoinColumn(name = "ClassroomID")
        private Classroom mainClass;
</code>```

In the other side there is the class named Classroom as follows:

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

@OneToMany(cascade = CascadeType.ALL, mappedBy = "mainClass", fetch = FetchType.EAGER)
private List<Student> studentsList;
</code>```

When obtaining the Classroom object, it performs one query to obtain the information from itself and subsequent queries to obtain the information of each student contained in the studentsList for every classRoom object.

First query:

```<code>Hibernate:
/* SELECT
         r
     FROM
         Classroom r
     LEFT JOIN
         r.classStudents */

     select
         classroom0_.id as id1_0_,
         classroom0_.number as number2_0_
     from
         Classroom classroom0_
     left outer join
         STUDENT classstude1_
             on classroom0_.id=classstude1_.ClassroomID
</code>```

And then it performs the next query as many times as Students assigned to each classroom.

```<code>  Hibernate:
      /* load one-to-many com.hw.access.Classroom.classStudents */
      select
          classstude0_.ClassroomID as Classroo4_0_1_,
          classstude0_.id as id1_1_1_,
          classstude0_.id as id1_1_0_,
          classstude0_.FIRST_NAME as FIRST_NA2_1_0_,
          classstude0_.LAST_NAME as LAST_NAM3_1_0_,
          classstude0_.ClassroomID as Classroo4_1_0_
      from
          STUDENT classstude0_
      where
          classstude0_.ClassroomID=?
</code>```

The question is: Why doesn't it takes the Information all at once? Why doesn't it takes the information in just one query? As it is already performing the Join clause there.

Why just when adding Fetch explicitly in the query, it does what it is requested?

For example:

```<code>SELECT
         r
     FROM
         Classroom r
     LEFT JOIN FETCH
         r.classStudents */
</code>```

And then, the output query does takes all the information in just one query:

```<code>Hibernate:

        select
              classroom0_.id as id1_0_0_,
              classstude1_.id as id1_1_1_,
              classroom0_.number as number2_0_0_,
              classstude1_.FIRST_NAME as FIRST_NA2_1_1_,
              classstude1_.LAST_NAME as LAST_NAM3_1_1_,
              classstude1_.ClassroomID as Classroo4_1_1_,
              classstude1_.ClassroomID as Classroo4_0_0__,
              classstude1_.id as id1_1_0__
          from
              Classroom classroom0_
          left outer join
              STUDENT classstude1_
                  on classroom0_.id=classstude1_.ClassroomID
</code>```

答:
As you have a OneToMany relationship from Classroom to Student, using a single query would cause the Classroom fields to be repeated for each line.
Now imagine you have a second OneToMany relationship from Classroom to, say Course; if, for a given Classroom you have N Students and M Courses, you would have a query returning N+M rows, each containing the same fields of class Classroom.

Body:
I have the following doubt. I would like to know why when using JPA and Hibernate, when performing an Eager loading in a ManyToOne or OneToMany relationship, it calls the DB in order to obtain the Entity information but additionally, produces subsequent queries to fetch every child.

On the other side, when using a query with JOIN FETCH it performs the query as I would expect it to be, taking the information all at once, since the fetchType is denoted as "EAGER".

Here it is a simple example:

I have the Class Student which has ManyToOne relationship with the Class Classroom.

@Entity
@Table(name = "STUDENT")
public class Student {

@ManyToOne(optional = true, fetch = FetchType.EAGER)
        @JoinColumn(name = "ClassroomID")
        private Classroom mainClass;

In the other side there is the class named Classroom as follows:

@Entity
public class Classroom {

@OneToMany(cascade = CascadeType.ALL, mappedBy = "mainClass", fetch = FetchType.EAGER)
private List<Student> studentsList;

When obtaining the Classroom object, it performs one query to obtain the information from itself and subsequent queries to obtain the information of each student contained in the studentsList for every classRoom object.

First query:

Hibernate:
/* SELECT
         r
     FROM
         Classroom r
     LEFT JOIN
         r.classStudents */

     select
         classroom0_.id as id1_0_,
         classroom0_.number as number2_0_
     from
         Classroom classroom0_
     left outer join
         STUDENT classstude1_
             on classroom0_.id=classstude1_.ClassroomID

And then it performs the next query as many times as Students assigned to each classroom.

  Hibernate:
      /* load one-to-many com.hw.access.Classroom.classStudents */
      select
          classstude0_.ClassroomID as Classroo4_0_1_,
          classstude0_.id as id1_1_1_,
          classstude0_.id as id1_1_0_,
          classstude0_.FIRST_NAME as FIRST_NA2_1_0_,
          classstude0_.LAST_NAME as LAST_NAM3_1_0_,
          classstude0_.ClassroomID as Classroo4_1_0_
      from
          STUDENT classstude0_
      where
          classstude0_.ClassroomID=?

The question is: Why doesn't it takes the Information all at once? Why doesn't it takes the information in just one query? As it is already performing the Join clause there.

Why just when adding Fetch explicitly in the query, it does what it is requested?

For example:

SELECT
         r
     FROM
         Classroom r
     LEFT JOIN FETCH
         r.classStudents */

And then, the output query does takes all the information in just one query:

Hibernate:

        select
              classroom0_.id as id1_0_0_,
              classstude1_.id as id1_1_1_,
              classroom0_.number as number2_0_0_,
              classstude1_.FIRST_NAME as FIRST_NA2_1_1_,
              classstude1_.LAST_NAME as LAST_NAM3_1_1_,
              classstude1_.ClassroomID as Classroo4_1_1_,
              classstude1_.ClassroomID as Classroo4_0_0__,
              classstude1_.id as id1_1_0__
          from
              Classroom classroom0_
          left outer join
              STUDENT classstude1_
                  on classroom0_.id=classstude1_.ClassroomID


问:
Android SeekBar Flipped Horizontally
With the Android SeekBar, you can normally drag the thumb to the left or to the right and the yellow progress color is to the left of the thumb. I want the exact opposite, essentially flipping the yellow progress color to the right of the thumb and flipping the entire SeekBar on the y-axis.

Can anyone point me in the right direction? Thanks!

答:
This should fix a few issues with @mhenry answer</p>

```<code>class ReverseSeekBar : SeekBar {
    constructor(context: Context) : super(context) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        init()
    }

    var first = true

    override fun onTouchEvent(event: MotionEvent): Boolean {
        event.setLocation(this.width - event.x, event.y)
        return super.onTouchEvent(event)
    }

    override fun getProgress(): Int {
        return max - super.getProgress() + min
    }

    override fun setProgress(progress: Int) {
        super.setProgress(max - progress + min)
    }

    override fun onDraw(canvas: Canvas?) {
        if (first) {
            first = false
            val old = progress
            progress = min + max - progress
            super.onDraw(canvas)
            progress = old
        } else
            super.onDraw(canvas)
    }

    private fun init() {
        rotation = 180f
    }

}
</code>```

Title: Android SeekBar Flipped Horizontally

Body:
This should fix a few issues with @mhenry answer

class ReverseSeekBar : SeekBar {
    constructor(context: Context) : super(context) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        init()
    }

    var first = true

    override fun onTouchEvent(event: MotionEvent): Boolean {
        event.setLocation(this.width - event.x, event.y)
        return super.onTouchEvent(event)
    }

    override fun getProgress(): Int {
        return max - super.getProgress() + min
    }

    override fun setProgress(progress: Int) {
        super.setProgress(max - progress + min)
    }

    override fun onDraw(canvas: Canvas?) {
        if (first) {
            first = false
            val old = progress
            progress = min + max - progress
            super.onDraw(canvas)
            progress = old
        } else
            super.onDraw(canvas)
    }

    private fun init() {
        rotation = 180f
    }

}


问:
foreach loop gives error CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
I am trying to run a cmdlet on each element of a list. but i am getting the error ObjectNotFound: (*@{samAccountName=my_ad_username}*:ADUser) [Get-ADUser], ADIdentityNotFoundException for each element of my list.

Bellow is cmdlet

```<code>$users = Get-ADUser -Filter "*" -SearchBase "OU=Europe,DC=myDC,DC=com" | select samAccountName

$fr_all_grp_assigned_to_different_users = Foreach ($user in $users){
        #Get-AdUser $user
    }
</code>```

Result

```<code>> Get-ADUser : Cannot validate argument on parameter 'Identity'. The
> Identity property on the argument is null or empty. At line:6 char:20
> +         Get-aduser $user
> +                    ~~~~~
>     + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
>     + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
> Get-ADUser : Cannot validate argument on parameter 'Identity'. The
> Identity property on the argument is null or empty. At line:6 char:20
> +         Get-aduser $user
</code>```

Line 6 refers to #Get-AdUser $user

Can anyone help ?

答:
Inside of your loop, you need to provide the SamAccountName value to the -Identity parameter of Get-ADUser.

```<code>Get-ADUser -Identity $user.SamAccountName
</code>```

Explanation:

You can execute Get-ADUser by providing values manually to parameters or piping objects into the command and let advanced parameter assignment dynamically map values to parameters. Some parameters are positional in that you don't need to specify the parameter name when running the command with a value(s). These features/concepts exists across most PowerShell commands.

In the case of Get-ADUser Value, Value is automatically mapped to parameter -Identity. -Identity expects one of the following values:

A distinguished name

A GUID (objectGUID)

A security identifier (objectSid)

A SAM account name (sAMAccountName)

Get-ADUser has a convenient feature where if you pass it a Microsoft.ActiveDirectory.Management.ADUser object type (returned from a directory server) through a pipe or to the -Identity parameter, it will automatically perform a search based on the provided values. If you provide it any other object type, it will not automatically select property values to pass to -Identity. Piping to Select SamAccountName returns a PSCustomObject rather than an ADUser object and then you lose your convenience.

Once you are dealing with objects that are not ADUser, you must provide -Identity with the actual value you want to query. In your case, that leaves you with two options.

Option 1: Select only SamAccountName values in your initial query

With this option, you can make use of the -ExpandProperty or -Expand parameter of Select-Object to return only the values of the target property.

```<code>$users = Get-ADUser -Filter * -SearchBase "OU=Europe,DC=myDC,DC=com" |
    Select-Object -ExpandProperty SamAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users) {
    Get-ADUser $user
}
</code>```

Option 2: Use Member Access operator (.) to directly access the SamAccountName value

With this option you can use the syntax object.Property to retrieve the Property value.

```<code># Using the singular object.Property ($user.SamAccountName)
$users = Get-ADUser -Filter * -SearchBase "OU=Europe,DC=myDC,DC=com" |
    Select-Object SamAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users) {
    Get-ADUser $user.SamAccountName
}
</code>```

Starting with PowerShell v3, you can use the same syntax on a collection to return a collection of values (collection.Property).

```<code># Using collection.Property ($users.SamAccountName)
# $user contains only a SamAccountName value here
$users = Get-ADUser -Filter * -SearchBase "OU=Europe,DC=myDC,DC=com" |
    Select-Object -ExpandProperty SamAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users.SamAccountName) {
    Get-ADUser $user
}
</code>```

Body:
I am trying to run a cmdlet on each element of a list. but i am getting the error ObjectNotFound: (*@{samAccountName=my_ad_username}*:ADUser) [Get-ADUser], ADIdentityNotFoundException for each element of my list.

Bellow is cmdlet

$users = Get-ADUser -Filter "*" -SearchBase "OU=Europe,DC=myDC,DC=com" | select samAccountName

$fr_all_grp_assigned_to_different_users = Foreach ($user in $users){
        #Get-AdUser $user
    }

Result

> Get-ADUser : Cannot validate argument on parameter 'Identity'. The
> Identity property on the argument is null or empty. At line:6 char:20
> +         Get-aduser $user
> +                    ~~~~~
>     + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
>     + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
> Get-ADUser : Cannot validate argument on parameter 'Identity'. The
> Identity property on the argument is null or empty. At line:6 char:20
> +         Get-aduser $user

Line 6 refers to #Get-AdUser $user

Can anyone help ?

Body:
Inside of your loop, you need to provide the SamAccountName value to the -Identity parameter of Get-ADUser.

Get-ADUser -Identity $user.SamAccountName

Explanation:

You can execute Get-ADUser by providing values manually to parameters or piping objects into the command and let advanced parameter assignment dynamically map values to parameters. Some parameters are positional in that you don't need to specify the parameter name when running the command with a value(s). These features/concepts exists across most PowerShell commands.

In the case of Get-ADUser Value, Value is automatically mapped to parameter -Identity. -Identity expects one of the following values:

A distinguished name

A GUID (objectGUID)

A security identifier (objectSid)

A SAM account name (sAMAccountName)

Get-ADUser has a convenient feature where if you pass it a Microsoft.ActiveDirectory.Management.ADUser object type (returned from a directory server) through a pipe or to the -Identity parameter, it will automatically perform a search based on the provided values. If you provide it any other object type, it will not automatically select property values to pass to -Identity. Piping to Select SamAccountName returns a PSCustomObject rather than an ADUser object and then you lose your convenience.

Once you are dealing with objects that are not ADUser, you must provide -Identity with the actual value you want to query. In your case, that leaves you with two options.

Option 1: Select only SamAccountName values in your initial query

With this option, you can make use of the -ExpandProperty or -Expand parameter of Select-Object to return only the values of the target property.

$users = Get-ADUser -Filter * -SearchBase "OU=Europe,DC=myDC,DC=com" |
    Select-Object -ExpandProperty SamAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users) {
    Get-ADUser $user
}

Option 2: Use Member Access operator (.) to directly access the SamAccountName value

With this option you can use the syntax object.Property to retrieve the Property value.

# Using the singular object.Property ($user.SamAccountName)
$users = Get-ADUser -Filter * -SearchBase "OU=Europe,DC=myDC,DC=com" |
    Select-Object SamAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users) {
    Get-ADUser $user.SamAccountName
}

Starting with PowerShell v3, you can use the same syntax on a collection to return a collection of values (collection.Property).

# Using collection.Property ($users.SamAccountName)
# $user contains only a SamAccountName value here
$users = Get-ADUser -Filter * -SearchBase "OU=Europe,DC=myDC,DC=com" |
    Select-Object -ExpandProperty SamAccountName
$fr_all_grp_assigned_to_different_users = Foreach ($user in $users.SamAccountName) {
    Get-ADUser $user
}


问:
How do I concatenate two lists inside nested list Python?
How do I concatenate two lists inside the nested list Python?

I have this list

```<code>lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
</code>```

And my expected output is

```<code>lists_of_lists =[[1,2],[3,5],[6,6]]
</code>```

I tried this way

```<code>new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)
</code>```

But I got

```<code>[1, 2, 3, 5, 6, 6]
</code>```

Thank you for any suggestions

答:
Try numpy:

In:

```<code>import numpy as np
lists_of_lists =np.array([[[1],[2]],[[3],[5]],[[6],[6]]])
lists_of_lists.reshape(lists_of_lists.size//2, 2)
</code>```

Out:

```<code>array([[1, 2],
       [3, 5],
       [6, 6]])
</code>```

Body:
How do I concatenate two lists inside the nested list Python?

I have this list

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]

And my expected output is

lists_of_lists =[[1,2],[3,5],[6,6]]

I tried this way

new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)

But I got

[1, 2, 3, 5, 6, 6]

Thank you for any suggestions

Body:
Try numpy:

In:

import numpy as np
lists_of_lists =np.array([[[1],[2]],[[3],[5]],[[6],[6]]])
lists_of_lists.reshape(lists_of_lists.size//2, 2)

Out:

array([[1, 2],
       [3, 5],
       [6, 6]])


问:
What are the Pros/Cons of Flash Builder vs. FlashDevelop?
I want to play around a bit with FLASH for app development. I'm looking for a good IDE for that.  Someone suggested Flash Develop.</p>

答:
Flash Builder, even in version 4.5, has primitive, useless syntax coloring and customization features. From a 700$ package I was expecting at least what I can do with my free text editor.
In the syntax coloring preferences, there is a total of 6 keywords, and you cannot add any custom one.
How am I expected to code having variable names, function calls, and classes look exactly the same?
I will stick to Flash Pro CS5.5 and SciTe.</p>

OwnerDisplayName: MrAnalogy


问:
How to compute the digits of an irrational number one by one?
I want to read digit by digit the decimals of the sqrt of 5 in C.
The square root of 5 is 2,23606797749979..., so this'd be the expected output:

```<code>2
3
6
0
6
7
9
7
7
...
</code>```

I've found the following code:

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

void main()
{
    int number;

    float temp, sqrt;

    printf("Provide the number: \n");

    scanf("%d", &number);

    // store the half of the given number e.g from 256 => 128
    sqrt = number / 2;
    temp = 0;

    // Iterate until sqrt is different of temp, that is updated on the loop
    while(sqrt != temp){
        // initially 0, is updated with the initial value of 128
        // (on second iteration = 65)
        // and so on
        temp = sqrt;

        // Then, replace values (256 / 128 + 128 ) / 2 = 65
        // (on second iteration 34.46923076923077)
        // and so on
        sqrt = ( number/temp + temp) / 2;
    }

    printf("The square root of '%d' is '%f'", number, sqrt);
}
</code>```

But this approach stores the result in a float variable, and I don't want to depend on the limits of the float types, as I would like to extract like 10,000 digits, for instance. I also tried to use the native sqrt() function and casting it to string number using this method, but I faced the same issue.

答:
What you've asked about is a very hard problem, and whether it's even possible to do "one by one" (i.e. without working space requirement that scales with how far out you want to go) depends on both the particular irrational number and the base you want it represented in. For example, in 1995 when a formula for pi was discovered that allows computing the nth binary digit in O(1) space, this was a really big deal. It was not something people expected to be possible.

If you're willing to accept O(n) space, then some cases like the one you mentioned are fairly easy. For example, if you have the first n digits of the square root of a number as a decimal string, you can simply try appending each digit 0 to 9, then squaring the string with long multiplication (same as you learned in grade school), and choosing the last one that doesn't overshoot. Of course this is very slow, but it's simple. The easy way to make it a lot faster (but still asymptotically just as bad) is using an arbitrary-precision math library in place of strings. Doing significantly better requires more advanced approaches and in general may not be possible.

Body:
I want to read digit by digit the decimals of the sqrt of 5 in C.
The square root of 5 is 2,23606797749979..., so this'd be the expected output:

2
3
6
0
6
7
9
7
7
...

I've found the following code:

#include<stdio.h>

void main()
{
    int number;

    float temp, sqrt;

    printf("Provide the number: \n");

    scanf("%d", &number);

    // store the half of the given number e.g from 256 => 128
    sqrt = number / 2;
    temp = 0;

    // Iterate until sqrt is different of temp, that is updated on the loop
    while(sqrt != temp){
        // initially 0, is updated with the initial value of 128
        // (on second iteration = 65)
        // and so on
        temp = sqrt;

        // Then, replace values (256 / 128 + 128 ) / 2 = 65
        // (on second iteration 34.46923076923077)
        // and so on
        sqrt = ( number/temp + temp) / 2;
    }

    printf("The square root of '%d' is '%f'", number, sqrt);
}

But this approach stores the result in a float variable, and I don't want to depend on the limits of the float types, as I would like to extract like 10,000 digits, for instance. I also tried to use the native sqrt() function and casting it to string number using this method, but I faced the same issue.


问:
cbind with loop in R
I'm new with R and I've an issue
So my issue is :
I've multiples tables ex: 10 , also different list from kmeans results related to this tables (10). So I want use cbind in order to add each cluster  to its table :

Ex:

```<code>NEW_table1<- cbind(table1,kmeans_table1$cluster)
NEW_table2<- cbind(table2,kmeans_table2$cluster)
</code>```

...

I've tryd with this code but a get an error

```<code>for (i in 1:10)
{ assign(paste0("NEW_table", i)<-cbind(as.name(paste0("filter_table",i)),Class=(i$cluster) ))
}

> Error in i$cluster : $ operator is invalid for atomic vectors
</code>```

答:
Without seeing the data I'll have a guess that this might work:

```<code>do.call(cbind, mapply(function(x, y) cbind(x, y), tables, kmeans, simplify=F))
</code>```

where tables is a list of your tables i.e. list(tables)
and kmeans is a list of your kmeans i.e. list(kmeans)

```<code>x = 1:10
x2 = list(x, x, x)

y = 10:1
y2 = list(y, y, y)

do.call(cbind, mapply(function(x, y) cbind(x, y), x2, y2, SIMPLIFY = F))
</code>```

Title: cbind with loop in R

Body:
I'm new with R and I've an issue
So my issue is :
I've multiples tables ex: 10 , also different list from kmeans results related to this tables (10). So I want use cbind in order to add each cluster  to its table :

Ex:

NEW_table1<- cbind(table1,kmeans_table1$cluster)
NEW_table2<- cbind(table2,kmeans_table2$cluster)

...

I've tryd with this code but a get an error

for (i in 1:10)
{ assign(paste0("NEW_table", i)<-cbind(as.name(paste0("filter_table",i)),Class=(i$cluster) ))
}

> Error in i$cluster : $ operator is invalid for atomic vectors

Body:
Without seeing the data I'll have a guess that this might work:

do.call(cbind, mapply(function(x, y) cbind(x, y), tables, kmeans, simplify=F))

where tables is a list of your tables i.e. list(tables)
and kmeans is a list of your kmeans i.e. list(kmeans)

x = 1:10
x2 = list(x, x, x)

y = 10:1
y2 = list(y, y, y)

do.call(cbind, mapply(function(x, y) cbind(x, y), x2, y2, SIMPLIFY = F))


问:
Excluding projects from build in YAML configuration azure-pipelines
I am trying to exclude some projects from building in azure pipelines.

I tried the following options...

Trying to build only the projects under core?

```<code>- script: dotnet build **/Core/*.csproj --configuration $(buildConfiguration)
</code>```

and

```<code>- script: dotnet build **/Core/**/*.csproj --configuration $(buildConfiguration)
</code>```

Trying to use the task @DotnNetCli2.0

Referenced the yaml file matching patterns

But couldn't find a good example.

The projects I want to build are under different subfolders as in ../../Core/Domain/Domain.csproj and ../../Core/Presentation/Presentation.csproj

Is there something I'm missing, is it possible; or am I just plain doing something wrong.

答:
You can just use the dotnetcore cli task with something like this:</p>
```<code>- task: DotNetCoreCLI@2
  inputs:
  command: 'build'
  projects: |
      '**/*.csproj'
      '!**/*Mobile*.csproj' # This ignores projects with the occurrence of Mobile anywhere in the filename
</code>```

Body:
I am trying to exclude some projects from building in azure pipelines.

I tried the following options...

Trying to build only the projects under core?

- script: dotnet build **/Core/*.csproj --configuration $(buildConfiguration)

and

- script: dotnet build **/Core/**/*.csproj --configuration $(buildConfiguration)

Trying to use the task @DotnNetCli2.0

Referenced the yaml file matching patterns

But couldn't find a good example.

The projects I want to build are under different subfolders as in ../../Core/Domain/Domain.csproj and ../../Core/Presentation/Presentation.csproj

Is there something I'm missing, is it possible; or am I just plain doing something wrong.

Body:
You can just use the dotnetcore cli task with something like this:

- task: DotNetCoreCLI@2
  inputs:
  command: 'build'
  projects: |
      '**/*.csproj'
      '!**/*Mobile*.csproj' # This ignores projects with the occurrence of Mobile anywhere in the filename


问:
How to write test case for undefined window Object | Vue test utils | Jest Framework
I am using vue test utils - Jest framework for unit testing of my vue file. I'm not able to test the below line.

```<code>const inBrowser = typeof window !== 'undefined';
</code>```

My question is how to set JavaScript Window  as undefined. Is there any way to set window as undefined Browser Object Model (BOM)?

答:
Based on this and this you can use the .spyOn function and set the window as undefined:</p>

```<code>let windowSpy;

beforeEach(() => {
  windowSpy = jest.spyOn(global, 'window', 'get');
  windowSpy.mockImplementation(() => undefined);
});

it('window should be undefined.', () => {
  expect(window).toBeUndefined();
});
</code>```

Body:
I am using vue test utils - Jest framework for unit testing of my vue file. I'm not able to test the below line.

const inBrowser = typeof window !== 'undefined';

My question is how to set JavaScript Window  as undefined. Is there any way to set window as undefined Browser Object Model (BOM)?

Body:
Based on this and this you can use the .spyOn function and set the window as undefined:

let windowSpy;

beforeEach(() => {
  windowSpy = jest.spyOn(global, 'window', 'get');
  windowSpy.mockImplementation(() => undefined);
});

it('window should be undefined.', () => {
  expect(window).toBeUndefined();
});


问:
Dynamics CRM 8.2 - Outlook 365 - Hyperlink not recognized
When clicking on "Email a link" from a Dynamics CRM form, Outlook opens with the link, but this link is not recognized as hyperlink, so not clickable.

Did you also experience this problem?

答:
You have to press Ctrl + Click the hyperlink when the Outlook email is in Draft mode.

You can change this settings if you want.

Outlook -> File -> Options -> Mail -> Editor Options -> Advanced


问:
Role based security for tabs/pages in PowerBI (not row level secuity)
Is there a way to provide role based security for different tabs/pages on PowerBi cloud desktop version. As in, if I have a PowerBI report with 27 different tabs used by 4 departments, can we restrict access to each department based on tabs that is relevant to them. like maybe department 4 is only interested in tabs/pages 2,3,6,8 while department 2 is only interested in tabs/pages 2,7,8,11,21,23 so only those tabs from reports should be visible to them.

The challenge I faced in row level security- The whole framework/skeleton of report along with non-relevant calculations is visible to each user.

答:
No, but this idea is submitted to Microsoft with a status "under review" and you may vote for it:

https://ideas.powerbi.com/forums/265200-power-bi-ideas/suggestions/16059178-page-tab-level-security


问:
Limit number of executions of a python program
Hello
I made a program in python2.6 and converted to exe with py2exe.
I wish that could limit the number of times the
user can use, then this is blocked with a counter or maybe a library.
Any ideas?</p>

答:
Either store the count in the registry or write it to a file along with the program.  Either way is easy for the end user to modify though, unless you manage to encrypt the count file.

Since it's an .exe from py2exe, there would be at least a low barrier if you used something like AES encryption with a string key stored in the executable to encrypt/decrypt it.  Enterprising users would still find their way around this by extracting the key from the executable.

Alternatively, you can have your program call out to a server you control and increment its use count in your own database.

None of these seems like a great answer to me, just providing ideas.


问:
Why JavaScript reduce method current index parameter starts from 1?
If you will launch this snipet it in your console

```<code>[0,1,2,3].reduce((acc, val, index) => {
  console.log(index);
  return acc;
});
</code>```

You will get

```<code>1
2
3
</code>```

So the question is why index starts from 1?

UPD: Probably I missing something very basic, but

```<code>[0,1,2,3].reduce((acc, val, index, initialValue) => {
  console.log(index);
  return acc;
});
</code>```

gives me

```<code>1
2
3
0
</code>```

UPD2: So yes, it's me missing something basic.

```<code>[0,1,2,3].reduce((acc, val, index) => {
  console.log(index);
  return acc;
}, 0);
</code>```

答:
Because you have not provided an initialValue argument. From the docs:

If no initialValue is supplied, the first element in the array will be used and skipped

And reading further, there's a direct answer to your question:

Note: If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

More info here

Body:
If you will launch this snipet it in your console

[0,1,2,3].reduce((acc, val, index) => {
  console.log(index);
  return acc;
});

You will get

1
2
3

So the question is why index starts from 1?

UPD: Probably I missing something very basic, but

[0,1,2,3].reduce((acc, val, index, initialValue) => {
  console.log(index);
  return acc;
});

gives me

1
2
3
0

UPD2: So yes, it's me missing something basic.

[0,1,2,3].reduce((acc, val, index) => {
  console.log(index);
  return acc;
}, 0);


问:
In YugabyteDB YSQL, how can we track the number of active connections on each server?
How can we track the active connections to a yb-tserver at a given time, and what client IP address the connection is originating from? Mostly need this for debugging purposes.</p>

答:
You can see active YSQL connections in location http://<any-tserver-ip>:13000/rpcz of any yb-tserver ip.

It will return a json response (example below):

```<code>{
    "connections": [
        {
            "db_oid": 12457,
            "db_name": "yugabyte",
            "query": "CREATE TABLE IF NOT EXISTS test_tablets_11(id bigserial primary key) SPLIT (INTO 150 TABLETS);",
            "application_name": "",
            "process_start_time": "2020-02-20 14:09:57.272725+00",
            "transaction_start_time": "2020-02-20 14:10:12.780273+00",
            "query_start_time": "2020-02-20 14:10:12.780273+00",
            "application_name": "",
            "backend_type": "client backend",
            "backend_status": "active",
            "host": "127.0.0.1",
            "port": "44434"
        },
        {
            "application_name": "",
            "process_start_time": "2020-02-20 13:39:58.133322+00",
            "application_name": "",
            "backend_type": "checkpointer",
            "backend_status": ""
        }
    ]
}
</code>```

You can view all active requests (RPCs) on each tserver in :9000/utilz:

Body:
You can see active YSQL connections in location http://<any-tserver-ip>:13000/rpcz of any yb-tserver ip.

It will return a json response (example below):

{
    "connections": [
        {
            "db_oid": 12457,
            "db_name": "yugabyte",
            "query": "CREATE TABLE IF NOT EXISTS test_tablets_11(id bigserial primary key) SPLIT (INTO 150 TABLETS);",
            "application_name": "",
            "process_start_time": "2020-02-20 14:09:57.272725+00",
            "transaction_start_time": "2020-02-20 14:10:12.780273+00",
            "query_start_time": "2020-02-20 14:10:12.780273+00",
            "application_name": "",
            "backend_type": "client backend",
            "backend_status": "active",
            "host": "127.0.0.1",
            "port": "44434"
        },
        {
            "application_name": "",
            "process_start_time": "2020-02-20 13:39:58.133322+00",
            "application_name": "",
            "backend_type": "checkpointer",
            "backend_status": ""
        }
    ]
}

You can view all active requests (RPCs) on each tserver in :9000/utilz:


问:
500 error in Laravel but log folder is empty
I am working in a Client's Laravel project which version is 5.7.28. But I am not getting anything in storage/logs/ folder. I copied the .env.example to .env. I run composer install and php artisan key:generate. Some of my .env files configuration is like below

```<code>APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:8ovbzfpWGsGTDyDIRWDO8VKObeXGyWqnMVw5KjTVJTc=
APP_DEBUG=true
APP_URL=http://127.0.0.1:8000
BASE_URL=http://127.0.0.1:8000
</code>```

I set permission 777 for all folders.

But I am getting 500 error. How can I solve the error.

答:
Run
php artisan optimize
Before production </p>

Body:
I am working in a Client's Laravel project which version is 5.7.28. But I am not getting anything in storage/logs/ folder. I copied the .env.example to .env. I run composer install and php artisan key:generate. Some of my .env files configuration is like below

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:8ovbzfpWGsGTDyDIRWDO8VKObeXGyWqnMVw5KjTVJTc=
APP_DEBUG=true
APP_URL=http://127.0.0.1:8000
BASE_URL=http://127.0.0.1:8000

I set permission 777 for all folders.

But I am getting 500 error. How can I solve the error.


问:
What is the fastest way to check for existence and get random element from data structure in python?
I need a data structure (preferably a built in python type) that allows for existence check in O(1) and also random element choosing in O(1). The elements to store in the structure are unique integers. I have considered this options:

list: O(1) random choice with random.choice, but O(n) existence with in operator.

set: O(1) existence check with in operator, but can't use random.choice without casting to tuple (O(n))

tuple: O(1) random choice with random.choice, but O(n) check for existence

dictionary: O(1) existence check , but memory use is at least 2 times as much compared to the other options (keys and values) , and random.choice does not work without casting to list or getting items (assumably O(n) operations).

Do I need to implement a compound data structure? What is the best approach?
PD: I am using Python 3 by the way.

EDIT:

The data structure is created from a list comprehension with a range generator, so the data inside the sequence is always ordered. Something like this:

```<code>data=[x for x in range(n) if condition]
</code>```

答:
Unless you have strong memory constraints, I would go with a list and a set, that you keep synchronized. You check with the set for existence but pick at random from the list.

```<code>class RandomChoice:
    def __init__(self, data):
        self.list = list(data)
        self.set = set(self.list)

    def add(self, element):
        if element not in self.set:
            self.list.append(element)
            self.set.add(element)

    def contains(self, element):
        return self.set.contains(element)

    def get_random(self):
        return random.choice(self.list)
</code>```

Of course it takes twice the storage than a single list or a single set, but it does the job.

Body:
I need a data structure (preferably a built in python type) that allows for existence check in O(1) and also random element choosing in O(1). The elements to store in the structure are unique integers. I have considered this options:

list: O(1) random choice with random.choice, but O(n) existence with in operator.

set: O(1) existence check with in operator, but can't use random.choice without casting to tuple (O(n))

tuple: O(1) random choice with random.choice, but O(n) check for existence

dictionary: O(1) existence check , but memory use is at least 2 times as much compared to the other options (keys and values) , and random.choice does not work without casting to list or getting items (assumably O(n) operations).

Do I need to implement a compound data structure? What is the best approach?
PD: I am using Python 3 by the way.

EDIT:

The data structure is created from a list comprehension with a range generator, so the data inside the sequence is always ordered. Something like this:

data=[x for x in range(n) if condition]

Body:
Unless you have strong memory constraints, I would go with a list and a set, that you keep synchronized. You check with the set for existence but pick at random from the list.

class RandomChoice:
    def __init__(self, data):
        self.list = list(data)
        self.set = set(self.list)

    def add(self, element):
        if element not in self.set:
            self.list.append(element)
            self.set.add(element)

    def contains(self, element):
        return self.set.contains(element)

    def get_random(self):
        return random.choice(self.list)

Of course it takes twice the storage than a single list or a single set, but it does the job.


问:
How to pass to the next element when the requested value is not found in a json file
I am quite a beginner on Python. I am trying to extract analytics infos from homebrew packackages APIs through Request module. To do so I first dynamically get the urls for each package and then I loop over each url to get the infos I need. The script runs well until the loop stops over the "carina" package. I suppose the stopping is due to the fact the path package_json['analytics']['install']['30d'][package_name] is no longer correct in the [package_name] part (the package name in the analytics dictionary becomes "carina --HEAD").

For this time I would like the loop just pass to the next package and print an error message.

So far I tried to solve it using the following:

```<code>    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass
</code>```

but it doesn't work.

Could anyone help me, please?

The script

```<code>r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass

    installs_30 = package_json['analytics']['install']['30d'][package_name]
    installs_90 = package_json['analytics']['install']['90d'][package_name]
    installs_365 = package_json['analytics']['install']['365d'][package_name]

    data = {
        "nome": package_name,
        "descrizione": package_desc,
        "analytics": {
            "30d": installs_30,
            "90d": installs_90,
            "365d": installs_365
        }
    }

    results.append(data)

    time.sleep(r.elapsed.total_seconds())

    if r.status_code != 200:
        print (f"Got error for {package_name}")
    else:
        print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)
</code>```

The Error message

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-42e0fb795383> in <module>
     16
     17
---> 18     installs_30 = package_json['analytics']['install']['30d'][package_name]
     19     installs_90 = package_json['analytics']['install']['90d'][package_name]
     20     installs_365 = package_json['analytics']['install']['365d'][package_name]

KeyError: 'carina'
</code>```

答:
The other answers may be incomplete. While it is true that changing exception to except will resolve one of the errors, your question specifically asks about checking the path package_json['analytics']['install']['30d'][package_name] and moving on to the next package if that raises a key error. To do that, you need your try/except call to be wrapped around those particular lines of code. Here is one example:

```<code>r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
        installs_30 = package_json['analytics']['install']['30d'][package_name]
        installs_90 = package_json['analytics']['install']['90d'][package_name]
        installs_365 = package_json['analytics']['install']['365d'][package_name]

        data = {
            "nome": package_name,
            "descrizione": package_desc,
            "analytics": {
                "30d": installs_30,
                "90d": installs_90,
                "365d": installs_365
            }
        }

        results.append(data)

        time.sleep(r.elapsed.total_seconds())

        if r.status_code != 200:
            print (f"Got error for {package_name}")
        else:
            print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')
    except:
        pass

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)
</code>```

Body:
I am quite a beginner on Python. I am trying to extract analytics infos from homebrew packackages APIs through Request module. To do so I first dynamically get the urls for each package and then I loop over each url to get the infos I need. The script runs well until the loop stops over the "carina" package. I suppose the stopping is due to the fact the path package_json['analytics']['install']['30d'][package_name] is no longer correct in the [package_name] part (the package name in the analytics dictionary becomes "carina --HEAD").

For this time I would like the loop just pass to the next package and print an error message.

So far I tried to solve it using the following:

    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass

but it doesn't work.

Could anyone help me, please?

The script

r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass

    installs_30 = package_json['analytics']['install']['30d'][package_name]
    installs_90 = package_json['analytics']['install']['90d'][package_name]
    installs_365 = package_json['analytics']['install']['365d'][package_name]

    data = {
        "nome": package_name,
        "descrizione": package_desc,
        "analytics": {
            "30d": installs_30,
            "90d": installs_90,
            "365d": installs_365
        }
    }

    results.append(data)

    time.sleep(r.elapsed.total_seconds())

    if r.status_code != 200:
        print (f"Got error for {package_name}")
    else:
        print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)

The Error message

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-42e0fb795383> in <module>
     16
     17
---> 18     installs_30 = package_json['analytics']['install']['30d'][package_name]
     19     installs_90 = package_json['analytics']['install']['90d'][package_name]
     20     installs_365 = package_json['analytics']['install']['365d'][package_name]

KeyError: 'carina'

Body:
The other answers may be incomplete. While it is true that changing exception to except will resolve one of the errors, your question specifically asks about checking the path package_json['analytics']['install']['30d'][package_name] and moving on to the next package if that raises a key error. To do that, you need your try/except call to be wrapped around those particular lines of code. Here is one example:

r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
        installs_30 = package_json['analytics']['install']['30d'][package_name]
        installs_90 = package_json['analytics']['install']['90d'][package_name]
        installs_365 = package_json['analytics']['install']['365d'][package_name]

        data = {
            "nome": package_name,
            "descrizione": package_desc,
            "analytics": {
                "30d": installs_30,
                "90d": installs_90,
                "365d": installs_365
            }
        }

        results.append(data)

        time.sleep(r.elapsed.total_seconds())

        if r.status_code != 200:
            print (f"Got error for {package_name}")
        else:
            print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')
    except:
        pass

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)