问:
How to access the page protected by basic auth using Faraday?
I have a php page I want to access and that page is protected by basic auth. I know the url and username/password, they are listed below in code:

```<code>url = 'https://henry.php' # note that it is a php website
username = 'foo'
password = 'bar'
</code>```

Faraday provide basic auth function, their doc says that I should use the following code:

```<code>connection = Faraday.new(url: url) do |conn|
  conn.basic_auth(username, password)
end
</code>```

I want to get the response body of the above url to make sure that the basic auth indeed succeed and I can access the content, but I don't know how to. I tried each of the following ways but none of them work:

```<code>connection.body
connection.response.body
connection.env.response.body

# or

r = connection.get
r.body
r.response.body
r.env.response.body

# or

r = connection.get '/'
r.body
r.response.body
r.env.response.body
</code>```

What is the proper way to get the body?

Note:

In browser, I access https://henry.php directly and browser prompt me a box asking my username and password and I enter them and I can see the content - I can see the details I have is correct and it should work (this is because browser knows how to do basic auth), but I just can't figure out how to do it in code using Faraday.

答:
The Faraday gem comes with a number of plugins (middleware) that make HTTP requests simpler and more customizable. In Ruby, basic authentication might be difficult. Let's have a look at it;

```<code>require "faraday"

request_helper = Faraday.new(url: 'example.com') do |builder|
                builder.use Faraday::Request::BasicAuthentication, client_key, secret_key
             end

# you make HTTP requests using `request_helper` since basic auth is configured

response = request_helper.get('/myendpoit')
</code>```

You must obtain tokens by proving client and secret keys when using an API such as the Stripe API. We can give client and secret keys as inputs to the Faraday::Request::BasicAuthentication middleware to establish basic authentication using the same approach as before.

Body:
I have a php page I want to access and that page is protected by basic auth. I know the url and username/password, they are listed below in code:

url = 'https://henry.php' # note that it is a php website
username = 'foo'
password = 'bar'

Faraday provide basic auth function, their doc says that I should use the following code:

connection = Faraday.new(url: url) do |conn|
  conn.basic_auth(username, password)
end

I want to get the response body of the above url to make sure that the basic auth indeed succeed and I can access the content, but I don't know how to. I tried each of the following ways but none of them work:

connection.body
connection.response.body
connection.env.response.body

# or

r = connection.get
r.body
r.response.body
r.env.response.body

# or

r = connection.get '/'
r.body
r.response.body
r.env.response.body

What is the proper way to get the body?

Note:

In browser, I access https://henry.php directly and browser prompt me a box asking my username and password and I enter them and I can see the content - I can see the details I have is correct and it should work (this is because browser knows how to do basic auth), but I just can't figure out how to do it in code using Faraday.

Body:
The Faraday gem comes with a number of plugins (middleware) that make HTTP requests simpler and more customizable. In Ruby, basic authentication might be difficult. Let's have a look at it;

require "faraday"

request_helper = Faraday.new(url: 'example.com') do |builder|
                builder.use Faraday::Request::BasicAuthentication, client_key, secret_key
             end

# you make HTTP requests using `request_helper` since basic auth is configured

response = request_helper.get('/myendpoit')

You must obtain tokens by proving client and secret keys when using an API such as the Stripe API. We can give client and secret keys as inputs to the Faraday::Request::BasicAuthentication middleware to establish basic authentication using the same approach as before.


来源: stackexchange

问:
How do I fix this error? java.lang.OutOfMemoryError (no error message)
Error while building apk.Who is getting this error.How can I fix this error?</p>
```<code> Execution failed for task ':app:packageDebug'.
    > A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
       > java.lang.OutOfMemoryError (no error message)

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
</code>```

答: you should check if there is an open packager in the background, if yes, so close it and try to run again</p>

ContentLicense: CC BY-SA 4.0

Body:
Error while building apk.Who is getting this error.How can I fix this error?

 Execution failed for task ':app:packageDebug'.
    > A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
       > java.lang.OutOfMemoryError (no error message)

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.


问:
Power Query: Expression.Error: There weren't enough elements in the enumeration to complete the operation. (LIST)
What I am trying to achieve is to obtain "matches/pairs" from two tables. One (source 1)is data table with Date/Time and Pressure value columns and the other (source 2) is like Date/Time and Info value Columns. Second table has so called "pairs" , start and stop in certain time. I want to get exact matches when is found in source 1 or approximate match when is not exact as in source 1 (seconds can be a problem).

Lets say you are matching/lookup two tables, give me everything that  falls between for instance 15.01.2022 06:00:00 and 15.01.2022 09:15:29.

Where I have a problem is more likely exact match and seconds. It is skipping or cant find any pair if the seconds are not matching. So my question is how to make if not seconds then lookup for next availablee match, can be a minute too as long as they are in the given range (start stop instances).
That is a reason I am getting this Expression error. Or is there a way to skip that error and proceed with Query??

Link to download the data:

https://docs.google.com/spreadsheets/d/1Jv5j7htAaEFktN0ntwOZCV9jesF43tEP/edit?usp=sharing&ouid=101738555398870704584&rtpof=true&sd=true

On the code below is what I am trying to do:

```<code>    let

//Be sure to change the table names in the Source= and Source2= lines to be the actual table names from your workbook
    Source = Excel.CurrentWorkbook(){[Name="Parameters"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Date/Time", type datetime}, {"P7 [mbar]", Int64.Type}}),

//get start/stop times table
    Source2 = Excel.CurrentWorkbook(){[Name="Log_Original"]}[Content],
    typeIt = Table.TransformColumnTypes(Source2, {"Date/Time", type datetime}),
    #"Filtered Rows" = Table.SelectRows(typeIt, each ([#"Date/Time"] <> null)),
    #"Added Index" = Table.AddIndexColumn(#"Filtered Rows", "Index", 0, 1),

#"Added Custom" = Table.AddColumn(#"Added Index", "NextLineStart", each if Text.Contains([Info],"start", Comparer.OrdinalIgnoreCase) = true
                and Text.Contains(#"Added Index"[Info]{[Index]+1},"start",Comparer.OrdinalIgnoreCase) = true
            then "delete"
            else null),
    #"Filtered Rows1" = Table.SelectRows(#"Added Custom", each ([NextLineStart] = null)),
    #"Removed Columns1" = Table.RemoveColumns(#"Filtered Rows1",{"Index", "NextLineStart"}),

//create a list of all the relevant start/stop times
     filterTimes = List.Combine(
                        List.Generate(
                            ()=> [times = List.DateTimes(#"Removed Columns1"[#"Date/Time"]{0},
                                                        Duration.TotalSeconds(#"Removed Columns1"[#"Date/Time"]{1}-#"Removed Columns1"[#"Date/Time"]{0})+1,
                                                        #duration(0,0,0,1)), IDX = 0],
                            each [IDX] < Table.RowCount(#"Removed Columns1"),
                            each [times = List.DateTimes(#"Removed Columns1"[#"Date/Time"]{[IDX]+2},
                                                        Duration.TotalSeconds(#"Removed Columns1"[#"Date/Time"]{[IDX]+3}-#"Removed Columns1"[#"Date/Time"]{[IDX]+2})+1,
                                                        #duration(0,0,0,1)), IDX = [IDX]+2],
                            each [times]
                                    )
                            ),

//filter the table using the list
filterTimesCol = Table.FromList(filterTimes,Splitter.SplitByNothing()),
filteredTable = Table.Join(#"Changed Type","Date/Time",filterTimesCol,"Column1",JoinKind.Inner),
    #"Removed Columns" = Table.RemoveColumns(filteredTable,{"Column1"}),
    #"Added Custom1" = Table.AddColumn(#"Removed Columns", "Custom", each DateTime.ToText([#"Date/Time"],"dd-MMM-yy")),
    #"Filtered Rows2" = Table.SelectRows(#"Added Custom1", each [#"Date/Time"] > #datetime(2019, 01, 01, 0, 0, 0)),
    #"Sorted Rows" = Table.Sort(#"Filtered Rows2",{{"Date/Time", Order.Ascending}})
in
    #"Sorted Rows"
</code>```

答:
I set up the below to return a sorted table with all results between the start and ending date/times.  You can then select the first or middle or bottom row of each table if you want from this point. Its hard to tell from your question if you are looking for the value closest to the start value, closest to the end value or something inbetween. You can wrap my Table.Sort with a Table.FirstN or Table.LastN to pick up the first or last row.

I left most of your starting code alone

```<code>let Source = Table.Buffer(T1),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Date/Time", type datetime}, {"P7 [mbar]", Int64.Type}}),
//get start/stop times table
Source2 = T2,
typeIt = Table.TransformColumnTypes(Source2, {"Date/Time", type datetime}),
#"Filtered Rows" = Table.SelectRows(typeIt, each ([#"Date/Time"] <> null)),
#"Added Index" = Table.AddIndexColumn(#"Filtered Rows", "Index", 0, 1),
// shift Info up one row for comparison
    shiftedList = List.RemoveFirstN(  #"Added Index"[Info],1),
    custom1 = Table.ToColumns(  #"Added Index") & {shiftedList},
    custom2 = Table.FromColumns(custom1,Table.ColumnNames(  #"Added Index") & {"NextInfo"}),
#"Filtered Rows2" = Table.SelectRows(custom2, each not (Text.Contains([Info],"start", Comparer.OrdinalIgnoreCase) and Text.Contains([NextInfo],"start", Comparer.OrdinalIgnoreCase))),
#"Added Custom3" = Table.AddColumn(#"Filtered Rows2", "Type", each if Text.Contains(Text.Lower([Info]),"start") then "start" else if Text.Contains(Text.Lower([Info]),"finished") then "finished" else null),
 #"Removed Columns2" = Table.RemoveColumns(#"Added Custom3",{"Info", "NextInfo"}),
#"Added Custom1" = Table.AddColumn(#"Removed Columns2", "Custom", each if [Type]="start" then [Index] else null),
#"Filled Down" = Table.FillDown(#"Added Custom1",{"Custom"}),
#"Removed Columns" = Table.RemoveColumns(#"Filled Down",{"Index"}),
#"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[Type]), "Type", "Date/Time"),
#"Added Custom2" = Table.AddColumn(#"Pivoted Column","Table",(i)=>Table.Sort(Table.SelectRows(T1, each [#"Date/Time"]>=i[start] and [#"Date/Time"]<=i[finished]),{{"Date/Time", Order.Ascending}}) , type table )
in #"Added Custom2"
</code>```

Body:
What I am trying to achieve is to obtain "matches/pairs" from two tables. One (source 1)is data table with Date/Time and Pressure value columns and the other (source 2) is like Date/Time and Info value Columns. Second table has so called "pairs" , start and stop in certain time. I want to get exact matches when is found in source 1 or approximate match when is not exact as in source 1 (seconds can be a problem).

Lets say you are matching/lookup two tables, give me everything that  falls between for instance 15.01.2022 06:00:00 and 15.01.2022 09:15:29.

Where I have a problem is more likely exact match and seconds. It is skipping or cant find any pair if the seconds are not matching. So my question is how to make if not seconds then lookup for next availablee match, can be a minute too as long as they are in the given range (start stop instances).
That is a reason I am getting this Expression error. Or is there a way to skip that error and proceed with Query??

Link to download the data:

https://docs.google.com/spreadsheets/d/1Jv5j7htAaEFktN0ntwOZCV9jesF43tEP/edit?usp=sharing&ouid=101738555398870704584&rtpof=true&sd=true

On the code below is what I am trying to do:

    let

//Be sure to change the table names in the Source= and Source2= lines to be the actual table names from your workbook
    Source = Excel.CurrentWorkbook(){[Name="Parameters"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Date/Time", type datetime}, {"P7 [mbar]", Int64.Type}}),

//get start/stop times table
    Source2 = Excel.CurrentWorkbook(){[Name="Log_Original"]}[Content],
    typeIt = Table.TransformColumnTypes(Source2, {"Date/Time", type datetime}),
    #"Filtered Rows" = Table.SelectRows(typeIt, each ([#"Date/Time"] <> null)),
    #"Added Index" = Table.AddIndexColumn(#"Filtered Rows", "Index", 0, 1),

#"Added Custom" = Table.AddColumn(#"Added Index", "NextLineStart", each if Text.Contains([Info],"start", Comparer.OrdinalIgnoreCase) = true
                and Text.Contains(#"Added Index"[Info]{[Index]+1},"start",Comparer.OrdinalIgnoreCase) = true
            then "delete"
            else null),
    #"Filtered Rows1" = Table.SelectRows(#"Added Custom", each ([NextLineStart] = null)),
    #"Removed Columns1" = Table.RemoveColumns(#"Filtered Rows1",{"Index", "NextLineStart"}),

//create a list of all the relevant start/stop times
     filterTimes = List.Combine(
                        List.Generate(
                            ()=> [times = List.DateTimes(#"Removed Columns1"[#"Date/Time"]{0},
                                                        Duration.TotalSeconds(#"Removed Columns1"[#"Date/Time"]{1}-#"Removed Columns1"[#"Date/Time"]{0})+1,
                                                        #duration(0,0,0,1)), IDX = 0],
                            each [IDX] < Table.RowCount(#"Removed Columns1"),
                            each [times = List.DateTimes(#"Removed Columns1"[#"Date/Time"]{[IDX]+2},
                                                        Duration.TotalSeconds(#"Removed Columns1"[#"Date/Time"]{[IDX]+3}-#"Removed Columns1"[#"Date/Time"]{[IDX]+2})+1,
                                                        #duration(0,0,0,1)), IDX = [IDX]+2],
                            each [times]
                                    )
                            ),

//filter the table using the list
filterTimesCol = Table.FromList(filterTimes,Splitter.SplitByNothing()),
filteredTable = Table.Join(#"Changed Type","Date/Time",filterTimesCol,"Column1",JoinKind.Inner),
    #"Removed Columns" = Table.RemoveColumns(filteredTable,{"Column1"}),
    #"Added Custom1" = Table.AddColumn(#"Removed Columns", "Custom", each DateTime.ToText([#"Date/Time"],"dd-MMM-yy")),
    #"Filtered Rows2" = Table.SelectRows(#"Added Custom1", each [#"Date/Time"] > #datetime(2019, 01, 01, 0, 0, 0)),
    #"Sorted Rows" = Table.Sort(#"Filtered Rows2",{{"Date/Time", Order.Ascending}})
in
    #"Sorted Rows"

Body:
I set up the below to return a sorted table with all results between the start and ending date/times.  You can then select the first or middle or bottom row of each table if you want from this point. Its hard to tell from your question if you are looking for the value closest to the start value, closest to the end value or something inbetween. You can wrap my Table.Sort with a Table.FirstN or Table.LastN to pick up the first or last row.

I left most of your starting code alone

let Source = Table.Buffer(T1),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Date/Time", type datetime}, {"P7 [mbar]", Int64.Type}}),
//get start/stop times table
Source2 = T2,
typeIt = Table.TransformColumnTypes(Source2, {"Date/Time", type datetime}),
#"Filtered Rows" = Table.SelectRows(typeIt, each ([#"Date/Time"] <> null)),
#"Added Index" = Table.AddIndexColumn(#"Filtered Rows", "Index", 0, 1),
// shift Info up one row for comparison
    shiftedList = List.RemoveFirstN(  #"Added Index"[Info],1),
    custom1 = Table.ToColumns(  #"Added Index") & {shiftedList},
    custom2 = Table.FromColumns(custom1,Table.ColumnNames(  #"Added Index") & {"NextInfo"}),
#"Filtered Rows2" = Table.SelectRows(custom2, each not (Text.Contains([Info],"start", Comparer.OrdinalIgnoreCase) and Text.Contains([NextInfo],"start", Comparer.OrdinalIgnoreCase))),
#"Added Custom3" = Table.AddColumn(#"Filtered Rows2", "Type", each if Text.Contains(Text.Lower([Info]),"start") then "start" else if Text.Contains(Text.Lower([Info]),"finished") then "finished" else null),
 #"Removed Columns2" = Table.RemoveColumns(#"Added Custom3",{"Info", "NextInfo"}),
#"Added Custom1" = Table.AddColumn(#"Removed Columns2", "Custom", each if [Type]="start" then [Index] else null),
#"Filled Down" = Table.FillDown(#"Added Custom1",{"Custom"}),
#"Removed Columns" = Table.RemoveColumns(#"Filled Down",{"Index"}),
#"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[Type]), "Type", "Date/Time"),
#"Added Custom2" = Table.AddColumn(#"Pivoted Column","Table",(i)=>Table.Sort(Table.SelectRows(T1, each [#"Date/Time"]>=i[start] and [#"Date/Time"]<=i[finished]),{{"Date/Time", Order.Ascending}}) , type table )
in #"Added Custom2"


问:
Represent a single-rowed table in EF?
I have a configuration table in my database and it contains exactly one row.

```<code>ConfirmedScheduleColor | OverlappedScheduleColor | ColN
</code>```

Currently, I'm retrieving the configuration like this:

```<code>var db = new SchedulingDbContext();
var config = db.Configurations.FirstOrDefault();
</code>```

It's currently working fine and I can access my configurations and all. The thing is, the code looks awkward since I'm accessing the Configurations DbSet as if it contains many records (FirstOrDefault()); although actually, it contains only one record. I want to access my configurations like I'm accessing a static object. How to do that in EF?

答:
In EF Core you can set the check constraint for the primary key. It enforces that column Id must have value that is equal to 1 which means only one record can exist in table if you have the primary key.</p>
```<code>modelBuilder.Entity<YourTable>(e =>
{
   e.HasCheckConstraint("CK_Table_Column", "[Id] = 1");

   e.HasData(...) //optionally add some initial date for Id = 1
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Represent a single-rowed table in EF?

Body:
I have a configuration table in my database and it contains exactly one row.

ConfirmedScheduleColor | OverlappedScheduleColor | ColN

Currently, I'm retrieving the configuration like this:

var db = new SchedulingDbContext();
var config = db.Configurations.FirstOrDefault();

It's currently working fine and I can access my configurations and all. The thing is, the code looks awkward since I'm accessing the Configurations DbSet as if it contains many records (FirstOrDefault()); although actually, it contains only one record. I want to access my configurations like I'm accessing a static object. How to do that in EF?

Body:
In EF Core you can set the check constraint for the primary key. It enforces that column Id must have value that is equal to 1 which means only one record can exist in table if you have the primary key.

modelBuilder.Entity<YourTable>(e =>
{
   e.HasCheckConstraint("CK_Table_Column", "[Id] = 1");

   e.HasData(...) //optionally add some initial date for Id = 1
});


问:
Having Issue on Configuring Windows Server 2016 Active Directory
Logged in to windows Server 2016 as an administrator, I have enable Active Directory Domain Services on Windows Server 2016 by adding role. The Active Directory Users and Computers is listing under Control Panel | Administrative Tools as shown in following image but when I click on that, I am getting following message

To manage users and groups on this computers use Local Users and Groups.
To manage users, groups and computers in a domain, log on as a user with domain administration right.

Can you please let me know why this is happening and how I can fix this?

答:
•   You are encountering this error because ‘Active Directory Domain Services’ role surely has been installed on the Windows Server 2016 server, but it has not been yet promoted to ‘Domain Controller’. By promoting the server to DC and initializing its authority over the DNS zones hosted on this Server or any other server on which DNS role is installed, you would grant the user ID which you configure while promoting to DC as the default Domain and Schema Administrator. And then by logging in with this ID, you will be able to access the various service management consoles of Active Directory.

Thus, kindly promote the Server to the level of Domain Controller in your environment and then try logging in to the Server with that ID. You should be able to access the features of Active Directory. For promoting the Server to DC, please refer to the documentation link below: -

https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/deploy/install-active-directory-domain-services--level-100-#BKMK_GUI


问:
'const' scope in for loop JavaScript
In the code below, is ele available only for an individual iteration of the loop?

```<code>for (var i=0; i<3; i++){
  const ele = i
  console.log(ele)
}
</code>```

I'm thinking this should be the case, otherwise there will be a

```<code>Syntax Error: Identifier 'ele' has already been declared
</code>```

every time the loop iterates after the very first time.

I could not find a way to confirm this using console.log(), so looking for a concrete answer.

EDIT: To clarify, I understand that ele is valid within the for loop only. My question is specifically if the scope is ' reinstantiated' every iteration of this loop or not. It definitely looks like it, but I haven't heard or read that explicitly anywhere yet.

答:
why do not directly use console.log(i) ?

howei think you should try to use var or let instead of const

Title: 'const' scope in for loop JavaScript

Body:
In the code below, is ele available only for an individual iteration of the loop?

for (var i=0; i<3; i++){
  const ele = i
  console.log(ele)
}

I'm thinking this should be the case, otherwise there will be a

Syntax Error: Identifier 'ele' has already been declared

every time the loop iterates after the very first time.

I could not find a way to confirm this using console.log(), so looking for a concrete answer.

EDIT: To clarify, I understand that ele is valid within the for loop only. My question is specifically if the scope is ' reinstantiated' every iteration of this loop or not. It definitely looks like it, but I haven't heard or read that explicitly anywhere yet.


问:
Objects are not valid as a React child React Native
I'm getting Render Error
Objects are not valid as a React child (found:object with keys {name, lati, long}). If you meant to render a collection of children, use an array instead.

I need to send the prop "name" from const mesta using Tab.Screen children, but keep getting the error.

My code:

MainContainer.js

```<code>import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {name: 'Praha', lati: '', long: ''},
  {name: 'České Budějovice', lati: '', long: ''},
  {name: 'Plzeň', lati: '', long: ''},
  {name: 'Karlovy Vary', lati: '', long: ''},
  {name: 'Ústí nad Labem', lati: '', long: ''},
  {name: 'Liberec', lati: '', long: ''},
  {name: 'Hradec Králové', lati: '', long: ''},
  {name: 'Pardubice', lati: '', long: ''},
  {name: 'Jihlava', lati: '', long: ''},
  {name: 'Brno', lati: '', long: ''},
  {name: 'Olomouc', lati: '', long: ''},
  {name: 'Ostrava', lati: '', long: ''},
  {name: 'Zlín', lati: '', long: ''},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary mesta={mesta}/>}/>
        {/* <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/> */}

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;
</code>```

Primary.js

```<code>import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';

var nazvy = ['Praha','České Budějovice','Plzeň','Karlovy Vary','Ústí nad Labem','Liberec','Hradec Králové','Pardubice','Jihlava','Brno','Olomouc','Ostrava','Zlín',]

export default function Primary(props)
{
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.mesta.map(itemz => (
                    <Text
                    style={styles.card2}
                    //onPress={() => navigation.navigate('Mapa')}
                    >
                        {itemz}
                    </Text>
                ))}
                    {nazvy.map(item => (
                        <Text
                        style={styles.card}
                        //onPress={() => navigation.navigate('Mapa')}
                        >
                            {item}
                        </Text>
                    ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });
</code>```

答:
You can show complete object as string in Text view like

```<code><View>
  {props.mesta.map((itemz) => (
    <Text
      style={styles.card2}
      //onPress={() => navigation.navigate('Mapa')}
    >
      {JSON.stringify(itemz)} // here it is
    </Text>
  ))}
</View>
</code>```

Body:
I'm getting Render Error
Objects are not valid as a React child (found:object with keys {name, lati, long}). If you meant to render a collection of children, use an array instead.

I need to send the prop "name" from const mesta using Tab.Screen children, but keep getting the error.

My code:

MainContainer.js

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {name: 'Praha', lati: '', long: ''},
  {name: 'České Budějovice', lati: '', long: ''},
  {name: 'Plzeň', lati: '', long: ''},
  {name: 'Karlovy Vary', lati: '', long: ''},
  {name: 'Ústí nad Labem', lati: '', long: ''},
  {name: 'Liberec', lati: '', long: ''},
  {name: 'Hradec Králové', lati: '', long: ''},
  {name: 'Pardubice', lati: '', long: ''},
  {name: 'Jihlava', lati: '', long: ''},
  {name: 'Brno', lati: '', long: ''},
  {name: 'Olomouc', lati: '', long: ''},
  {name: 'Ostrava', lati: '', long: ''},
  {name: 'Zlín', lati: '', long: ''},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary mesta={mesta}/>}/>
        {/* <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/> */}

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;

Primary.js

import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';

var nazvy = ['Praha','České Budějovice','Plzeň','Karlovy Vary','Ústí nad Labem','Liberec','Hradec Králové','Pardubice','Jihlava','Brno','Olomouc','Ostrava','Zlín',]

export default function Primary(props)
{
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.mesta.map(itemz => (
                    <Text
                    style={styles.card2}
                    //onPress={() => navigation.navigate('Mapa')}
                    >
                        {itemz}
                    </Text>
                ))}
                    {nazvy.map(item => (
                        <Text
                        style={styles.card}
                        //onPress={() => navigation.navigate('Mapa')}
                        >
                            {item}
                        </Text>
                    ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });

Body:
You can show complete object as string in Text view like

<View>
  {props.mesta.map((itemz) => (
    <Text
      style={styles.card2}
      //onPress={() => navigation.navigate('Mapa')}
    >
      {JSON.stringify(itemz)} // here it is
    </Text>
  ))}
</View>


问:
Bug: A return won't stop execution when a reject is received and handled
Steps to reproduce:

Step 1. VSC, F1 to create an auto-gen Azure Function (AF).

Step 2. index.js, replace it with below following MS AF Js developer guide

```<code>module.exports = async function (context)
{
    const good = await db.pgTest({})  // this call will receive a Promise.reject, see below
        .catch
        (
            ce =>
            {
                context.res = {status: 401, body: ce};
                return;   // execution supposed end, but it goes on
            }
        );
    var x = good[0]["column1"];
    // execution continues to above line even .catch() has a return
    // 'good' will have an array when db.pgTest() succeeds, now is 'undefined'
    // but strangely terminal doesn't print out exception like:
    // Exception: TypeError: Cannot read property '0' of undefined, Stack: TypeError: Cannot read property '0' of undefined

}

</code>```

Step 3. create db.pgTest(), a standard Promise. Can be any db calls I'm using pg-promise:

```<code>const pgTest = (param) =>
{
    return new Promise((resolve, reject) =>
    {
        var sql = 'select * from schema.nonexits()';  // simply call a non-exists function to raise a runtime error
        db.any(sql)
        .then
        (
            good => resolve(good),
            bad =>
            {
                reject({status: 401, bad: bad});
            }
        )
        .catch
        (
            ce =>
            {
                reject({status: 402, bad: ce});   // because .then(..., bad=>...) this block is never reached.
            }
        )
    }
    );
}

</code>```

Environment:

```<code>Version: 1.63.1 (system setup)
Commit: fe719cd3e5825bf14e14182fddeb88ee8daf044f
Date: 2021-12-14T02:13:54.292Z
Electron: 13.5.2
Chromium: 91.0.4472.164
Node.js: 14.16.0
V8: 9.1.269.39-electron.0
OS: Windows_NT x64 10.0.19044
Azure Functions Extension: v1.6.0
</code>```

Step 4. F5 and hit the URL.

Update
My question of return is about index.js, block ce => { ... return; }. I overlooked this block indeed is a function.

答:
Here we put the call back request of PgTest() Function inside a Promise wrapper Promise( (resolve, reject) => { //callback function}). This wrapper allows you to call the pgTest function like a promise with .catch() methods. When the pgTest is called, it executes the request to the API and waits for either a resolve() or a reject() statement to execute. In the callback function, you simply pass the retrieved data into the resolve or reject methods. check here

The .catch is a wrapper function of a promise and can be used to catch any exception that happens within the .then/inside the block.

So, the return will be performed, and it will went out of the wrapper function. because the .catch wrapper function can handle every exception in the .Catch block

Updated:

Refer here for more information

Body:
Steps to reproduce:

Step 1. VSC, F1 to create an auto-gen Azure Function (AF).

Step 2. index.js, replace it with below following MS AF Js developer guide

module.exports = async function (context)
{
    const good = await db.pgTest({})  // this call will receive a Promise.reject, see below
        .catch
        (
            ce =>
            {
                context.res = {status: 401, body: ce};
                return;   // execution supposed end, but it goes on
            }
        );
    var x = good[0]["column1"];
    // execution continues to above line even .catch() has a return
    // 'good' will have an array when db.pgTest() succeeds, now is 'undefined'
    // but strangely terminal doesn't print out exception like:
    // Exception: TypeError: Cannot read property '0' of undefined, Stack: TypeError: Cannot read property '0' of undefined

}

Step 3. create db.pgTest(), a standard Promise. Can be any db calls I'm using pg-promise:

const pgTest = (param) =>
{
    return new Promise((resolve, reject) =>
    {
        var sql = 'select * from schema.nonexits()';  // simply call a non-exists function to raise a runtime error
        db.any(sql)
        .then
        (
            good => resolve(good),
            bad =>
            {
                reject({status: 401, bad: bad});
            }
        )
        .catch
        (
            ce =>
            {
                reject({status: 402, bad: ce});   // because .then(..., bad=>...) this block is never reached.
            }
        )
    }
    );
}

Environment:

Version: 1.63.1 (system setup)
Commit: fe719cd3e5825bf14e14182fddeb88ee8daf044f
Date: 2021-12-14T02:13:54.292Z
Electron: 13.5.2
Chromium: 91.0.4472.164
Node.js: 14.16.0
V8: 9.1.269.39-electron.0
OS: Windows_NT x64 10.0.19044
Azure Functions Extension: v1.6.0

Step 4. F5 and hit the URL.

Update
My question of return is about index.js, block ce => { ... return; }. I overlooked this block indeed is a function.


问:
Counting certain rows in PowerBI
I never used PowerBI and this is a trivial problem in pandas, but I don`t know how this works here.

I have an Excel that contains a lot of columns, some of which problematic because it throws me an error when I am trying to load it in PowerBI. The columns that interest me are just (out of 20 columns):

```<code>Object                Status
444444441             X
444444442
444444443             X
444444444             X
444444445
</code>```

I just want to count the Objects whose Status is marked, and display them in a diagram. Do I need to convert the values of Status into 0 and 1s, so bool instead of text, and then count them? I tried to convert it automatically and it doesnt work.

答:
Not fully sure about the solution you strive for, but here, two primitive ones:

Calculate a measure that gives you the number of objects with status "X":

Count1 = COUNTAX(FILTER(data, data[Status]="X"), data[Object])

which would give you e.g.

Add the plot, mark it and chose "Status is X" in the filter menue:

which gives you the following:

where Count2 = count(data[Object])

Hope that does help!

Title: Counting certain rows in PowerBI

Body:
I never used PowerBI and this is a trivial problem in pandas, but I don`t know how this works here.

I have an Excel that contains a lot of columns, some of which problematic because it throws me an error when I am trying to load it in PowerBI. The columns that interest me are just (out of 20 columns):

Object                Status
444444441             X
444444442
444444443             X
444444444             X
444444445

I just want to count the Objects whose Status is marked, and display them in a diagram. Do I need to convert the values of Status into 0 and 1s, so bool instead of text, and then count them? I tried to convert it automatically and it doesnt work.


问:
TestNG's @Test annotation not executed properly with the mvn command
Everything with the @Test annotation throws null pointer exception, regardless of the method called. I tried calling driver.findElement() and executing js script with JavascriptExecutor. Both methods ended up with a null pointer.
If I run through the IDE everything works like a charm. Otherwise, only the Before and After annotations are executed adequately
Here's my pom.xml:

```<code>   <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">

<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <parallel>methods</parallel>
                <threadCount>1</threadCount>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.1.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.testng/testng -->
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.5</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.10</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache-extras.beanshell</groupId>
        <artifactId>bsh</artifactId>
        <version>2.0b6</version>
    </dependency>
</dependencies>

<properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

 </project>
</code>```

and testng.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Practice Suite">
<test name="Test Basics 1">

    <method-selectors>
        <method-selector>
            <script language="beanshell">
                <![CDATA[
                String testGroup = System.getProperty("env");
                groups.containsKey(testGroup);
            ]]>
            </script>
        </method-selector>
    </method-selectors>

    <classes>
        <class name="tests.SignUpTest"/>
    </classes>
</test>

 </suite>
</code>```

and finally the two manners I am using to run the test:

mvn -Dwebdriver=chrome -Denv=qa install

mvn -Dwebdriver=chrome -Denv=qa test

EDIT:

BeforeTest and Test:

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

public class BaseTest {

protected  WebDriver driver;

private WebDriver selectDriver(String driver)

    switch (driverString) {
        case "chrome":
            return new ChromeDriver();
        case "firefox":
            return new FirefoxDriver();
        case "edge":
            return new EdgeDriver();
        case "safari":
            return new SafariDriver();
        default:
            return new ChromeDriver();
    }

}

     @BeforeTest(alwaysRun = true)
    public void testInit() {

        driver = selectDriver(System.getProperty("webdriver"));

    }

}

import additions.BaseTest;
import org.testng.Assert;
import org.testng.annotations.Test;
import pages.DashBoardPage;
import pages.LoginPage;

public class LoginTest extends BaseTest {

@Test
public void successfulLogin(){
    LoginPage loginPage = new LoginPage(driver);

    loginPage
            .populateUserName("somename")
            .populatePassword("somepassowrd")
            .clickLoginButton();

}
</code>```

}

答:
I've solved it. It turns out that initialising the driver with the @BeforeTest annotation is not a good idea, especially if your teardown method is marked with @AfterTest. The driver is initialised and used correctly in the first @Test method, but on the second one, the teardown method is already called and the driver becomes null. So I used @BeforeClass and @AfterClass (I might reconsider and use @Before/AfterSuite). Then I added the following configuration to the  pom.xml

```<code>    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>

                <suiteXmlFiles>
                    <suiteXmlFile>testng.xml</suiteXmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

Then I added the package with the tests I wanted to execute, in the testng.xml file, like this:

```<code>        <packages>
        <package name="path.to.tests.*"></package>
    </packages>
</code>```

Finally I called the mvn command using the following syntax:

```<code>mvn test -Dsurefire.suiteXmlFiles=testng.xml  -Dwebdriver="chrome" -Denv="qa"
</code>```

This way you don't have to call the path to the testng.xml file, but rather call it out of the pom.xml. As a side note to the last sentence, my testng.xml file is located in the project directory, along with the src folder. If you put it in another folder, I guess it will be good to set the path to this folder in the pom.xml

I hope this is understandable and it will be helpful for anyone who gets stuck with such issue.

Thank again to the others for the clues.

Body:
Everything with the @Test annotation throws null pointer exception, regardless of the method called. I tried calling driver.findElement() and executing js script with JavascriptExecutor. Both methods ended up with a null pointer.
If I run through the IDE everything works like a charm. Otherwise, only the Before and After annotations are executed adequately
Here's my pom.xml:

   <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">

<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <parallel>methods</parallel>
                <threadCount>1</threadCount>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.1.1</version>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.5</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.10</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache-extras.beanshell</groupId>
        <artifactId>bsh</artifactId>
        <version>2.0b6</version>
    </dependency>
</dependencies>

<properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

 </project>

and testng.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Practice Suite">
<test name="Test Basics 1">

    <method-selectors>
        <method-selector>

        </method-selector>
    </method-selectors>

    <classes>
        <class name="tests.SignUpTest"/>
    </classes>
</test>

 </suite>

and finally the two manners I am using to run the test:

mvn -Dwebdriver=chrome -Denv=qa install

mvn -Dwebdriver=chrome -Denv=qa test

EDIT:

BeforeTest and Test:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

public class BaseTest {

protected  WebDriver driver;

private WebDriver selectDriver(String driver)

    switch (driverString) {
        case "chrome":
            return new ChromeDriver();
        case "firefox":
            return new FirefoxDriver();
        case "edge":
            return new EdgeDriver();
        case "safari":
            return new SafariDriver();
        default:
            return new ChromeDriver();
    }

}

     @BeforeTest(alwaysRun = true)
    public void testInit() {

        driver = selectDriver(System.getProperty("webdriver"));

    }

}

import additions.BaseTest;
import org.testng.Assert;
import org.testng.annotations.Test;
import pages.DashBoardPage;
import pages.LoginPage;

public class LoginTest extends BaseTest {

@Test
public void successfulLogin(){
    LoginPage loginPage = new LoginPage(driver);

    loginPage
            .populateUserName("somename")
            .populatePassword("somepassowrd")
            .clickLoginButton();

}

}

Body:
I've solved it. It turns out that initialising the driver with the @BeforeTest annotation is not a good idea, especially if your teardown method is marked with @AfterTest. The driver is initialised and used correctly in the first @Test method, but on the second one, the teardown method is already called and the driver becomes null. So I used @BeforeClass and @AfterClass (I might reconsider and use @Before/AfterSuite). Then I added the following configuration to the  pom.xml

    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>

                <suiteXmlFiles>
                    <suiteXmlFile>testng.xml</suiteXmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
    </plugins>
</build>

Then I added the package with the tests I wanted to execute, in the testng.xml file, like this:

        <packages>
        <package name="path.to.tests.*"></package>
    </packages>

Finally I called the mvn command using the following syntax:

mvn test -Dsurefire.suiteXmlFiles=testng.xml  -Dwebdriver="chrome" -Denv="qa"

This way you don't have to call the path to the testng.xml file, but rather call it out of the pom.xml. As a side note to the last sentence, my testng.xml file is located in the project directory, along with the src folder. If you put it in another folder, I guess it will be good to set the path to this folder in the pom.xml

I hope this is understandable and it will be helpful for anyone who gets stuck with such issue.

Thank again to the others for the clues.


问:
Find Element By 2 Tag in a Div
I want to find  value but value is always changing. And name="customerNum" is unique. So I want to use that 2 tag. But when I try, I got error. What is the way to use this 2 tag with "and" maybe.</p>
```<code><div class="gtstep-input-inner">
  <input name="customerNum" type="text">
  <input type="hidden" value="638367795">
</div>
</code>```

答:
```<code>x = driver.find_element(By.XPATH, "//input[@type='hidden']").get_attribute('value')
print(x)
</code>```

Output:

```<code>638367795

Process finished with exit code 0
</code>```

As you said the value changes, it will fetch the value at that point in time (when the line is executed)

If you just want to get that element and not the value in it, then use this:

```<code>driver.find_element(By.XPATH, "//input[@type='hidden']")
</code>```

As per your html in your query, this works to get the input element that has value attribute, i.e., the second input element

Title: Find Element By 2 Tag in a Div

Body:
I want to find  value but value is always changing. And name="customerNum" is unique. So I want to use that 2 tag. But when I try, I got error. What is the way to use this 2 tag with "and" maybe.

  <input name="customerNum" type="text">
  <input type="hidden" value="638367795">

Body:
x = driver.find_element(By.XPATH, "//input[@type='hidden']").get_attribute('value')
print(x)

Output:

638367795

Process finished with exit code 0

As you said the value changes, it will fetch the value at that point in time (when the line is executed)

If you just want to get that element and not the value in it, then use this:

driver.find_element(By.XPATH, "//input[@type='hidden']")

As per your html in your query, this works to get the input element that has value attribute, i.e., the second input element


问:
Is there a better way to summarize a time series by category start and end times in T-SQL?
I would like to summarize a time series of data by:

Category - (1. Low, 2. Moderate, 3. Strong, 4. Extreme).

The start and end times of the run of each Category.

The image below shows a snippet of the data and the desired output.

Since the Categories (1. Low, 2. Moderate, 3. Strong, 4. Extreme) repeat throughout the timeline, an approach such as the SELECT below will summarize the MIN and MAX ReadingDateTime values over the entire table in four rows.

The minimum and maximum ReadingDateTime over all readings in the Low category.

The minimum and maximum ReadingDateTime over all readings in the Moderate category.

The minimum and maximum ReadingDateTime over all readings in the Strong category.

The minimum and maximum ReadingDateTime over all readings in the Extreme category.

```<code>    SELECT..
             MIN(ReadingDateTime)
            ,MAX(ReadingDateTime)
    FROM CurrentLogger
    GROUP BY LoggerId
            ,Category
    ORDER BY LoggerId
            ,ReadingDateTime
</code>```

For example:

I have one approach, but I am sure there is a much better way.  I mark the start and end of runs of Categories by using the SQL LAG and LEAD functions.

```<code>SELECT LoggerId
      ,Location
      ,Category
      ,dBDateTime
      ,FirstInRun = IIF(LAG(dBCategory,1,0) OVER(ORDER BY InstrumentId, dBDateTime)<>dBCategory,1,0)
      ,LastInRun = IIF(LEAD(dBCategory,1,0) OVER(ORDER BY InstrumentId, dBDateTime)<>dBCategory,1,0)
FROM CurrentLogger
ORDER BY InstrumentId
        ,dBDateTime
</code>```

The output is below:

There are several ugly and slow ways to roll this up to the desired output.

My question is:

Before rolling this up to the desired output, is there a far more obvious way to get the start and end times for each of the consecutive categorical runs?

答:
One way to roll it up is to use the ROW_NUMBER() function to create your groups and then get the MIN/MAX dates for each group.  Consider the following:</p>
```<code>CREATE TABLE #CurrentLogger(LoggerID int, Location varchar(20),Category varchar(20),ReadingDateTime datetime)
INSERT INTO #CurrentLogger VALUES
(10,'OutSide','1. Low','9/14/21 8:16:37 AM'),
(10,'OutSide','1. Low','9/14/21 8:16:39 AM'),
(10,'OutSide','1. Low','9/14/21 8:16:41 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:43 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:45 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:47 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:49 AM'),
(10,'OutSide','4. Extreme','9/14/21 8:16:51 AM'),
(10,'OutSide','3. Strong','9/14/21 8:16:53 AM'),
(10,'OutSide','3. Strong','9/14/21 8:16:55 AM'),
(10,'OutSide','3. Strong','9/14/21 8:16:57 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:59 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:17:01 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:17:03 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:17:05 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:07 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:09 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:11 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:13 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:15 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:17 AM');

WITH CTE AS
(
    SELECT *,
        ROW_NUMBER() OVER(PARTITION BY LoggerID ORDER BY ReadingDateTime)
        - ROW_NUMBER() OVER(PARTITION BY LoggerID,Location,Category ORDER BY ReadingDateTime) Grp
    FROM #CurrentLogger
)
SELECT LoggerID,Location,Category, MIN(ReadingDateTime) StartDate, MAX(ReadingDateTime) EndDate
FROM CTE
GROUP BY Grp,LoggerID,Location,Category
ORDER BY StartDate
</code>```

Body:
I would like to summarize a time series of data by:

Category - (1. Low, 2. Moderate, 3. Strong, 4. Extreme).

The start and end times of the run of each Category.

The image below shows a snippet of the data and the desired output.

Since the Categories (1. Low, 2. Moderate, 3. Strong, 4. Extreme) repeat throughout the timeline, an approach such as the SELECT below will summarize the MIN and MAX ReadingDateTime values over the entire table in four rows.

The minimum and maximum ReadingDateTime over all readings in the Low category.

The minimum and maximum ReadingDateTime over all readings in the Moderate category.

The minimum and maximum ReadingDateTime over all readings in the Strong category.

The minimum and maximum ReadingDateTime over all readings in the Extreme category.

    SELECT..
             MIN(ReadingDateTime)
            ,MAX(ReadingDateTime)
    FROM CurrentLogger
    GROUP BY LoggerId
            ,Category
    ORDER BY LoggerId
            ,ReadingDateTime

For example:

I have one approach, but I am sure there is a much better way.  I mark the start and end of runs of Categories by using the SQL LAG and LEAD functions.

SELECT LoggerId
      ,Location
      ,Category
      ,dBDateTime
      ,FirstInRun = IIF(LAG(dBCategory,1,0) OVER(ORDER BY InstrumentId, dBDateTime)<>dBCategory,1,0)
      ,LastInRun = IIF(LEAD(dBCategory,1,0) OVER(ORDER BY InstrumentId, dBDateTime)<>dBCategory,1,0)
FROM CurrentLogger
ORDER BY InstrumentId
        ,dBDateTime

The output is below:

There are several ugly and slow ways to roll this up to the desired output.

My question is:

Before rolling this up to the desired output, is there a far more obvious way to get the start and end times for each of the consecutive categorical runs?

Body:
One way to roll it up is to use the ROW_NUMBER() function to create your groups and then get the MIN/MAX dates for each group.  Consider the following:

CREATE TABLE #CurrentLogger(LoggerID int, Location varchar(20),Category varchar(20),ReadingDateTime datetime)
INSERT INTO #CurrentLogger VALUES
(10,'OutSide','1. Low','9/14/21 8:16:37 AM'),
(10,'OutSide','1. Low','9/14/21 8:16:39 AM'),
(10,'OutSide','1. Low','9/14/21 8:16:41 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:43 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:45 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:47 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:49 AM'),
(10,'OutSide','4. Extreme','9/14/21 8:16:51 AM'),
(10,'OutSide','3. Strong','9/14/21 8:16:53 AM'),
(10,'OutSide','3. Strong','9/14/21 8:16:55 AM'),
(10,'OutSide','3. Strong','9/14/21 8:16:57 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:16:59 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:17:01 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:17:03 AM'),
(10,'OutSide','2. Moderate','9/14/21 8:17:05 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:07 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:09 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:11 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:13 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:15 AM'),
(10,'OutSide','1. Low','9/14/21 8:17:17 AM');

WITH CTE AS
(
    SELECT *,
        ROW_NUMBER() OVER(PARTITION BY LoggerID ORDER BY ReadingDateTime)
        - ROW_NUMBER() OVER(PARTITION BY LoggerID,Location,Category ORDER BY ReadingDateTime) Grp
    FROM #CurrentLogger
)
SELECT LoggerID,Location,Category, MIN(ReadingDateTime) StartDate, MAX(ReadingDateTime) EndDate
FROM CTE
GROUP BY Grp,LoggerID,Location,Category
ORDER BY StartDate


问:
Python os.pathislink, exists and isdir dont work
```<code>amd_path = '/sys/class/backlight/amdgpu_b10/'
amd_gpu = os.path.islink(amd_path)

</code>```

On this path, the script always shows false whether it uses exist, islink, isdir shows false, can anyone help?
Unfortunately, my research did not help me.

答:
Maybe it actually does not exist ?

>>> os.path.exists("/does-not-exist")
False
>>> os.path.islink("/does-not-exist")
False
>>> os.path.isdir("/does-not-exist")
False
```

Body:
amd_path = '/sys/class/backlight/amdgpu_b10/'
amd_gpu = os.path.islink(amd_path)

On this path, the script always shows false whether it uses exist, islink, isdir shows false, can anyone help?
Unfortunately, my research did not help me.


问:
ASP.NET Core - Azure Active directory Authentication - Unable to obtain configuration from: 'System.String'
I have a .NET Core 2.2 / Angular 10 app where I want to implement an Azure AD login. The app already has a simple user/password login using JWT:

```<code> services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer("Default",options=>
....
  options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["SecurityKeyIssuer"],
                ValidAudience = Configuration["SecurityKeyAudience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]))
            };
</code>```

Now I tried adding this:

```<code> .AddJwtBearer("AzureAD",opt =>
        {
            opt.IncludeErrorDetails = true;
            opt.Authority = Configuration["ActiveDirectory:Authority"];
            opt.Audience = Configuration["ActiveDirectory:Audience"];
...

services
        .AddAuthorization(options =>
        {
            options.DefaultPolicy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .AddAuthenticationSchemes("Default", "AzureAD")
                .Build();
        });
</code>```

I tried several variations of this, like hardcoding the authority etc. in different formats. I get to the login page where I'm able to log in using the default user/password authentication, but after that every page only shows me this 500 error:

Even after I commented out all the new configs. When I remove the AzureAD authentication scheme, it works normally again.
Any suggestions?

Of course I registered the app and used the info from the Azure AD page.

Also, when trying this:

```<code>services.AddAuthentication("MyAuthenticationScheme")
      .AddMicrosoftIdentityWebApp();
</code>```

It says:

Severity  Code    Description Project File    Line    Suppression State
Error   CS1061  'AuthenticationBuilder' does not contain a definition for 'AddMicrosoftIdentityWebApp' and no accessible extension method 'AddMicrosoftIdentityWebApp' accepting a first argument of type 'AuthenticationBuilder' could be found (are you missing a using directive or an assembly reference?)  JI.Infopool.WebApp  C:\Projekte\JI.Infopool - master\JI.Infopool.WebApp\Startup.cs  56  Active

Although I've included the NuGet Package Microsoft.Identity.Web

答:
1.Initially please check if the login request to microsoft was locked by the firewall.

2.Make sure  appsettings.json values are correct.

```<code>"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "<azure ad domain>",
  "TenantId": "<azure ad tenant id>",
  "ClientId": "<backend app id>"
}
</code>```

In Startup.cs

Check the following  code in ConfigureServices()

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        //services.AddControllersWithViews();
///
//
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
        services.AddAuthorization();

        ...
    }
</code>```

In configure() method make sure you have these

```<code>        app.UseAuthentication();
        app.UseAuthorization();
</code>```

Reference: using openidconnect-with-azure-ad-angular and core webapiconfiguration

Body:
I have a .NET Core 2.2 / Angular 10 app where I want to implement an Azure AD login. The app already has a simple user/password login using JWT:

 services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer("Default",options=>
....
  options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["SecurityKeyIssuer"],
                ValidAudience = Configuration["SecurityKeyAudience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]))
            };

Now I tried adding this:

 .AddJwtBearer("AzureAD",opt =>
        {
            opt.IncludeErrorDetails = true;
            opt.Authority = Configuration["ActiveDirectory:Authority"];
            opt.Audience = Configuration["ActiveDirectory:Audience"];
...

services
        .AddAuthorization(options =>
        {
            options.DefaultPolicy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .AddAuthenticationSchemes("Default", "AzureAD")
                .Build();
        });

I tried several variations of this, like hardcoding the authority etc. in different formats. I get to the login page where I'm able to log in using the default user/password authentication, but after that every page only shows me this 500 error:

Even after I commented out all the new configs. When I remove the AzureAD authentication scheme, it works normally again.
Any suggestions?

Of course I registered the app and used the info from the Azure AD page.

Also, when trying this:

services.AddAuthentication("MyAuthenticationScheme")
      .AddMicrosoftIdentityWebApp();

It says:

Severity  Code    Description Project File    Line    Suppression State
Error   CS1061  'AuthenticationBuilder' does not contain a definition for 'AddMicrosoftIdentityWebApp' and no accessible extension method 'AddMicrosoftIdentityWebApp' accepting a first argument of type 'AuthenticationBuilder' could be found (are you missing a using directive or an assembly reference?)  JI.Infopool.WebApp  C:\Projekte\JI.Infopool - master\JI.Infopool.WebApp\Startup.cs  56  Active

Although I've included the NuGet Package Microsoft.Identity.Web

Body:
1.Initially please check if the login request to microsoft was locked by the firewall.

2.Make sure  appsettings.json values are correct.

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "<azure ad domain>",
  "TenantId": "<azure ad tenant id>",
  "ClientId": "<backend app id>"
}

In Startup.cs

Check the following  code in ConfigureServices()

    public void ConfigureServices(IServiceCollection services)
    {
        //services.AddControllersWithViews();
///
//
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
        services.AddAuthorization();

        ...
    }

In configure() method make sure you have these

        app.UseAuthentication();
        app.UseAuthorization();

Reference: using openidconnect-with-azure-ad-angular and core webapiconfiguration


问:
How do I print the values in the groovy function?
I am new to groovy. I am trying to print the vales in the function. But, I am unable to see in the logs. I would like to know if this is the right way to echo the values. Below is the code:

```<code>void kubernetesDeploy(String chartName, String imageTag, String kubecliVersion, String mavenChartName) {

        helloApplyHelmTemplate(
                env: "dev",
                chartName: "${chartName}",
                pathToValues: "./${chartName}/values-dev.yaml",
                imageTag: "${imageTag}",
                kubecliVersion: kubecliVersion,
                mavenChartName: "${mavenChartName}"
        )

            // Printing the variables for testing
            println "chartName:++++++ ${chartName}"
            println "pathToValues:++++++ ${pathToValues}"
            println "imageTag:++++++ ${imageTag}"
            println "kubecliVersion:++++++ ${kubecliVersion}"
            println "mavenChartName:++++++ ${mavenChartName}"
}
</code>```

答: println don't writes in a log (BTW: which IDE are you using?) but writes to the output stream. In Eclipse it would be the Console View, in a shell the command prompt.</p>

Body:
I am new to groovy. I am trying to print the vales in the function. But, I am unable to see in the logs. I would like to know if this is the right way to echo the values. Below is the code:

void kubernetesDeploy(String chartName, String imageTag, String kubecliVersion, String mavenChartName) {

        helloApplyHelmTemplate(
                env: "dev",
                chartName: "${chartName}",
                pathToValues: "./${chartName}/values-dev.yaml",
                imageTag: "${imageTag}",
                kubecliVersion: kubecliVersion,
                mavenChartName: "${mavenChartName}"
        )

            // Printing the variables for testing
            println "chartName:++++++ ${chartName}"
            println "pathToValues:++++++ ${pathToValues}"
            println "imageTag:++++++ ${imageTag}"
            println "kubecliVersion:++++++ ${kubecliVersion}"
            println "mavenChartName:++++++ ${mavenChartName}"
}


问:
How to add create powershell aliases for git commands
I have been tired of doing git add & git commit everyday
I know in Linux you can just edit your bashrc using 1 line command
But since I use windows I am having a hard time creating an alias for

```<code> Fucntion gcd {
    Insert("git commit")
}
Set-Alias gcm gcd
</code>```

But I get an error

```<code>Set-Alias : Alias is not writeable because alias gcm is read-only or constant and cannot be written to.
</code>```

I also tried without using Insert Keyword even without functions still getting an error

答:
You don't need to rely on your specific shell for aliases, since Git already supports them out of the box:

If you don’t want to type the entire text of each of the Git commands, you can easily set up an alias for each command using git config.

Git aliases are defined in the .gitconfig file, either globally or for a particular repository.

In your case, you can create a global alias for git commit by saying:

git config --global alias.gcd commit
```

Body:
I have been tired of doing git add & git commit everyday
I know in Linux you can just edit your bashrc using 1 line command
But since I use windows I am having a hard time creating an alias for

 Fucntion gcd {
    Insert("git commit")
}
Set-Alias gcm gcd

But I get an error

Set-Alias : Alias is not writeable because alias gcm is read-only or constant and cannot be written to.

I also tried without using Insert Keyword even without functions still getting an error


问:
Syntax error in sqlite statement in python?
I have the following code fragment in an object initializer. However, the third line below gives the error sqlite3.OperationalError: near "(": syntax error

```<code>self._conn = sqlite3.connect('dictionary')
cursor = self._conn.cursor()
cursor.execute('CREATE TABLE `words` (`word` VARCHAR(15) NOT NULL, PRIMARY (`word`));')
</code>```

Any ideas as to what could be causing this. I'm far from an export at SQL but I fail to see what I did incorrectly.

答:
PRIMARY word is not valid SQL. Use

```<code>CREATE TABLE words (word VARCHAR(15) NOT NULL PRIMARY KEY);
</code>```

Body:
I have the following code fragment in an object initializer. However, the third line below gives the error sqlite3.OperationalError: near "(": syntax error

self._conn = sqlite3.connect('dictionary')
cursor = self._conn.cursor()
cursor.execute('CREATE TABLE `words` (`word` VARCHAR(15) NOT NULL, PRIMARY (`word`));')

Any ideas as to what could be causing this. I'm far from an export at SQL but I fail to see what I did incorrectly.

Body:
PRIMARY word is not valid SQL. Use

CREATE TABLE words (word VARCHAR(15) NOT NULL PRIMARY KEY);


问:
How to setup a different path for ignored types for prettier file watcher in IntelliJ IDEA?
I have installed Prettier plugin in my IntelliJ IDEA and configured file watcher for it.
At the beginning ignored types were defined in .prettierignore file in project root directory. However due to other plugins which also are using similar files to ignore, .prettierignore was moved to other directory with other config files and renamed: ./configs/.qualityignore.

Path in file watcher was updated appropriately. But due to some reason, when I use ctrl+alt+shift+P (plugin's key shortcut) Prettier besides to see path doesn't respect it and change ignored files.

File Watcher Settings

Program: $ProjectFileDir$\node_modules\.bin\prettier

Arguments: --write $FilePathRelativeToProjectRoot$ --ignore-path configs/.qualityignore

Output paths to refresh: $FilePathRelativeToProjectRoot$

Console output

cmd.exe /D /C call C:\Users\Bob\Projects\project-name\node_modules\.bin\prettier.cmd --write src\dashboard\common\ToolTipComponent.less.d.ts; --ignore-path configs\.qualityignore

[error] No matching files. Patterns tried: src\dashboard\common\ToolTipComponent.less.d.ts; !**/node_modules/** !./node_modules/** !**/.{git,svn,hg}/** !./.{git,svn,hg}/**

Process finished with exit code 2

Is it a prettier plugin limitation/issue or I'm doing something wrong? Is there an other way to setup this updated path to Prettier plugin and it's file watcher?

答:
Ok, I managed to solve this issue by myself, so now I would like to share my solution.

First of all - my File Watcher Settings were wrong. Correct version:

Program: $ProjectFileDir$\node_modules\.bin\prettier

Arguments: --write $FilePathRelativeToProjectRoot$ --ignore-path $ProjectFileDir$\configs\.qualityignore

Output paths to refresh:

Working directory: $ProjectFileDir$

Main changes:

a little bit different path for ignored files

no need any output paths to refresh

added working directory

If you have checked in Advanced options: Auto-save edited files to trigger the watcher, prettier will be fired every time when you will save your changes, so actually no need to use keyboard shortcut for Prettier: ctrl+alt+shift+P.

If for some reason you prefer to use keyboard shortcut and your file with ignored types is in the different location than root, in my opinion is better to uninstall Prettier plugin and create a new external tool with prettier script (you need to have installed prettier locally) and than you can give it whatever keyboard shortcut you want. I found this article really helpful in this matter: Run prettier in WebStorm or IntelliJ on Windows

Just in case, my settings to this second solution:

Program: $ProjectFileDir$\node_modules\.bin\prettier.cmd

Arguments: --write $FilePathRelativeToProjectRoot$ --ignore-path $ProjectFileDir$\configs\.qualityignore

Working directory: $ProjectFileDir$

IntelliJ IDEA version: 2021.2.3


问:
If q-char-sequence is about source file, then why the grammar doesn't have source-file-name?
C2x, 6.10.2 Source file inclusion, Semantics, 2 (emphasis added):

A preprocessing directive of the form

```<code># include " q-char-sequence " new-line
</code>```

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

C2x, 6.4.7 Header names, Syntax, 1:

```<code>header-name:
                 < h-char-sequence >
                 " q-char-sequence "
</code>```

If q-char-sequence is about source file, then why the grammar doesn't have source-file-name?

Meaning that per grammar "x.c", "x.h", <x.c>, and <x.h> are all header-name. A bit confused.

答:
The grammar only defines h-char-sequence and q-char-sequence as sequence of characters. It is up to the implementation to say which sequences are valid and how they are interpreted. The standards only adds the following constraint:

A #include directive shall identify a header or source file that can be processed by the implementation.

So using a sequence that would not not indentify a correct file should raise a compilation error.

The semantics part adds another requirement §5:

The implementation shall provide unique mappings for sequences consisting of one or more nondigits
or digits (6.4.2.1) followed by a period (.) and a single nondigit. The first character shall not be a
digit. The implementation may ignore distinctions of alphabetical case and restrict the mapping to
eight significant characters before the period.

This ensures that the implementation will be able to accept the standard names like stdio.h and that a file having a name like foo.h has to be accepted, provided it maps to an existing file with the correct format.

Body:
C2x, 6.10.2 Source file inclusion, Semantics, 2 (emphasis added):

A preprocessing directive of the form

# include " q-char-sequence " new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

C2x, 6.4.7 Header names, Syntax, 1:

header-name:
                 < h-char-sequence >
                 " q-char-sequence "

If q-char-sequence is about source file, then why the grammar doesn't have source-file-name?

Meaning that per grammar "x.c", "x.h", <x.c>, and <x.h> are all header-name. A bit confused.


问:
WHMCS how to find right tpl files in pages
i'm using WHMCS and i want to make some changes in part of the page but its so hard and takes so much time for me to find the right tpl file and edit it in the template.

for example for this "search for domains" tab in this url =>

```<code>example.com/cart.php?a=add&domain=register
</code>```

where is the .tpl file.

答: The tpl for cart.php?a=add&domain=register is actually located at /whmcs/templates/orderforms/standard_cart/domainregister.tpl if I understand your question.</p>

Body:
i'm using WHMCS and i want to make some changes in part of the page but its so hard and takes so much time for me to find the right tpl file and edit it in the template.

for example for this "search for domains" tab in this url =>

example.com/cart.php?a=add&domain=register

where is the .tpl file.


问:
How to make this IsSimilar(varchar,varchar) function more performant
I need to implement a function to look for similar names. It's for the development of a new system that has migrated the data of a previous system.
One of the features would be that on account creation, it would try and look for person records that are there with a similar name and propose them.
Examples for similar names for "John Johnson" could be:

John Johnson

Jon Jonsen

John & Jane Johnson-Peters

Fam. Johnsen

J. Johnson

To achieve this I've created some SQL functions and functional wise they work:

[dbo].[Levenshtein]: A copy of the top rated answer from this question

[dbo].[SplitString]: Which is to split a name string based on '/', '', '&', '+' and '-'

```<code> CREATE FUNCTION [dbo].[SplitString](
     @s nvarchar(4000)
 )
 RETURNS @table TABLE ([value] VARCHAR(4000))
 WITH SCHEMABINDING
 AS
 BEGIN
     DECLARE @repl VARCHAR(4000) = REPLACE(REPLACE(REPLACE(REPLACE(@s, '/', '-'),'&', '-'),'+', '-'),'\', '-');
     INSERT INTO @table
     SELECT TRIM(value) FROM STRING_SPLIT(@repl, '-', NULL)
     WHERE RTRIM(value) <> '';

     RETURN
 END
</code>```

[dbo].[IsSimilar]: Takes 2 strings, calls the split function and checks if any part of the splits are similar, meaning within Levenshtein distance 5, an initial, or 'Fam'

```<code> CREATE FUNCTION [dbo].[IsSimilar](
     @s nvarchar(4000)
   , @t nvarchar(4000)
 )
 RETURNS BIT
 WITH SCHEMABINDING
 AS
 BEGIN
     DECLARE @sT TABLE (idx int IDENTITY(1,1), [value] VARCHAR(4000))
     DECLARE @tT TABLE (idx int IDENTITY(1,1), [value] VARCHAR(4000))
     DECLARE @sNrOfWords INT,
             @tNrOfWords INT,
             @sCount INT = 1,
             @tCount INT = 1,
             @sVal VARCHAR(4000),
             @tVal VARCHAR(4000)

     IF (@s = 'fam' OR @s = 'fam.' OR @t = 'fam' OR @t = 'fam.')
         return 1

     INSERT INTO @sT SELECT [value] FROM [dbo].[SplitString](@s)
     INSERT INTO @tT SELECT [value] FROM [dbo].[SplitString](@t)

     SET @sNrOfWords = (SELECT COUNT([value]) FROM @sT)
     SET @tNrOfWords = (SELECT COUNT([value]) FROM @tT)

     IF (@sNrOfWords > 0 AND @tNrOfWords > 0)
     BEGIN
         WHILE (@sCount <= (SELECT MAX(idx) FROM @sT))
         BEGIN
             SET @sVal = (SELECT [value] FROM @sT WHERE idx = @sCount)
             WHILE (@tCount <= (SELECT MAX(idx) FROM @tT))
             BEGIN
                 SET @tVal = (SELECT [value] FROM @tT WHERE idx = @tCount)
                 IF (((LEN(@sVal) = 1 OR LEN(@tVal) = 1 OR SUBSTRING(@sVal, 2, 1) IN ('.', ' ') OR SUBSTRING(@tVal, 2, 1) IN ('.', ' ')) AND SUBSTRING(@sVal, 1, 1) = SUBSTRING(@tVal, 1, 1)) OR ((SELECT [dbo].[Levenshtein](@sVal,@tVal, 5)) IS NOT NULL))
                     RETURN 1
                 SET @tCount = @tCount + 1
             END
             SET @sCount = @sCount + 1
             SET @tCount = 1
         END
     END
     RETURN 0
 END
</code>```

Sadly this solution isn't the most performant :(

It takes 12-13s to find this record based on my mispelled name, which off course is too long.
The full table is only 512 records at the moment.

Any help on getting this more performant?
I know looping isn't recomended in SQL, so probably something to gain there.
I'm not a DBA or SQL specialist, no idea how to write that differently without the loops.
Didn't think I could use a join as there's no equality.

答:
After implementing the suggestions in the comments on the OP, I managed to cut down the same SELECT statement from 12-13s to about 1s, which is a lot more acceptable.

The SplitString has been changed to an inline function:

```<code>Create FUNCTION [dbo].[SplitString](
    @s nvarchar(4000)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN(
    SELECT TRIM(value) AS value FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(REPLACE(@s, '/', '-'),'&', '-'),'+', '-'),'\', '-'), '-', NULL)
    WHERE RTRIM(value) <> ''
);
</code>```

Cutting down on the variables and using a Join statement for the IsSimilar function gives a boost as well:

```<code>CREATE FUNCTION [dbo].[IsSimilar](
    @s nvarchar(4000)
    , @t nvarchar(4000)
)
RETURNS BIT
AS
BEGIN

    IF (@s = 'fam' OR @s = 'fam.' OR @t = 'fam' OR @t = 'fam.')
        return 1

    IF (LEN(TRIM(@s)) > 0 AND LEN(TRIM(@t)) > 0)
    BEGIN
        RETURN (SELECT IIF (EXISTS(SELECT [sT].[value] FROM (SELECT [value] FROM [dbo].[SplitString](@s)) AS sT INNER JOIN (SELECT [value] FROM [dbo].[SplitString](@t)) AS tT ON (((LEN([sT].[value]) = 1 OR LEN([tT].[value]) = 1 OR SUBSTRING([sT].[value], 2, 1) IN ('.', ' ') OR SUBSTRING([tT].[value], 2, 1) IN ('.', ' ')) AND SUBSTRING([sT].[value], 1, 1) = SUBSTRING([tT].[value], 1, 1)) OR (NOT(SUBSTRING([sT].[value], 2, 1) IN ('.', ' ') OR SUBSTRING([tT].[value], 2, 1) IN ('.', ' ')) AND (SELECT [dbo].[Levenshtein]([sT].[value],[tT].[value], 5)) IS NOT NULL)) ), 1, 0))
    END
    RETURN 0
END
</code>```

I don't know how much this boost will hold up to real big data, but in this case that'll not be the case as Person records get linked to Account records with every new account creation and only Person records with AccountID = NULL will be considered.

Body:
I need to implement a function to look for similar names. It's for the development of a new system that has migrated the data of a previous system.
One of the features would be that on account creation, it would try and look for person records that are there with a similar name and propose them.
Examples for similar names for "John Johnson" could be:

John Johnson

Jon Jonsen

John & Jane Johnson-Peters

Fam. Johnsen

J. Johnson

To achieve this I've created some SQL functions and functional wise they work:

[dbo].[Levenshtein]: A copy of the top rated answer from this question

[dbo].[SplitString]: Which is to split a name string based on '/', '', '&', '+' and '-'

 CREATE FUNCTION [dbo].[SplitString](
     @s nvarchar(4000)
 )
 RETURNS @table TABLE ([value] VARCHAR(4000))
 WITH SCHEMABINDING
 AS
 BEGIN
     DECLARE @repl VARCHAR(4000) = REPLACE(REPLACE(REPLACE(REPLACE(@s, '/', '-'),'&', '-'),'+', '-'),'\', '-');
     INSERT INTO @table
     SELECT TRIM(value) FROM STRING_SPLIT(@repl, '-', NULL)
     WHERE RTRIM(value) <> '';

     RETURN
 END

[dbo].[IsSimilar]: Takes 2 strings, calls the split function and checks if any part of the splits are similar, meaning within Levenshtein distance 5, an initial, or 'Fam'

 CREATE FUNCTION [dbo].[IsSimilar](
     @s nvarchar(4000)
   , @t nvarchar(4000)
 )
 RETURNS BIT
 WITH SCHEMABINDING
 AS
 BEGIN
     DECLARE @sT TABLE (idx int IDENTITY(1,1), [value] VARCHAR(4000))
     DECLARE @tT TABLE (idx int IDENTITY(1,1), [value] VARCHAR(4000))
     DECLARE @sNrOfWords INT,
             @tNrOfWords INT,
             @sCount INT = 1,
             @tCount INT = 1,
             @sVal VARCHAR(4000),
             @tVal VARCHAR(4000)

     IF (@s = 'fam' OR @s = 'fam.' OR @t = 'fam' OR @t = 'fam.')
         return 1

     INSERT INTO @sT SELECT [value] FROM [dbo].[SplitString](@s)
     INSERT INTO @tT SELECT [value] FROM [dbo].[SplitString](@t)

     SET @sNrOfWords = (SELECT COUNT([value]) FROM @sT)
     SET @tNrOfWords = (SELECT COUNT([value]) FROM @tT)

     IF (@sNrOfWords > 0 AND @tNrOfWords > 0)
     BEGIN
         WHILE (@sCount <= (SELECT MAX(idx) FROM @sT))
         BEGIN
             SET @sVal = (SELECT [value] FROM @sT WHERE idx = @sCount)
             WHILE (@tCount <= (SELECT MAX(idx) FROM @tT))
             BEGIN
                 SET @tVal = (SELECT [value] FROM @tT WHERE idx = @tCount)
                 IF (((LEN(@sVal) = 1 OR LEN(@tVal) = 1 OR SUBSTRING(@sVal, 2, 1) IN ('.', ' ') OR SUBSTRING(@tVal, 2, 1) IN ('.', ' ')) AND SUBSTRING(@sVal, 1, 1) = SUBSTRING(@tVal, 1, 1)) OR ((SELECT [dbo].[Levenshtein](@sVal,@tVal, 5)) IS NOT NULL))
                     RETURN 1
                 SET @tCount = @tCount + 1
             END
             SET @sCount = @sCount + 1
             SET @tCount = 1
         END
     END
     RETURN 0
 END

Sadly this solution isn't the most performant :(

It takes 12-13s to find this record based on my mispelled name, which off course is too long.
The full table is only 512 records at the moment.

Any help on getting this more performant?
I know looping isn't recomended in SQL, so probably something to gain there.
I'm not a DBA or SQL specialist, no idea how to write that differently without the loops.
Didn't think I could use a join as there's no equality.

Body:
After implementing the suggestions in the comments on the OP, I managed to cut down the same SELECT statement from 12-13s to about 1s, which is a lot more acceptable.

The SplitString has been changed to an inline function:

Create FUNCTION [dbo].[SplitString](
    @s nvarchar(4000)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN(
    SELECT TRIM(value) AS value FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(REPLACE(@s, '/', '-'),'&', '-'),'+', '-'),'\', '-'), '-', NULL)
    WHERE RTRIM(value) <> ''
);

Cutting down on the variables and using a Join statement for the IsSimilar function gives a boost as well:

CREATE FUNCTION [dbo].[IsSimilar](
    @s nvarchar(4000)
    , @t nvarchar(4000)
)
RETURNS BIT
AS
BEGIN

    IF (@s = 'fam' OR @s = 'fam.' OR @t = 'fam' OR @t = 'fam.')
        return 1

    IF (LEN(TRIM(@s)) > 0 AND LEN(TRIM(@t)) > 0)
    BEGIN
        RETURN (SELECT IIF (EXISTS(SELECT [sT].[value] FROM (SELECT [value] FROM [dbo].[SplitString](@s)) AS sT INNER JOIN (SELECT [value] FROM [dbo].[SplitString](@t)) AS tT ON (((LEN([sT].[value]) = 1 OR LEN([tT].[value]) = 1 OR SUBSTRING([sT].[value], 2, 1) IN ('.', ' ') OR SUBSTRING([tT].[value], 2, 1) IN ('.', ' ')) AND SUBSTRING([sT].[value], 1, 1) = SUBSTRING([tT].[value], 1, 1)) OR (NOT(SUBSTRING([sT].[value], 2, 1) IN ('.', ' ') OR SUBSTRING([tT].[value], 2, 1) IN ('.', ' ')) AND (SELECT [dbo].[Levenshtein]([sT].[value],[tT].[value], 5)) IS NOT NULL)) ), 1, 0))
    END
    RETURN 0
END

I don't know how much this boost will hold up to real big data, but in this case that'll not be the case as Person records get linked to Account records with every new account creation and only Person records with AccountID = NULL will be considered.


问:
Matplotlib axhline: linewidth changes X position of line
I've observed some weird effects of using linewidth param in axhline from matplotlib.pyplot. I want to make line bolder, but this param makes line wider too.

For example, linewidth = 1:

and linewidth = 25:

X position of these blocks makes really big difference for me. I can't accept errors as big as that. Do you have any ideas how to make this line bolder without changing their X position?

答:
If the lines you are drawing are limited between a minimum and a maximum value, then you should use matplotlib.pyplot.hlines in place of matplotlib.pyplot.axhline. Moreover you can control the line endings style with capstyle parameter:

```<code>import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.hlines(y = 1, xmin = 1, xmax = 2, color = 'red', linewidth = 1, label = 'linewidth = 1, default capstyle')
ax.hlines(y = 2, xmin = 1, xmax = 2, color = 'green', linewidth = 25, capstyle = 'projecting', label = 'linewidth = 25, "projecting" capstyle')
ax.hlines(y = 3, xmin = 1, xmax = 2, color = 'blue', linewidth = 25, capstyle = 'butt', label = 'linewidth = 25, "butt" capstyle')

ax.set_xlim(-1, 4)
ax.set_ylim(-1, 5)

ax.legend(frameon = True)

plt.show()
</code>```

Body:
If the lines you are drawing are limited between a minimum and a maximum value, then you should use matplotlib.pyplot.hlines in place of matplotlib.pyplot.axhline. Moreover you can control the line endings style with capstyle parameter:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.hlines(y = 1, xmin = 1, xmax = 2, color = 'red', linewidth = 1, label = 'linewidth = 1, default capstyle')
ax.hlines(y = 2, xmin = 1, xmax = 2, color = 'green', linewidth = 25, capstyle = 'projecting', label = 'linewidth = 25, "projecting" capstyle')
ax.hlines(y = 3, xmin = 1, xmax = 2, color = 'blue', linewidth = 25, capstyle = 'butt', label = 'linewidth = 25, "butt" capstyle')

ax.set_xlim(-1, 4)
ax.set_ylim(-1, 5)

ax.legend(frameon = True)

plt.show()


问:
XMPP 1 to 1 chat query?
I am developing a chat project using Openfire.

I have done with group chatting.

But confusion is in 1 to 1 chat.

I am using:

```<code><message from='user2@server/user2' to='user1@server/user1' type='chat'>

<body>TEST< /body>

</message>
</code>```

but it does not send it.

Thanks in advance.

答:
After fixing the syntax issues, removing the from address, and removing the doubtfully-correct resource from the to address, you're left with:

```<code><message to='user1@server' type='chat'>
  <body>TEST</body>
</message>
</code>```

The resource on the to address is like the issue.  Read XEP-0296 for how to deal with resources correctly when doing XMPP IM.

Title: XMPP 1 to 1 chat query?

Body:
I am developing a chat project using Openfire.

I have done with group chatting.

But confusion is in 1 to 1 chat.

I am using:

<message from='user2@server/user2' to='user1@server/user1' type='chat'>

TEST

</message>

but it does not send it.

Thanks in advance.

Body:
After fixing the syntax issues, removing the from address, and removing the doubtfully-correct resource from the to address, you're left with:

<message to='user1@server' type='chat'>
  <body>TEST</body>
</message>

The resource on the to address is like the issue.  Read XEP-0296 for how to deal with resources correctly when doing XMPP IM.


问:
Jenkins pipeline stage build is green even though an error is present
I have a Jenkins Pipline with three stages: "Build" "Test" and "Deploy".

Here is the problem I have with "Build":

The build step ensures that structure of the Control-M Automation API json files are valid.

To do this, I utilize the $endpoint/build service provided by Automation API in the build step:

```<code>        stage('Build') {
            environment {
                CONTROLM_CREDS = credentials('xxx')
                ENDPOINT = 'xxx'
            }
            steps {
                sh '''
                username=$CONTROLM_CREDS_USR
                password=$CONTROLM_CREDS_PSW
                # Login
                login=$(curl -k -s -H "Content-Type: application/json" -X POST -d \\{\\"username\\":\\"$username\\",\\"password\\":\\"$password\\"\\} "$ENDPOINT/session/login" )
                token=$(echo ${login##*token\\" : \\"} | cut -d '"' -f 1)
                # Build
                curl -k -s -H "Authorization: Bearer $token" -X POST -F "definitionsFile=@ctmjobs/TestCICD.json" "$ENDPOINT/build"
                curl -k -s -H "Authorization: Bearer $token" -X POST "$ENDPOINT/session/logout"
                '''
            }
        }
<snip>
</code>```

Everything works as expected, but if I intentionally put an error in the json file, Jenkins detects it and prints the error in the terminal, but "Build" still goes green. Can anyone identify the error? My expectation is that the stage "Build" goes to red as soon as there is an error in the JSON file.

Here is a Jenkins output from the terminal:

```<code>+ password=****
++ curl -k -s -H 'Content-Type: application/json' -X POST -d '{"username":"xxx","password":"****"}' /automation-api/session/login
+ login='{
  "username" : "xxx",
  "token" : "xxx",
  "version" : "9.19.200"
}'
++ echo 'xxx",
' '"version"' : '"9.19.200"
' '}'
++ cut -d '"' -f 1
+ token=xxx
+ curl -k -s -H 'Authorization: Bearer xxx' -X POST -F definitionsFile=@ctmjobs/Test.json /automation-api/build
{
  "errors" : [ {
    "message" : "unknown type: Job:Dummmy",
    "file" : "Test.json",
    "line" : 40,
    "col" : 29
  }, {
    "message" : "unknown type: Job:Dummmy",
    "file" : "Test.json",
    "line" : 63,
    "col" : 29
  } ]
}+ curl -k -s -H 'Authorization: Bearer xxx' -X POST /automation-api/session/logout
{
  "message" : "Successfully logged out from session xxx"
} ``

</code>```

答:
Jenkins in order to consider a stage as failed, it will check the exit code of a command executed, in your case

```<code>curl -k -s -H 'Authorization: Bearer xxx' -X POST -F definitionsFile=@ctmjobs/Test.json /automation-api/build
</code>```

The issue is that the curl, as a command, is executed successfully.
But the body of the curl indicates that the api call failed.

You could add --fail flag to your curl. This will force curl to return an erroneous exit code when the response status is > 400

(HTTP) Fail silently (no output at all) on server errors. This is
mostly done to enable scripts etc to better deal with failed attempts.
In normal cases when an HTTP server fails to deliver a document, it
returns an HTML document stating so (which often also describes why
and more). This flag will prevent curl from outputting that and return
error 22.

```<code>curl --show-error --fail -k -H 'Authorization: Bearer xxx' -X POST -F definitionsFile=@ctmjobs/Test.json /automation-api/build
</code>```

Body:
I have a Jenkins Pipline with three stages: "Build" "Test" and "Deploy".

Here is the problem I have with "Build":

The build step ensures that structure of the Control-M Automation API json files are valid.

To do this, I utilize the $endpoint/build service provided by Automation API in the build step:

        stage('Build') {
            environment {
                CONTROLM_CREDS = credentials('xxx')
                ENDPOINT = 'xxx'
            }
            steps {
                sh '''
                username=$CONTROLM_CREDS_USR
                password=$CONTROLM_CREDS_PSW
                # Login
                login=$(curl -k -s -H "Content-Type: application/json" -X POST -d \\{\\"username\\":\\"$username\\",\\"password\\":\\"$password\\"\\} "$ENDPOINT/session/login" )
                token=$(echo ${login##*token\\" : \\"} | cut -d '"' -f 1)
                # Build
                curl -k -s -H "Authorization: Bearer $token" -X POST -F "definitionsFile=@ctmjobs/TestCICD.json" "$ENDPOINT/build"
                curl -k -s -H "Authorization: Bearer $token" -X POST "$ENDPOINT/session/logout"
                '''
            }
        }
<snip>

Everything works as expected, but if I intentionally put an error in the json file, Jenkins detects it and prints the error in the terminal, but "Build" still goes green. Can anyone identify the error? My expectation is that the stage "Build" goes to red as soon as there is an error in the JSON file.

Here is a Jenkins output from the terminal:

+ password=****
++ curl -k -s -H 'Content-Type: application/json' -X POST -d '{"username":"xxx","password":"****"}' /automation-api/session/login
+ login='{
  "username" : "xxx",
  "token" : "xxx",
  "version" : "9.19.200"
}'
++ echo 'xxx",
' '"version"' : '"9.19.200"
' '}'
++ cut -d '"' -f 1
+ token=xxx
+ curl -k -s -H 'Authorization: Bearer xxx' -X POST -F definitionsFile=@ctmjobs/Test.json /automation-api/build
{
  "errors" : [ {
    "message" : "unknown type: Job:Dummmy",
    "file" : "Test.json",
    "line" : 40,
    "col" : 29
  }, {
    "message" : "unknown type: Job:Dummmy",
    "file" : "Test.json",
    "line" : 63,
    "col" : 29
  } ]
}+ curl -k -s -H 'Authorization: Bearer xxx' -X POST /automation-api/session/logout
{
  "message" : "Successfully logged out from session xxx"
} ``

Body:
Jenkins in order to consider a stage as failed, it will check the exit code of a command executed, in your case

curl -k -s -H 'Authorization: Bearer xxx' -X POST -F definitionsFile=@ctmjobs/Test.json /automation-api/build

The issue is that the curl, as a command, is executed successfully.
But the body of the curl indicates that the api call failed.

You could add --fail flag to your curl. This will force curl to return an erroneous exit code when the response status is > 400

(HTTP) Fail silently (no output at all) on server errors. This is
mostly done to enable scripts etc to better deal with failed attempts.
In normal cases when an HTTP server fails to deliver a document, it
returns an HTML document stating so (which often also describes why
and more). This flag will prevent curl from outputting that and return
error 22.

curl --show-error --fail -k -H 'Authorization: Bearer xxx' -X POST -F definitionsFile=@ctmjobs/Test.json /automation-api/build