问:
Thread-safe circular buffer in Java
Consider a few web server instances running in parallel. Each server holds a reference to a single shared "Status keeper", whose role is keeping the last N requests from all servers.

For example (N=3):

```<code>Server a: "Request id = ABCD"        Status keeper=["ABCD"]
Server b: "Request id = XYZZ"        Status keeper=["ABCD", "XYZZ"]
Server c: "Request id = 1234"        Status keeper=["ABCD", "XYZZ", "1234"]
Server b: "Request id = FOO"         Status keeper=["XYZZ", "1234", "FOO"]
Server a: "Request id = BAR"         Status keeper=["1234", "FOO", "BAR"]
</code>```

At any point in time, the "Status keeper" might be called from a monitoring application that reads these last N requests for an SLA report.

What's the best way to implement this producer-consumer scenario in Java, giving the web servers higher priority than the SLA report?

CircularFifoBuffer seems to be the appropriate data structure to hold the requests, but I'm not sure what's the optimal way to implement efficient concurrency.

答:
Since you specifically ask to give writers (that is web servers) higher priority than the reader (that is monitoring), I would suggest the following design.

Web servers add request information to a concurrent queue which is read by a dedicated thread, which adds requests to a thread-local (therefore non-synchronized) queue that overwrites the oldest element, like EvictingQueue or CircularFifoQueue.
This same thread checks a flag which indicates if a report has been requested after every request processed, and if positive, produces a report from all elements present in the thread-local queue.

Title: Thread-safe circular buffer in Java

Body:
Consider a few web server instances running in parallel. Each server holds a reference to a single shared "Status keeper", whose role is keeping the last N requests from all servers.

For example (N=3):

Server a: "Request id = ABCD"        Status keeper=["ABCD"]
Server b: "Request id = XYZZ"        Status keeper=["ABCD", "XYZZ"]
Server c: "Request id = 1234"        Status keeper=["ABCD", "XYZZ", "1234"]
Server b: "Request id = FOO"         Status keeper=["XYZZ", "1234", "FOO"]
Server a: "Request id = BAR"         Status keeper=["1234", "FOO", "BAR"]

At any point in time, the "Status keeper" might be called from a monitoring application that reads these last N requests for an SLA report.

What's the best way to implement this producer-consumer scenario in Java, giving the web servers higher priority than the SLA report?

CircularFifoBuffer seems to be the appropriate data structure to hold the requests, but I'm not sure what's the optimal way to implement efficient concurrency.


来源: stackexchange

问:
How do i convert a textfile to lower case and find the frequencies of the letters?
I am writing a code that reads a text file and outputs the frequency of the letters. I used a FileInputStream method to read the file and I have no idea on how to convert the uppercase to lower case.

The code runs but only lower case letters are being read. How do i rectify the issue?

答:
If you're allowed to use Java 8 streams and such "new" IO objects as Files and Path, you can do this task pretty simply:

```<code>Map<Character, Long> freq = Files.lines(Path.of(filepath))        // get stream of file lines
                .flatMap(s -> s.chars().mapToObj(c -> (char) c))  // convert each line into stream of characters
                .collect(
                    Collectors.groupingBy(Function.identity(),    // group by each character
                    Collectors.counting()));                      // count characters in the stream
</code>```

If you need to count only letters, you can additionally filter them:

```<code>Map<Character, Long> letterFreq = Files.lines(Path.of(filepath))
                .flatMap(s -> s.chars().mapToObj(c -> (char) c))
                .filter(Character::isLetter)
                .collect(
                    Collectors.groupingBy(Function.identity(), Collectors.counting()));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you're allowed to use Java 8 streams and such "new" IO objects as Files and Path, you can do this task pretty simply:

Map<Character, Long> freq = Files.lines(Path.of(filepath))        // get stream of file lines
                .flatMap(s -> s.chars().mapToObj(c -> (char) c))  // convert each line into stream of characters
                .collect(
                    Collectors.groupingBy(Function.identity(),    // group by each character
                    Collectors.counting()));                      // count characters in the stream

If you need to count only letters, you can additionally filter them:

Map<Character, Long> letterFreq = Files.lines(Path.of(filepath))
                .flatMap(s -> s.chars().mapToObj(c -> (char) c))
                .filter(Character::isLetter)
                .collect(
                    Collectors.groupingBy(Function.identity(), Collectors.counting()));


问:
Get a random client with no call history and order by the amount of calls they didn't answer
I have a simple database with a clients table. I also have a (phone) calls table. So when I call a client, the call will be logged.

Calls have a type id, all related to the topic of the call, except type id 11, which means they didn't pick up the phone.

So what I am trying to do is a get a random client to call, that has no history of picked up calls but then I want to order them by how many times they haven't answered.

I don't want to get a client that Ive called but hasn't picked up when theres clients available that I haven't even attempted to call yet. I want both, but the latter first.

```<code>SELECT clients.*
FROM clients
LEFT JOIN calls ON calls.client = clients.id and calls.type != 11
GROUP BY clients.id
HAVING COUNT(calls.id) < 1
ORDER BY RAND() ASC
LIMIT 1
</code>```

Here is where Im up to so far, It gets a random client without calls (except type 11) and then picks a random one

I just don't know how to order them by the amount of calls they didn't pick up in ASC order

答:
get count of calls first and then join on client

below will give you the idea

```<code>Select * From
Clients
Left Join
(
SELECT client, count(client) call_count
FROM calls
Where calls.type != 11
GROUP BY call.client
) calls
ON clients.id = calls.client
ORDER BY RAND() ASC
LIMIT 1
</code>```

Body:
I have a simple database with a clients table. I also have a (phone) calls table. So when I call a client, the call will be logged.

Calls have a type id, all related to the topic of the call, except type id 11, which means they didn't pick up the phone.

So what I am trying to do is a get a random client to call, that has no history of picked up calls but then I want to order them by how many times they haven't answered.

I don't want to get a client that Ive called but hasn't picked up when theres clients available that I haven't even attempted to call yet. I want both, but the latter first.

SELECT clients.*
FROM clients
LEFT JOIN calls ON calls.client = clients.id and calls.type != 11
GROUP BY clients.id
HAVING COUNT(calls.id) < 1
ORDER BY RAND() ASC
LIMIT 1

Here is where Im up to so far, It gets a random client without calls (except type 11) and then picks a random one

I just don't know how to order them by the amount of calls they didn't pick up in ASC order

Body:
get count of calls first and then join on client

below will give you the idea

Select * From
Clients
Left Join
(
SELECT client, count(client) call_count
FROM calls
Where calls.type != 11
GROUP BY call.client
) calls
ON clients.id = calls.client
ORDER BY RAND() ASC
LIMIT 1


问:
Why doesn't height: 100% work to expand divs to the screen height?
I want the carousel DIV (s7) to expand to the height of the entire screen. I haven't an idea as to why it's not succeeding. To see the page you can go here.

body {
  height: 100%;
  color: #FFF;
  font: normal 28px/28px'HelveticaWorldRegular', Helvetica, Arial, Sans-Serif;
  background: #222 url('') no-repeat center center fixed;
  overflow: hidden;
  background-size: cover;
  margin: 0;
  padding: 0;
}
.holder {
  height: 100%;
  margin: auto;
}
#s7 {
  width: 100%;
  height: 100%: margin: auto;
  overflow: hidden;
  z-index: 1;
}
#s7 #posts {
  width: 100%;
  min-height: 100%;
  color: #FFF;
  font-size: 13px;
  text-align: left;
  line-height: 16px;
  margin: auto;
  background: #AAA;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">

    <img src="http://static.tumblr.com/ux4v5bf/ASslogxz4/left.png">

    <img src="http://static.tumblr.com/ux4v5bf/swslogxmg/right.png">

</div>

<div class="holder">
  <tr>
    <td>
      <div id="s7">
        {block:Posts}
        <div id="posts"></code>```

答:
Here's another solution for people who don't want to use html, body, .blah { height: 100% }.

.app {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow-y: auto;
}

.full-height {
  height: 100%;
}

.test {
  width: 10px;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="full-height test">
  </div>
  Scroll works too
</div></code>```

Body:
I want the carousel DIV (s7) to expand to the height of the entire screen. I haven't an idea as to why it's not succeeding. To see the page you can go here.

body {
  height: 100%;
  color: #FFF;
  font: normal 28px/28px'HelveticaWorldRegular', Helvetica, Arial, Sans-Serif;
  background: #222 url('') no-repeat center center fixed;
  overflow: hidden;
  background-size: cover;
  margin: 0;
  padding: 0;
}
.holder {
  height: 100%;
  margin: auto;
}
#s7 {
  width: 100%;
  height: 100%: margin: auto;
  overflow: hidden;
  z-index: 1;
}
#s7 #posts {
  width: 100%;
  min-height: 100%;
  color: #FFF;
  font-size: 13px;
  text-align: left;
  line-height: 16px;
  margin: auto;
  background: #AAA;
}

        {block:Posts}

Body:
Here's another solution for people who don't want to use html, body, .blah { height: 100% }.

.app {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow-y: auto;
}

.full-height {
  height: 100%;
}

.test {
  width: 10px;
  background: red;
}

<div class="app">
  <div class="full-height test">
  </div>
  Scroll works too
</div>


问:
Bind image to datagrid using resources
I am trying to retrieve the image from resource file and tryin to bind it to the datagrid of my WPF application.

The datagrid is somewhat like this:

```<code><DataGridTemplateColumn Header="Image" Width="45">
  <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image  Source="{Binding Path=Icon}" />
                    </DataTemplate>
 </DataGridTemplateColumn.CellTemplate>
</code>```

And Image is a property of type image of my MVVm class like this:

```<code> public Image Icon
    {
        get { return _licenseImage; }
        set { _licenseImage = value;
        PropertChanged("Icon");}
    }
</code>```

And in the code behind Im tryin to do something like this to get image from resource file and tryin to bind it to datagrid column.

```<code>ResourceManager resourceManager =
        new ResourceManager("Resources.Images", Assembly.GetExecutingAssembly());
BitMap bitmap = resourceManager.GetObject("okimage") as BitMap;

Image image = bitmap;
return image;
</code>```

I can see that image is populated but it is not displaying in the grid.

答:
I think the problem is that you are binding to the wrong property. Try this:</p>

```<code><Image  Source="{Binding Path=Icon}" />
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bind image to datagrid using resources

Body:
I am trying to retrieve the image from resource file and tryin to bind it to the datagrid of my WPF application.

The datagrid is somewhat like this:

<DataGridTemplateColumn Header="Image" Width="45">
  <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image  Source="{Binding Path=Icon}" />
                    </DataTemplate>
 </DataGridTemplateColumn.CellTemplate>

And Image is a property of type image of my MVVm class like this:

 public Image Icon
    {
        get { return _licenseImage; }
        set { _licenseImage = value;
        PropertChanged("Icon");}
    }

And in the code behind Im tryin to do something like this to get image from resource file and tryin to bind it to datagrid column.

ResourceManager resourceManager =
        new ResourceManager("Resources.Images", Assembly.GetExecutingAssembly());
BitMap bitmap = resourceManager.GetObject("okimage") as BitMap;

Image image = bitmap;
return image;

I can see that image is populated but it is not displaying in the grid.

Body:
I think the problem is that you are binding to the wrong property. Try this:

<Image  Source="{Binding Path=Icon}" />


问:
drawer-navigation doesn't hide screen
I am using react-navigation 5 and I have stack navigation and inside drawer navigation, I want to hide some of the drawer's navigation screens. So, I pass null in drawerLabel attribute as follow

```<code>import * as React from 'react';
import {createDrawerNavigator} from '@react-navigation/drawer';
import ShowNotes from "../screens/notes/ShowNotes";

const Drawer = createDrawerNavigator();

const DrawerNavigation = () => {
    return (
        <Drawer.Navigator>
            <>
                <Drawer.Screen
                     name="Home"
                     component={ShowNotes}
                    options={{
                        headerTitle: 'All Notes',
                        drawerLabel: () => null
                    }}
                />
            </>
         </Drawer.Navigator>
   );
}
export default DrawerNavigation;
</code>```

This DrawerNavigation is inside a StackNavigation like so

```<code>const Stack = createStackNavigator();
const Navigation = ({auth}) => {
return (
    <NavigationContainer theme={CustomTheme}>
        <Stack.Navigator
            screenOptions={({navigation}) => ({
                headerLeft: () => (
                    <Button
                        onPress={() => navigation.dispatch(DrawerActions.openDrawer())}
                        title="Info"
                        color="#fff"
                    />
                ),
            })}
        >
                        <Stack.Screen
                            name="Home"
                            component={DrawerNavigation}
                        />
                        <Stack.Screen
                            name="AddNoteScreen"
                            component={AddNote}
                        />
                        <Stack.Screen
                            name="UpdateNoteScreen"
                            component={UpdateNote}
                        />
            }
        </Stack.Navigator>
    </NavigationContainer>
);
};

const mapStateToProps = state => {
    return {auth: state.auth};
};

export default connect(mapStateToProps, {})(Navigation);
</code>```

What I see on my screen is the drawer doesn't contain my screen but an empty blank area which is clickable

How I can stop displaying a screen in drawer?

Cheers

答:
I don't know if this is the best solution but this is what it works for me.

I set the screens that I don't want to display as Drawer.Screen and inside  Drawer.Navigator I set the property drawerContent with the screens that I want to display in the drawer. have a look in the code

```<code><Drawer.Navigator
        drawerContent={() => {
            return (
                <>
                    <DrawerContentScrollView>
                        {auth.isSignedIn ?
                            <Layout>
                                <Layout>
                                    <Layout style={{flexDirection: 'row', marginTop: 15, marginLeft: 10}}>
                                        <Avatar.Image
                                            source={{
                                                uri: auth.userData.picture,
                                            }}
                                            size={70}
                                        />
                                        <Layout style={{flexDirection: 'column', marginLeft: 15}}>
                                            <Title>{auth.userData.name}</Title>
                                            <Caption>{auth.userData.email}</Caption>
                                        </Layout>
                                    </Layout>

                                </Layout>
                            </Layout>
                            :
                            <>
                            </>
                        }
                    </DrawerContentScrollView>

                    <DrawerSection>
                        <DrawerItem
                            icon={({color, size}) => (
                                <Icon
                                    name="exit-to-app"
                                    color={color}
                                    size={size}
                                />
                            )}
                            label="Sign Out"
                            onPress={() => {
                                LoginManager.logOut();
                                signOut();
                            }}
                        />
                    </DrawerSection>
                </>
            );
        }}
    >
    <
            Drawer.Screen
            name="Home"
            component={ShowNotes}
            options={
                {
                    headerTitle: 'All Notes',
                }
            }
        />
        <Drawer.Screen
            name="AddNoteScreen"
            component={AddNote}
        />
        <Drawer.Screen
            name="UpdateNoteScreen"
            component={UpdateNote}
        />
    </Drawer.Navigator>
</code>```

I hope it helps!

Title: drawer-navigation doesn't hide screen

Body:
I am using react-navigation 5 and I have stack navigation and inside drawer navigation, I want to hide some of the drawer's navigation screens. So, I pass null in drawerLabel attribute as follow

import * as React from 'react';
import {createDrawerNavigator} from '@react-navigation/drawer';
import ShowNotes from "../screens/notes/ShowNotes";

const Drawer = createDrawerNavigator();

const DrawerNavigation = () => {
    return (
        <Drawer.Navigator>
            <>
                <Drawer.Screen
                     name="Home"
                     component={ShowNotes}
                    options={{
                        headerTitle: 'All Notes',
                        drawerLabel: () => null
                    }}
                />
            </>
         </Drawer.Navigator>
   );
}
export default DrawerNavigation;

This DrawerNavigation is inside a StackNavigation like so

const Stack = createStackNavigator();
const Navigation = ({auth}) => {
return (
    <NavigationContainer theme={CustomTheme}>
        <Stack.Navigator
            screenOptions={({navigation}) => ({
                headerLeft: () => (
                    <Button
                        onPress={() => navigation.dispatch(DrawerActions.openDrawer())}
                        title="Info"
                        color="#fff"
                    />
                ),
            })}
        >
                        <Stack.Screen
                            name="Home"
                            component={DrawerNavigation}
                        />
                        <Stack.Screen
                            name="AddNoteScreen"
                            component={AddNote}
                        />
                        <Stack.Screen
                            name="UpdateNoteScreen"
                            component={UpdateNote}
                        />
            }
        </Stack.Navigator>
    </NavigationContainer>
);
};

const mapStateToProps = state => {
    return {auth: state.auth};
};

export default connect(mapStateToProps, {})(Navigation);

What I see on my screen is the drawer doesn't contain my screen but an empty blank area which is clickable

How I can stop displaying a screen in drawer?

Cheers

Body:
I don't know if this is the best solution but this is what it works for me.

I set the screens that I don't want to display as Drawer.Screen and inside  Drawer.Navigator I set the property drawerContent with the screens that I want to display in the drawer. have a look in the code

<Drawer.Navigator
        drawerContent={() => {
            return (
                <>
                    <DrawerContentScrollView>
                        {auth.isSignedIn ?
                            <Layout>
                                <Layout>
                                    <Layout style={{flexDirection: 'row', marginTop: 15, marginLeft: 10}}>
                                        <Avatar.Image
                                            source={{
                                                uri: auth.userData.picture,
                                            }}
                                            size={70}
                                        />
                                        <Layout style={{flexDirection: 'column', marginLeft: 15}}>
                                            <Title>{auth.userData.name}</Title>
                                            <Caption>{auth.userData.email}</Caption>
                                        </Layout>
                                    </Layout>

                                </Layout>
                            </Layout>
                            :
                            <>
                            </>
                        }
                    </DrawerContentScrollView>

                    <DrawerSection>
                        <DrawerItem
                            icon={({color, size}) => (
                                <Icon
                                    name="exit-to-app"
                                    color={color}
                                    size={size}
                                />
                            )}
                            label="Sign Out"
                            onPress={() => {
                                LoginManager.logOut();
                                signOut();
                            }}
                        />
                    </DrawerSection>
                </>
            );
        }}
    >
    <
            Drawer.Screen
            name="Home"
            component={ShowNotes}
            options={
                {
                    headerTitle: 'All Notes',
                }
            }
        />
        <Drawer.Screen
            name="AddNoteScreen"
            component={AddNote}
        />
        <Drawer.Screen
            name="UpdateNoteScreen"
            component={UpdateNote}
        />
    </Drawer.Navigator>

I hope it helps!


问:
Why mySQL database saves the string in small letters?
Please help
I am trying to make a html application form. The user can fill out the form after that it will be saved in mySQL database. In html i have changed the text-transform: into capitalize, when you fill up the form you can see that the first letter is capitalized but in MySQL database, the letters are changed into small. Strange. </p>

答: could you explain what do yo save the data in Uppercase? Any way, if yo want yo can create a function with js to capture data of the input before you send this to msyql, and this way yo can validate if the data has o no a capitalize. Because the css only has effect in browser like a Sepencer7593</p>


问:
Macro to loop through multiple excel files and download data from each
The goal of this Macro is to combine data from multiple excel files from different months into one master excel file. I have created a tab for every month in the master excel file (see attached picture) that I would like the data to go to and stack on top of each other.

I found some helpful code that I got to work a few times but after modifications is now broken. A few issues that I think I need to resolve before it can work like I want are:

This code is built with a fixed range that gets copied. The excel files I am looking at will have ranges that are variable.

The code keeps breaking on the line that reads Set wbTemp = Workbooks.Open(Filename:=FilePath & MyFile, ReadOnly:=True). This could be because I am testing excel files in different month folders all that have the same name?

I am getting the following error: "Run-time error '1004': Microsoft Excel cannot access the file 'S:\Actg\TESTING\September\Loans_20180920.csv'. There are several possible reasons: -The file name or path does not exist. -The file is being used by another program". I went through and deleted all of the other excel files that I was testing except the ones in the September folder but I am still getting this error.

Is there a way I can modify this code so that I don't have to copy it 12 times for every month? I was thinking it would be nice if a text box was prompted where I entered the month I wanted to download. Either way... I have already copied it 12 times so it wouldn't be any extra work.

Original Code Reference: Dan Wagner (Copying worksheets from multiple workbooks into current workbook)

Here's the code I am working with:

```<code>Sub Stack_Overflow_Example()

Dim MyFile As String, MyFiles As String, FilePath As String
Dim erow As Long

Dim wbMaster As Workbook, wbTemp As Workbook
Dim wsMaster As Worksheet, wsTemp As Worksheet

FilePath = "S:\Actg\TESTING\September\"
MyFiles = "S:\Actg\TESTING\September\*.csv"
MyFile = Dir(MyFiles)

With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
End With

Set wbMaster = ThisWorkbook
Set wsMaster = wbMaster.Sheets("September")

Do While Len(MyFile) > 0

    If MyFile <> "master.xlsm" Then

        Set wbTemp = Workbooks.Open(Filename:=FilePath & MyFile, ReadOnly:=True)
        Set wsTemp = wbTemp.Sheets(1)

        With wsMaster

            erow = .Range("A" & .Rows.Count).End(xlUp).Row
            wsTemp.Range("A2:U88").Copy
            .Range("A" & erow).Offset(1, 0).PasteSpecial xlPasteValues

        End With

        wbTemp.Close False
        Set wsTemp = Nothing
        Set wbTemp = Nothing
    End If

    MyFile = Dir
Loop

With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
End With

End Sub
</code>```

Please let me know if you have additional questions.

答:
My scenario sounds a little different from yours, as each workbook I am copying data from has individual months in each of those workbooks as well as the master workbook, but this should get you on the right path.

Note that the code below assumes that there is a header row that should not be copied. If there is not then you will change the first row from 2 to 1 in the copy line. If you need to open files from multiple locations, you could add another loop for the number of locations before the file opening code block and have the MyFolder variable change for each location for each iteration of the loop.

```<code>Sub RefreshMasterWorkbookData()

'Enable Error Handling
On Error GoTo Oops

'Declare variables and objects
Dim WkBk As Workbook, WkShtMaster As Worksheet, WkShtUser As Worksheet, CopyToRow As Long, PasteAtRow As Long

'Turn off screen updating and calculation to improve process speed and turn off events to keep other code (such as Worksheet_Change) from being triggered
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

'Open all files in a given directory
Dim MyFolder As String, MyFile As String
MyFolder = "C:\MyFolder" 'OR: "\\NetworkServer\NetworkFolder"
MyFile = Dir(MyFolder & "\*.xlsm") '& "\*.xl*")
Do While MyFile <> ""
    Workbooks.Open FileName:=MyFolder & "\" & MyFile, ReadOnly:=True
    MyFile = Dir
Loop

For Each WkBk In Workbooks 'Loops through each open workbook
    If Not WkBk.Name = ThisWorkbook.Name Then 'If not this master workbook
        For Each WkShtUser In WkBk.Worksheets 'Loops through each worksheet in the current workbook
            Select Case WkShtUser.Name 'Worksheet name for Month
                Case "Jan" 'Jan is the worksheet name for the monthly tab/sheet in the users individual file
                    Set WkShtMaster = M_01 'M_01 is the CodeName of the monthly worksheet in Master file
                Case "Feb"
                    Set WkShtMaster = M_02
                Case "Mar"
                    Set WkShtMaster = M_03
                Case "Apr"
                    Set WkShtMaster = M_04
                Case "May"
                    Set WkShtMaster = M_05
                Case "Jun"
                    Set WkShtMaster = M_06
                Case "Jul"
                    Set WkShtMaster = M_07
                Case "Aug"
                    Set WkShtMaster = M_08
                Case "Sep"
                    Set WkShtMaster = M_09
                Case "Oct"
                    Set WkShtMaster = M_10
                Case "Nov"
                    Set WkShtMaster = M_11
                Case "Dec"
                    Set WkShtMaster = M_12
                Case Else
                    GoTo NextWkSht
            End Select

            PasteAtRow = WkShtMaster.Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row + 1 'find first empty row in master sheet for appropriate month

            With WkShtUser 'Clear autofilter, if on, and copy designated columns of data from row 2 through last row
                If .FilterMode = True Then .AutoFilterMode = False
                CopyToRow = .Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
                If CopyToRow = 1 Then GoTo EmptyWkSht
                .Range("A2", "Z" & CopyToRow).Copy 'Where "Z" is the lst column of data you want to copy
            End With
            WkShtMaster.Range("A" & PasteAtRow).PasteSpecial xlPasteValues 'Paste data to empty rows in master for appropriate month
EmptyWkSht:
            If Not WkShtMaster Is Nothing Then Set WkShtMaster = Nothing
            CopyToRow = 0
            PasteAtRow = 0
NextWkSht:
        Next
        WkBk.Saved = True
        WkBk.Close False
    End If
Next

Oops:
    If Err Then
        Debug.Print Err.Description
        MsgBox "Refresh Error:" & vbNewLine & vbNewLine & Err.Description, vbCritical, "Error..."
    Else
        MsgBox "Refresh Completed Successfully", vbInformation, "Refresh Complete..."
    End If

    Application.EnableEvents = True
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub
</code>```

Body:
The goal of this Macro is to combine data from multiple excel files from different months into one master excel file. I have created a tab for every month in the master excel file (see attached picture) that I would like the data to go to and stack on top of each other.

I found some helpful code that I got to work a few times but after modifications is now broken. A few issues that I think I need to resolve before it can work like I want are:

This code is built with a fixed range that gets copied. The excel files I am looking at will have ranges that are variable.

The code keeps breaking on the line that reads Set wbTemp = Workbooks.Open(Filename:=FilePath & MyFile, ReadOnly:=True). This could be because I am testing excel files in different month folders all that have the same name?

I am getting the following error: "Run-time error '1004': Microsoft Excel cannot access the file 'S:\Actg\TESTING\September\Loans_20180920.csv'. There are several possible reasons: -The file name or path does not exist. -The file is being used by another program". I went through and deleted all of the other excel files that I was testing except the ones in the September folder but I am still getting this error.

Is there a way I can modify this code so that I don't have to copy it 12 times for every month? I was thinking it would be nice if a text box was prompted where I entered the month I wanted to download. Either way... I have already copied it 12 times so it wouldn't be any extra work.

Original Code Reference: Dan Wagner (Copying worksheets from multiple workbooks into current workbook)

Here's the code I am working with:

Sub Stack_Overflow_Example()

Dim MyFile As String, MyFiles As String, FilePath As String
Dim erow As Long

Dim wbMaster As Workbook, wbTemp As Workbook
Dim wsMaster As Worksheet, wsTemp As Worksheet

FilePath = "S:\Actg\TESTING\September\"
MyFiles = "S:\Actg\TESTING\September\*.csv"
MyFile = Dir(MyFiles)

With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
End With

Set wbMaster = ThisWorkbook
Set wsMaster = wbMaster.Sheets("September")

Do While Len(MyFile) > 0

    If MyFile <> "master.xlsm" Then

        Set wbTemp = Workbooks.Open(Filename:=FilePath & MyFile, ReadOnly:=True)
        Set wsTemp = wbTemp.Sheets(1)

        With wsMaster

            erow = .Range("A" & .Rows.Count).End(xlUp).Row
            wsTemp.Range("A2:U88").Copy
            .Range("A" & erow).Offset(1, 0).PasteSpecial xlPasteValues

        End With

        wbTemp.Close False
        Set wsTemp = Nothing
        Set wbTemp = Nothing
    End If

    MyFile = Dir
Loop

With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
End With

End Sub

Please let me know if you have additional questions.

Body:
My scenario sounds a little different from yours, as each workbook I am copying data from has individual months in each of those workbooks as well as the master workbook, but this should get you on the right path.

Note that the code below assumes that there is a header row that should not be copied. If there is not then you will change the first row from 2 to 1 in the copy line. If you need to open files from multiple locations, you could add another loop for the number of locations before the file opening code block and have the MyFolder variable change for each location for each iteration of the loop.

Sub RefreshMasterWorkbookData()

'Enable Error Handling
On Error GoTo Oops

'Declare variables and objects
Dim WkBk As Workbook, WkShtMaster As Worksheet, WkShtUser As Worksheet, CopyToRow As Long, PasteAtRow As Long

'Turn off screen updating and calculation to improve process speed and turn off events to keep other code (such as Worksheet_Change) from being triggered
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

'Open all files in a given directory
Dim MyFolder As String, MyFile As String
MyFolder = "C:\MyFolder" 'OR: "\\NetworkServer\NetworkFolder"
MyFile = Dir(MyFolder & "\*.xlsm") '& "\*.xl*")
Do While MyFile <> ""
    Workbooks.Open FileName:=MyFolder & "\" & MyFile, ReadOnly:=True
    MyFile = Dir
Loop

For Each WkBk In Workbooks 'Loops through each open workbook
    If Not WkBk.Name = ThisWorkbook.Name Then 'If not this master workbook
        For Each WkShtUser In WkBk.Worksheets 'Loops through each worksheet in the current workbook
            Select Case WkShtUser.Name 'Worksheet name for Month
                Case "Jan" 'Jan is the worksheet name for the monthly tab/sheet in the users individual file
                    Set WkShtMaster = M_01 'M_01 is the CodeName of the monthly worksheet in Master file
                Case "Feb"
                    Set WkShtMaster = M_02
                Case "Mar"
                    Set WkShtMaster = M_03
                Case "Apr"
                    Set WkShtMaster = M_04
                Case "May"
                    Set WkShtMaster = M_05
                Case "Jun"
                    Set WkShtMaster = M_06
                Case "Jul"
                    Set WkShtMaster = M_07
                Case "Aug"
                    Set WkShtMaster = M_08
                Case "Sep"
                    Set WkShtMaster = M_09
                Case "Oct"
                    Set WkShtMaster = M_10
                Case "Nov"
                    Set WkShtMaster = M_11
                Case "Dec"
                    Set WkShtMaster = M_12
                Case Else
                    GoTo NextWkSht
            End Select

            PasteAtRow = WkShtMaster.Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row + 1 'find first empty row in master sheet for appropriate month

            With WkShtUser 'Clear autofilter, if on, and copy designated columns of data from row 2 through last row
                If .FilterMode = True Then .AutoFilterMode = False
                CopyToRow = .Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
                If CopyToRow = 1 Then GoTo EmptyWkSht
                .Range("A2", "Z" & CopyToRow).Copy 'Where "Z" is the lst column of data you want to copy
            End With
            WkShtMaster.Range("A" & PasteAtRow).PasteSpecial xlPasteValues 'Paste data to empty rows in master for appropriate month
EmptyWkSht:
            If Not WkShtMaster Is Nothing Then Set WkShtMaster = Nothing
            CopyToRow = 0
            PasteAtRow = 0
NextWkSht:
        Next
        WkBk.Saved = True
        WkBk.Close False
    End If
Next

Oops:
    If Err Then
        Debug.Print Err.Description
        MsgBox "Refresh Error:" & vbNewLine & vbNewLine & Err.Description, vbCritical, "Error..."
    Else
        MsgBox "Refresh Completed Successfully", vbInformation, "Refresh Complete..."
    End If

    Application.EnableEvents = True
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub


问:
EOutOfResources exception when trying to restore tray icon
I'm getting an EOutOfResources exception 'Cannot remove shell notification icon' when trying to implement code to restore the tray icon after an Explorer crash/restart. My code is based on the old solution found here. The exception occurs when trying to hide the trayicon. Why does the Delphi XE code below not work?</p>

```<code>unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ImgList, ExtCtrls;

type
  TForm1 = class(TForm)
    TrayIcon1: TTrayIcon;
    ImageListTray: TImageList;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  protected
    procedure WndProc(var Message: TMessage); Override;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  msgTaskbarRestart : Cardinal; {custom systemwide message}

implementation

{$R *.dfm}

//ensure systray icon recreated on explorer crash
procedure TForm1.FormCreate(Sender: TObject);
begin
  msgTaskbarRestart := RegisterWindowMessage('TaskbarCreated');
end;

procedure TForm1.WndProc(var Message: TMessage);
begin
  if (msgTaskbarRestart <> 0) and (Message.Msg = msgTaskbarRestart) then begin
    TrayIcon1.Visible := False; {Destroy the systray icon here}//EOutOfResources exception here
    TrayIcon1.Visible := True;  {Replace the systray icon}
    Message.Result := 1;
  end;
  inherited WndProc(Message);
end;

end.
</code>```

答:
The TTrayIcon.Visible property setter raises EOutOfResources when a NIM_DELETE request fails:

procedure TCustomTrayIcon.SetVisible(Value: Boolean);
begin
  if FVisible <> Value then
  begin
    FVisible := Value;
    ...

    if not (csDesigning in ComponentState) then
    begin
      if FVisible then
        ...
      else if not (csLoading in ComponentState) then
      begin
        if not Refresh(NIM_DELETE) then
          raise EOutOfResources.Create(STrayIconRemoveError); // <-- HERE
      end;
      ...
    end;
  end;
end;
```

<p>Where <code>Refresh()</code> is just a call to the Win32 <code>Shell_NotifyIcon()</code> function:</p>

<pre class="lang-pascal prettyprint-override"><code>function TCustomTrayIcon.Refresh(Message: Integer): Boolean;
  ...
begin
  Result := Shell_NotifyIcon(Message, FData);
  ...
end;
</code>```

When you receive the TaskbarCreated message, your previous icons are no longer present in the Taskbar, so Shell_NotifyIcon(NIM_DELETE) returns False.  When the Taskbar is (re-)created, you are not supposed to try to remove old icons at all, only re-add new icons with Shell_NotifyIcon(NIM_ADD) as needed.

TTrayIcon has a public Refresh() method, but that uses NIM_MODIFY instead of NIM_ADD, so that will not work in this situation, either:

procedure TCustomTrayIcon.Refresh;
begin
  if not (csDesigning in ComponentState) then
  begin
    ...
    if Visible then
      Refresh(NIM_MODIFY);
  end;
end;
```

<p>However, you don't actually need to handle the <code>TaskbarCreated</code> message manually when using <code>TTrayIcon</code>, because it already handles that message internally for you, and it will call <code>Shell_NotifyIcon(NIM_ADD)</code> if <code>Visible=True</code>:</p>

<pre class="lang-pascal prettyprint-override"><code>procedure TCustomTrayIcon.WindowProc(var Message: TMessage);
  ...
begin
  case Message.Msg of
    ...
  else
    if (Cardinal(Message.Msg) = RM_TaskBarCreated) and Visible then
      Refresh(NIM_ADD); // <-- HERE
  end;
end;

...

initialization
  ...
  TCustomTrayIcon.RM_TaskBarCreated := RegisterWindowMessage('TaskbarCreated');
end.
</code>```

If, for some reason, that is not working correctly, and/or you need to handle TaskbarCreated manually, then I would suggest calling the protected TCustomTrayIcon.Refresh() method directly, eg:

type
  TTrayIconAccess = class(TTrayIcon)
  end;

procedure TForm1.WndProc(var Message: TMessage);
begin
  if (msgTaskbarRestart <> 0) and (Message.Msg = msgTaskbarRestart) then begin
    if TrayIcon1.Visible then begin
      // TrayIcon1.Refresh;
      TTrayIconAccess(TrayIcon1).Refresh(NIM_ADD);
    end;
    Message.Result := 1;
  end;
  inherited WndProc(Message);
end;
```

Otherwise, simply don't use TTrayIcon at all.  It is known to be buggy.  I have seen a lot of people have a lot of problems with TTrayIcon over the years.  I would suggest using Shell_NotifyIcon() directly instead.  I have never had any problems using it myself.

Body:
I'm getting an EOutOfResources exception 'Cannot remove shell notification icon' when trying to implement code to restore the tray icon after an Explorer crash/restart. My code is based on the old solution found here. The exception occurs when trying to hide the trayicon. Why does the Delphi XE code below not work?

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ImgList, ExtCtrls;

type
  TForm1 = class(TForm)
    TrayIcon1: TTrayIcon;
    ImageListTray: TImageList;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  protected
    procedure WndProc(var Message: TMessage); Override;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  msgTaskbarRestart : Cardinal; {custom systemwide message}

implementation

{$R *.dfm}

//ensure systray icon recreated on explorer crash
procedure TForm1.FormCreate(Sender: TObject);
begin
  msgTaskbarRestart := RegisterWindowMessage('TaskbarCreated');
end;

procedure TForm1.WndProc(var Message: TMessage);
begin
  if (msgTaskbarRestart <> 0) and (Message.Msg = msgTaskbarRestart) then begin
    TrayIcon1.Visible := False; {Destroy the systray icon here}//EOutOfResources exception here
    TrayIcon1.Visible := True;  {Replace the systray icon}
    Message.Result := 1;
  end;
  inherited WndProc(Message);
end;

end.

Body:
The TTrayIcon.Visible property setter raises EOutOfResources when a NIM_DELETE request fails:

procedure TCustomTrayIcon.SetVisible(Value: Boolean);
begin
  if FVisible <> Value then
  begin
    FVisible := Value;
    ...

    if not (csDesigning in ComponentState) then
    begin
      if FVisible then
        ...
      else if not (csLoading in ComponentState) then
      begin
        if not Refresh(NIM_DELETE) then
          raise EOutOfResources.Create(STrayIconRemoveError); // <-- HERE
      end;
      ...
    end;
  end;
end;

Where Refresh() is just a call to the Win32 Shell_NotifyIcon() function:

function TCustomTrayIcon.Refresh(Message: Integer): Boolean;
  ...
begin
  Result := Shell_NotifyIcon(Message, FData);
  ...
end;

When you receive the TaskbarCreated message, your previous icons are no longer present in the Taskbar, so Shell_NotifyIcon(NIM_DELETE) returns False.  When the Taskbar is (re-)created, you are not supposed to try to remove old icons at all, only re-add new icons with Shell_NotifyIcon(NIM_ADD) as needed.

TTrayIcon has a public Refresh() method, but that uses NIM_MODIFY instead of NIM_ADD, so that will not work in this situation, either:

procedure TCustomTrayIcon.Refresh;
begin
  if not (csDesigning in ComponentState) then
  begin
    ...
    if Visible then
      Refresh(NIM_MODIFY);
  end;
end;

However, you don't actually need to handle the TaskbarCreated message manually when using TTrayIcon, because it already handles that message internally for you, and it will call Shell_NotifyIcon(NIM_ADD) if Visible=True:

procedure TCustomTrayIcon.WindowProc(var Message: TMessage);
  ...
begin
  case Message.Msg of
    ...
  else
    if (Cardinal(Message.Msg) = RM_TaskBarCreated) and Visible then
      Refresh(NIM_ADD); // <-- HERE
  end;
end;

...

initialization
  ...
  TCustomTrayIcon.RM_TaskBarCreated := RegisterWindowMessage('TaskbarCreated');
end.

If, for some reason, that is not working correctly, and/or you need to handle TaskbarCreated manually, then I would suggest calling the protected TCustomTrayIcon.Refresh() method directly, eg:

type
  TTrayIconAccess = class(TTrayIcon)
  end;

procedure TForm1.WndProc(var Message: TMessage);
begin
  if (msgTaskbarRestart <> 0) and (Message.Msg = msgTaskbarRestart) then begin
    if TrayIcon1.Visible then begin
      // TrayIcon1.Refresh;
      TTrayIconAccess(TrayIcon1).Refresh(NIM_ADD);
    end;
    Message.Result := 1;
  end;
  inherited WndProc(Message);
end;

Otherwise, simply don't use TTrayIcon at all.  It is known to be buggy.  I have seen a lot of people have a lot of problems with TTrayIcon over the years.  I would suggest using Shell_NotifyIcon() directly instead.  I have never had any problems using it myself.


问:
Remove empty list elements in R
Since most of the words I search return an empty list, I'd like to keep only those which give a result.

```<code>> assocs<-findAssocs(dtm,names(freq[1:5]),0.5)
> assocs
$cuffie
numeric(0)

$auricolari
    colora  controlli interrotta operazione      verrà
      0.52       0.52       0.51       0.51       0.50

$qualità
numeric(0)

$suono
numeric(0)

$ricarica
         colora      interrotta      operazione           verrà     addentrarmi          attira
           0.57            0.56            0.55            0.54            0.53            0.53
       attirano        avanzati  consigliarveli      consultato        iniziare   interromperne
           0.53            0.53            0.53            0.53            0.53            0.53
    inutilmente        mettersi   negativamente      reinserire       ritornare siribixbygoogle
           0.53            0.53            0.53            0.53            0.53            0.53
      specifico         ventina       collocare
           0.53            0.53            0.52
</code>```

Desired Output:

```<code>> assocs

$auricolari
    colora  controlli interrotta operazione      verrà
      0.52       0.52       0.51       0.51       0.50

$ricarica
         colora      interrotta      operazione           verrà     addentrarmi          attira
           0.57            0.56            0.55            0.54            0.53            0.53
       attirano        avanzati  consigliarveli      consultato        iniziare   interromperne
           0.53            0.53            0.53            0.53            0.53            0.53
    inutilmente        mettersi   negativamente      reinserire       ritornare siribixbygoogle
           0.53            0.53            0.53            0.53            0.53            0.53
      specifico         ventina       collocare
           0.53            0.53            0.52
</code>```

By doing so I could search on more words without having returned an enormous list.

The library used for findassocs() is  tm.

The output is:

```<code>> class(assocs)
[1] "list"
</code>```

I have tried this:

```<code>for (i in 1:5){
  if (length(assocs[[i]])==0){
    new_assocs[j]=assocs[i]
    j=j+1
  }
}
</code>```

But the output was like this:

```<code>> new_assocs
[[1]]
numeric(0)

[[2]]
numeric(0)

[[3]]
numeric(0)

[[4]]
numeric(0)

[[5]]
numeric(0)

</code>```

Thank you all in advance.

答:
The function lengths() returns the number of elements (i.e., the length) for each element in a list. So you can do this:

```<code>assocs[lengths(assocs) > 1]
</code>```

This is, of course, basically the same answer as Daniel O's, but it is somewhat simpler and, for large lists, more efficient.

Title: Remove empty list elements in R

Body:
Since most of the words I search return an empty list, I'd like to keep only those which give a result.

> assocs<-findAssocs(dtm,names(freq[1:5]),0.5)
> assocs
$cuffie
numeric(0)

$auricolari
    colora  controlli interrotta operazione      verrà
      0.52       0.52       0.51       0.51       0.50

$qualità
numeric(0)

$suono
numeric(0)

$ricarica
         colora      interrotta      operazione           verrà     addentrarmi          attira
           0.57            0.56            0.55            0.54            0.53            0.53
       attirano        avanzati  consigliarveli      consultato        iniziare   interromperne
           0.53            0.53            0.53            0.53            0.53            0.53
    inutilmente        mettersi   negativamente      reinserire       ritornare siribixbygoogle
           0.53            0.53            0.53            0.53            0.53            0.53
      specifico         ventina       collocare
           0.53            0.53            0.52

Desired Output:

> assocs

$auricolari
    colora  controlli interrotta operazione      verrà
      0.52       0.52       0.51       0.51       0.50

$ricarica
         colora      interrotta      operazione           verrà     addentrarmi          attira
           0.57            0.56            0.55            0.54            0.53            0.53
       attirano        avanzati  consigliarveli      consultato        iniziare   interromperne
           0.53            0.53            0.53            0.53            0.53            0.53
    inutilmente        mettersi   negativamente      reinserire       ritornare siribixbygoogle
           0.53            0.53            0.53            0.53            0.53            0.53
      specifico         ventina       collocare
           0.53            0.53            0.52

By doing so I could search on more words without having returned an enormous list.

The library used for findassocs() is  tm.

The output is:

> class(assocs)
[1] "list"

I have tried this:

for (i in 1:5){
  if (length(assocs[[i]])==0){
    new_assocs[j]=assocs[i]
    j=j+1
  }
}

But the output was like this:

> new_assocs
[[1]]
numeric(0)

[[2]]
numeric(0)

[[3]]
numeric(0)

[[4]]
numeric(0)

[[5]]
numeric(0)

Thank you all in advance.

Body:
The function lengths() returns the number of elements (i.e., the length) for each element in a list. So you can do this:

assocs[lengths(assocs) > 1]

This is, of course, basically the same answer as Daniel O's, but it is somewhat simpler and, for large lists, more efficient.


问:
Javascript - Loop string until null character found
I want to iterate through a string until a null character is found (\0), like how we do in C language. I have listed down the steps which I have tried below.

```<code>let exampleValue = 'abcdef';
let i = 0;

// Trial 1
while (exampleValue[i] !== '\0') {
  i++;
  // This seems to go on infinitely
}

// Trial 2
while (exampleValue[i] !== '\0'.charCodeAt(0)) {
  i++;
  // This seems to go on infinitely
}

// Trial 3
while (exampleValue[i] !== \0) {
  i++;
  // This throws an invalid character error
}

// Trial 4
while (exampleValue[i] !== undefined) {
  i++;
  // This seems to work
}
</code>```

Based on the above samples, Trial 4 seems to work. Can I continue using Trial 4 for my desired output or is there a better way to solve my problem?

EDIT:
I apologize for not specifying my problem, I want to print each letter of the string by iterating through it without using exampleValue.length

EDIT 2:
After I read tadman's comment, I got to know Javascript's do not terminate their string using a null character but instead it stores it's keeps track of it characters and stores the length seperately.

答:
If you just want to count the length then just do exampleValue.length

let exampleValue = 'abcdef';
let i = exampleValue.length;
console.log(i);```
</div>
</div>
</p>

<p>Or if you want to perform some logic using that char, you can try:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let exampleValue = 'abcdef';
let i = 0;

exampleValue.split('').forEach(c => {
    console.log(c);
    i++;
    // Your logic here.
});

console.log(i);</code>```

Or using plain for loop:

let exampleValue = 'abcdef';
let i = 0;

for (let x = 0; x < exampleValue.length; x++) {
  console.log(exampleValue.charAt(i));
  i++;
  // Your logic here.
}

console.log(i);```

Body:
I want to iterate through a string until a null character is found (\0), like how we do in C language. I have listed down the steps which I have tried below.

let exampleValue = 'abcdef';
let i = 0;

// Trial 1
while (exampleValue[i] !== '\0') {
  i++;
  // This seems to go on infinitely
}

// Trial 2
while (exampleValue[i] !== '\0'.charCodeAt(0)) {
  i++;
  // This seems to go on infinitely
}

// Trial 3
while (exampleValue[i] !== \0) {
  i++;
  // This throws an invalid character error
}

// Trial 4
while (exampleValue[i] !== undefined) {
  i++;
  // This seems to work
}

Based on the above samples, Trial 4 seems to work. Can I continue using Trial 4 for my desired output or is there a better way to solve my problem?

EDIT:
I apologize for not specifying my problem, I want to print each letter of the string by iterating through it without using exampleValue.length

EDIT 2:
After I read tadman's comment, I got to know Javascript's do not terminate their string using a null character but instead it stores it's keeps track of it characters and stores the length seperately.

Body:
If you just want to count the length then just do exampleValue.length

let exampleValue = 'abcdef';
let i = exampleValue.length;
console.log(i);

Or if you want to perform some logic using that char, you can try:

let exampleValue = 'abcdef';
let i = 0;

exampleValue.split('').forEach(c => {
    console.log(c);
    i++;
    // Your logic here.
});

console.log(i);

Or using plain for loop:

let exampleValue = 'abcdef';
let i = 0;

for (let x = 0; x < exampleValue.length; x++) {
  console.log(exampleValue.charAt(i));
  i++;
  // Your logic here.
}

console.log(i);


问:
Ansible fetching Stdout key value
I need some help regarding, how to fetch specific value using Ansible

My task:

- name: 'check Describe Information'
  debug:
  var: describeresult.stdout
```

<p>I need IP address value from below stdout, what should I put in debug var to fetch IP address</p>

```TASK [check Describe Information] **********************************************
task path: /home/tom/Getipaddress.yml:28
ok: [127.0.0.1] => {
    "describeresult.stdout": {
        "failures": [],
        "tasks": [
            {
                "attachments": [
                    {
                        "details": [
                            {
                                "name": "subnetId",
                                "value": "subnet-xxxxxxxxxxxxxx"
                            },
                            {
                                "name": "networkInterfaceId",
                                "value": "eni-xxxxxxxxxxxxxxxx"
                            },
                            {
                                "name": "macAddress",
                                "value": "xxxxxxxxxxxxxxxxxx"
                            },
                            {
                                "name": "privateIPv4Address",
                                "value": "xxxxxxxxxxxxxxxxxx"
                            }
```

Plus I am using AWS ECS command to generate the above output with --output as a JSON not sure how to use --query to filter or fetch above IP address only

答:
You can use something like this for getting private IP address only
"{{describeresult.stdout['tasks'][0]['attachments'][0]['details'][3]['value']}}"

The above might have slight syntax issues but should work.

I have done something like this earlier for ec2_group_info module in ansible

You can start off by generating output in pieces describeresult.stdout['tasks'] should return JSON for the task attribute.
[0] indicates the first element when there is a box bracket for a JSON implying more than one element/list.
Let me know how it goes.

Title: Ansible fetching Stdout key value

Body:
I need some help regarding, how to fetch specific value using Ansible

My task:

- name: 'check Describe Information'
  debug:
  var: describeresult.stdout

I need IP address value from below stdout, what should I put in debug var to fetch IP address

TASK [check Describe Information] **********************************************
task path: /home/tom/Getipaddress.yml:28
ok: [127.0.0.1] => {
    "describeresult.stdout": {
        "failures": [],
        "tasks": [
            {
                "attachments": [
                    {
                        "details": [
                            {
                                "name": "subnetId",
                                "value": "subnet-xxxxxxxxxxxxxx"
                            },
                            {
                                "name": "networkInterfaceId",
                                "value": "eni-xxxxxxxxxxxxxxxx"
                            },
                            {
                                "name": "macAddress",
                                "value": "xxxxxxxxxxxxxxxxxx"
                            },
                            {
                                "name": "privateIPv4Address",
                                "value": "xxxxxxxxxxxxxxxxxx"
                            }

Plus I am using AWS ECS command to generate the above output with --output as a JSON not sure how to use --query to filter or fetch above IP address only


问:
ERROR: no PostgreSQL user name specified in startup packet
I'm rocking a Phoenix app, and when I try to run mix ecto.migrate, I encounter the following error:

```<code>GenServer #PID<0.181.0> terminating
** (Postgrex.Error) FATAL (invalid_authorization_specification): no PostgreSQL user name specified in startup packet
    (db_connection) lib/db_connection/connection.ex:148: DBConnection.Connection.connect/2
    (connection) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
Last message: nil
State: Postgrex.Protocol
</code>```

There's some Q&A out there that touches on this particular error, but I haven't found them to be useful, unfortunately. So I turn here!

Additional environment info: Mac OS X, Postgres.app, PG version 9.5

答:
Double check the typo of your environment variable, in my case I used PSQLS_USERNAME (extra S because I renamed from POSTGRES to PSQL to make it shorter) as environment variable and PSQL_USERNAME  in the connection row.

So I ended-up with a block of code that was properly formatted except the typo in the environment variable name (they are not underlined by the Code Editor).

Body:
I'm rocking a Phoenix app, and when I try to run mix ecto.migrate, I encounter the following error:

GenServer #PID<0.181.0> terminating
** (Postgrex.Error) FATAL (invalid_authorization_specification): no PostgreSQL user name specified in startup packet
    (db_connection) lib/db_connection/connection.ex:148: DBConnection.Connection.connect/2
    (connection) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
Last message: nil
State: Postgrex.Protocol

There's some Q&A out there that touches on this particular error, but I haven't found them to be useful, unfortunately. So I turn here!

Additional environment info: Mac OS X, Postgres.app, PG version 9.5


问:
Adding multiple annotations when faceting
I'm having trouble adding multiple annotations (using vectors) to a plot with facets.

For example:

```<code>library(tidyverse) # ggplot2_3.3.0

tibble(t = 1:100) %>%
  crossing(id = LETTERS[1:2]) %>%
  group_by(id) %>%
  mutate(y = cumsum(rnorm(n()))) %>%
  ggplot(aes(t, y)) + # perhaps add `group = id` if you don't facet by `id`
  facet_wrap(vars(id)) + # (1)
  annotate('rect', xmin = 20, xmax = 30, ymin = -Inf, ymax = Inf, fill = 'grey60') + # (2)
  annotate('rect', xmin = 30, xmax = 40, ymin = -Inf, ymax = Inf, fill = 'grey70') + # (2)
  annotate('rect', xmin = 40, xmax = 50, ymin = -Inf, ymax = Inf, fill = 'grey80') + # (2)
  annotate('rect', xmin = 50, xmax = 60, ymin = -Inf, ymax = Inf, fill = 'grey90') + # (2)
  # annotate('rect', ymin = -Inf, ymax = Inf,                # (3)
  #          xmin = seq(20, by=10, len=4),                   # (3)
  #          xmax = seq(30, by=10, len=4),                   # (3)
  #          fill = paste0('grey', seq(60, by=10, len=4))) + # (3)
  geom_line() +
  theme_light()
</code>```

The above code produces the desired plot (in particular, I want the same annotation on all facets).  However, the annotate command is repeated four times; furthermore the help page for annotate says "the properties of the geoms are ... passed in as vectors".
So a natural thing to try is to comment out lines (2), and uncomment lines (3).
Unfortunately this generates the error

Error: Aesthetics must be either length 1 or the same as the data (8): fill
```

Note that if, in addition, you comment out line (1) (and optionally add group = id to the aesthetics) then it does not generate an error.

答:
For a discussion of this behaviour of ggplot2 see gihub. As the issue was closed and as far as I get it there is nothing you can do abozt that by using annotate. However, to achieve what you want you can simply use geom_rect like so:

library(tidyverse) # ggplot2_3.3.0

df_annotate <- data.frame(
  xmin = seq(20, 50, 10),
  xmax = seq(30, 60, 10),
  ymin = -Inf,
  ymax = Inf,
  fill = paste0("grey", seq(60, 90, 10))
)

tibble(t = 1:100) %>%
  crossing(id = LETTERS[1:4]) %>%
  group_by(id) %>%
  mutate(y = cumsum(rnorm(n()))) %>%
  ggplot() +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill), data = df_annotate) +
  geom_line(aes(t, y)) +
  scale_fill_identity() +
  facet_wrap(vars(id)) +
  theme_light()
```

<p><img src="https://i.imgur.com/OMJ21Ug.png" alt=""></p>

<p><sup>Created on 2020-05-28 by the reprex package (v0.3.0)</sup></p>

<p><strong>Edit</strong> Using <code>ggnewscale</code> it's possible to have a second or ... fill scale:</p>

<pre class="lang-r prettyprint-override"><code>library(tidyverse) # ggplot2_3.3.0
library(ggnewscale)

df_annotate <- data.frame(
  xmin = seq(20, 50, 10),
  xmax = seq(30, 60, 10),
  ymin = -Inf,
  ymax = Inf,
  fill = paste0("grey", seq(60, 90, 10))
)

df <- tibble(t = 1:100) %>%
  crossing(id = LETTERS[1:4]) %>%
  group_by(id) %>%
  mutate(y = cumsum(rnorm(n())))

ggplot() +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill), data = df_annotate) +
  scale_fill_identity() +
  new_scale_fill() +
  geom_area(data = df, aes(t, y, fill = id)) +
  facet_wrap(vars(id)) +
  theme_light()
</code>```

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
I'm having trouble adding multiple annotations (using vectors) to a plot with facets.

For example:

library(tidyverse) # ggplot2_3.3.0

tibble(t = 1:100) %>%
  crossing(id = LETTERS[1:2]) %>%
  group_by(id) %>%
  mutate(y = cumsum(rnorm(n()))) %>%
  ggplot(aes(t, y)) + # perhaps add `group = id` if you don't facet by `id`
  facet_wrap(vars(id)) + # (1)
  annotate('rect', xmin = 20, xmax = 30, ymin = -Inf, ymax = Inf, fill = 'grey60') + # (2)
  annotate('rect', xmin = 30, xmax = 40, ymin = -Inf, ymax = Inf, fill = 'grey70') + # (2)
  annotate('rect', xmin = 40, xmax = 50, ymin = -Inf, ymax = Inf, fill = 'grey80') + # (2)
  annotate('rect', xmin = 50, xmax = 60, ymin = -Inf, ymax = Inf, fill = 'grey90') + # (2)
  # annotate('rect', ymin = -Inf, ymax = Inf,                # (3)
  #          xmin = seq(20, by=10, len=4),                   # (3)
  #          xmax = seq(30, by=10, len=4),                   # (3)
  #          fill = paste0('grey', seq(60, by=10, len=4))) + # (3)
  geom_line() +
  theme_light()

The above code produces the desired plot (in particular, I want the same annotation on all facets).  However, the annotate command is repeated four times; furthermore the help page for annotate says "the properties of the geoms are ... passed in as vectors".
So a natural thing to try is to comment out lines (2), and uncomment lines (3).
Unfortunately this generates the error

Error: Aesthetics must be either length 1 or the same as the data (8): fill

Note that if, in addition, you comment out line (1) (and optionally add group = id to the aesthetics) then it does not generate an error.

Body:
For a discussion of this behaviour of ggplot2 see gihub. As the issue was closed and as far as I get it there is nothing you can do abozt that by using annotate. However, to achieve what you want you can simply use geom_rect like so:

library(tidyverse) # ggplot2_3.3.0

df_annotate <- data.frame(
  xmin = seq(20, 50, 10),
  xmax = seq(30, 60, 10),
  ymin = -Inf,
  ymax = Inf,
  fill = paste0("grey", seq(60, 90, 10))
)

tibble(t = 1:100) %>%
  crossing(id = LETTERS[1:4]) %>%
  group_by(id) %>%
  mutate(y = cumsum(rnorm(n()))) %>%
  ggplot() +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill), data = df_annotate) +
  geom_line(aes(t, y)) +
  scale_fill_identity() +
  facet_wrap(vars(id)) +
  theme_light()

Created on 2020-05-28 by the reprex package (v0.3.0)

Edit Using ggnewscale it's possible to have a second or ... fill scale:

library(tidyverse) # ggplot2_3.3.0
library(ggnewscale)

df_annotate <- data.frame(
  xmin = seq(20, 50, 10),
  xmax = seq(30, 60, 10),
  ymin = -Inf,
  ymax = Inf,
  fill = paste0("grey", seq(60, 90, 10))
)

df <- tibble(t = 1:100) %>%
  crossing(id = LETTERS[1:4]) %>%
  group_by(id) %>%
  mutate(y = cumsum(rnorm(n())))

ggplot() +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill), data = df_annotate) +
  scale_fill_identity() +
  new_scale_fill() +
  geom_area(data = df, aes(t, y, fill = id)) +
  facet_wrap(vars(id)) +
  theme_light()

Created on 2020-05-29 by the reprex package (v0.3.0)


问:
Maintaining a Count of Distinct Strings with a Two-Column SQL Server Table
I want to use a two-column table to maintain instance counts for distinct strings.

The first column will contain a particular string, and the second will contain a count for it.

For example, two rows might be:

"CAT", 1
"DOG", 3

I'll write a stored procedure to which the caller passes a string. That stored procedure must first determine how many existing instances are in the database. Then it must update the database to have one more than that.

How can I write my stored procedure so that multiple clients can call it at the same time without overwriting each other's work?

答:
You can use an update statement with an output clause:</p>

```<code>  update #test
  set myCount = myCount + 1
  where myString = 'dog'
  output deleted.myCount ;
</code>```

Body:
You can use an update statement with an output clause:

  update #test
  set myCount = myCount + 1
  where myString = 'dog'
  output deleted.myCount ;


问:
How to send data through ajax function in JavaScript
i am trying to create an ajax favorite button in php similar to instagram and twitter.

my code seems to be fine and i am doing everything correctly and tried to get it working this way:

php code:

```<code>       $user_id = $_SESSION['active_user_id'];
        extract($_POST);
        extract($_GET);
        if(isset($_GET['message']))
        {
            $id=$_GET['message'];

            $q=$db->prepare("SELECT msgid,date,text

            FROM messages
            WHERE to_id=? and msgid=?");
            $q->bindValue(1,$user_id);
            $q->bindValue(2,$id);
            $q->execute();
            $row2=$q->fetch();
            $d=$row2['date'];

            $fav_questionq=$db->prepare("SELECT *
            FROM messages
            LEFT JOIN users
            ON messages.to_id=users.id
            WHERE users.id=? AND messages.msgid=?

            ");
            $fav_questionq->bindValue(1,$user_id);
            $fav_questionq->bindValue(2,$id);
            $fav_questionq->execute();
            $frow=$fav_questionq->fetch();

            $fquestion= $frow['text'];

            $result = $db->prepare("SELECT * FROM fav_messages
                                WHERE username=? AND message=?");
            $result-bindValue(1,$user_id);
            $result-bindValue(2,$id);
            $result->execute();

        if($result->rowCount()== 1 )
        {
            $deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
            $deletequery->bindValue(1,$id);
            $deletequery->execute();
        echo("<script>location.href = 'index.php?a=recieved';</script>");
        }
        else
        {
        $insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
        $insertquery->bindValue(1,$user_id);
        $insertquery->bindValue(2,$id);
        $insertquery->bindValue(3,$fquestion);
        $insertquery->bindValue(4,$d);
        $insertquery-execute();
        }
        echo("<script>location.href = 'index.php?a=recieved';</script>");
        }
</code>```

javascript code:

```<code>          <script>
            function GetXmlHttpObject() {
        var xmlHttp=null;
        try
            {
            // Firefox, Opera 8.0+, Safari
            xmlHttp=new XMLHttpRequest();
            }
        catch (e)
            {
            // Internet Explorer
            try
                { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
            catch (e)
                { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
            }
        return xmlHttp;
    }
   function ajaxfav(){
        var xmlHttp=GetXmlHttpObject();
        var url="favorite.php?message="+document.msgidform.fav_message.value;
        xmlHttp.onreadystatechange=function(){
            if(xmlHttp.readyState==4){
            alert("Message is favorited");

            }
        }
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);

    }
  </script>
</code>```

HTML form and link code:

```<code>        <form name="msgidform" method="post">
            <input type="hidden" name="fav_message" id="" <?php echo "value= '$msg_id'"; ?>></p>
        </form>

        <a class="msg-icon" href="" onclick="ajaxfav();"><img
                src="images/linedfav.png" id='img'></img></a>
</code>```

but i kept getting an error in the console that reads:

"Uncaught TypeError: Cannot read property 'value' of undefined
    at ajaxfav" but i've fixed it and now it immediately goes to the alert message, but nothing is inserted into the database, meaning that the data was not sent to the php file.
can someone advise me on what i can do?
network tab of the ajax call

please i would appreciate any help or suggestion. the php file is called but does not insert anything into the database.

答:
You can use
document.msgidform.elements['fav_message'].value

in your ajaxfav() function to get name field value.

Body:
i am trying to create an ajax favorite button in php similar to instagram and twitter.

my code seems to be fine and i am doing everything correctly and tried to get it working this way:

php code:

       $user_id = $_SESSION['active_user_id'];
        extract($_POST);
        extract($_GET);
        if(isset($_GET['message']))
        {
            $id=$_GET['message'];

            $q=$db->prepare("SELECT msgid,date,text

            FROM messages
            WHERE to_id=? and msgid=?");
            $q->bindValue(1,$user_id);
            $q->bindValue(2,$id);
            $q->execute();
            $row2=$q->fetch();
            $d=$row2['date'];

            $fav_questionq=$db->prepare("SELECT *
            FROM messages
            LEFT JOIN users
            ON messages.to_id=users.id
            WHERE users.id=? AND messages.msgid=?

            ");
            $fav_questionq->bindValue(1,$user_id);
            $fav_questionq->bindValue(2,$id);
            $fav_questionq->execute();
            $frow=$fav_questionq->fetch();

            $fquestion= $frow['text'];

            $result = $db->prepare("SELECT * FROM fav_messages
                                WHERE username=? AND message=?");
            $result-bindValue(1,$user_id);
            $result-bindValue(2,$id);
            $result->execute();

        if($result->rowCount()== 1 )
        {
            $deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
            $deletequery->bindValue(1,$id);
            $deletequery->execute();
        echo("");
        }
        else
        {
        $insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
        $insertquery->bindValue(1,$user_id);
        $insertquery->bindValue(2,$id);
        $insertquery->bindValue(3,$fquestion);
        $insertquery->bindValue(4,$d);
        $insertquery-execute();
        }
        echo("");
        }

javascript code:

HTML form and link code:

        <form name="msgidform" method="post">
            <input type="hidden" name="fav_message" id="" <?php echo "value= '$msg_id'"; ?>>

        </form>

but i kept getting an error in the console that reads:

"Uncaught TypeError: Cannot read property 'value' of undefined
    at ajaxfav" but i've fixed it and now it immediately goes to the alert message, but nothing is inserted into the database, meaning that the data was not sent to the php file.
can someone advise me on what i can do?
network tab of the ajax call

please i would appreciate any help or suggestion. the php file is called but does not insert anything into the database.


问:
How to change a range of array with one value Javascript?
I have an array like below let's say

```<code>var myArray = ["1", "", "", "2","3","","","8"];
</code>```

And I want to fill each " " value with previous not null value

According to that expectation should be like below

```<code>var myArray = ["1", "2", "2", "2","3","8","8","8"];
</code>```

Here what I tried but didn't work

    var myArray = ["1", "", "", "2","3","","","8"];

    function myFunction() {
      let currentEl=myArray [0];
      let prevIndex=0;
      fruits.map((e,a)=>{
      if(e!="" && myArray[a-1]==""){
       currentEl=e;
       let interval=arrayGenerate(a-currentIndex-1,currentEl);
       fruits.splice(currentIndex-1, currentEl+1, interval);
       currentIndex=a;
      }
      })
    }
    function arrayGenerate(iteration,value){
      let arr=[];
      for(var i=0;i<iteration;i++){
      arr.push(value);
      }
      return arr;
    }

console.log(myArray)```

答:
You can make use of a stack array to stack indices of null items and then unstack them whenever you encounter a non null item in myArray. (stack is not a reserved keyword so you can call it anything) :</p>

```<code>var stack = []
for(var i = 0; i < myArray.length; i++){
   if(myArray[i] === "")
    stack.push(i);
   else if(stack.length !== 0){
       for(var j = stack.length - 1 ; j > =0; j--){
         myArray[stack[j]] = myArray[i];
         stack.splice(j,1);
       }
   }
}

</code>```

Body:
I have an array like below let's say

var myArray = ["1", "", "", "2","3","","","8"];

And I want to fill each " " value with previous not null value

According to that expectation should be like below

var myArray = ["1", "2", "2", "2","3","8","8","8"];

Here what I tried but didn't work

    var myArray = ["1", "", "", "2","3","","","8"];

    function myFunction() {
      let currentEl=myArray [0];
      let prevIndex=0;
      fruits.map((e,a)=>{
      if(e!="" && myArray[a-1]==""){
       currentEl=e;
       let interval=arrayGenerate(a-currentIndex-1,currentEl);
       fruits.splice(currentIndex-1, currentEl+1, interval);
       currentIndex=a;
      }
      })
    }
    function arrayGenerate(iteration,value){
      let arr=[];
      for(var i=0;i<iteration;i++){
      arr.push(value);
      }
      return arr;
    }

console.log(myArray)

Body:
You can make use of a stack array to stack indices of null items and then unstack them whenever you encounter a non null item in myArray. (stack is not a reserved keyword so you can call it anything) :

var stack = []
for(var i = 0; i < myArray.length; i++){
   if(myArray[i] === "")
    stack.push(i);
   else if(stack.length !== 0){
       for(var j = stack.length - 1 ; j > =0; j--){
         myArray[stack[j]] = myArray[i];
         stack.splice(j,1);
       }
   }
}


问:
Why doesn't it has 0 as its output when I'm using threading.Lock to lock thread actions?

import threading

COUNTER = 100000

lock = threading.Lock()

def add():
  global x
  with lock:
    for i in range(COUNTER):
      x += 1

def subtract():
  global x
  with lock:
    for i in range(COUNTER):
      x -= 1
x = 0
t0 = threading.Thread(target = add)
t1 = threading.Thread(target = subtract)
t0.start()
t1.start()
print(x)
# The output shall be zero isn't it?
```

I made this code based on a code I saw in a course, that actually hasn't worked as well. When sharing a variable, threads are working pretty wrong with the data

答:
The corrected code is:

import threading

COUNTER = 100000

lock = threading.Lock()

def add():
    global x
    with lock:
        for i in range(COUNTER):
            x += 1

def subtract():
    global x
    with lock:
        for i in range(COUNTER):
            x -= 1

x = 0
t0 = threading.Thread(target=add)
t1 = threading.Thread(target=subtract)
t0.start()
t1.start()
# Added the below lines
t0.join()
t1.join()
# END
print(x)
```

The reason of your error is your main thread is not waiting for your child threads to finish there processes. That's why you are getting unusual output as you are printing the value of x in between.

Body:
import threading

COUNTER = 100000

lock = threading.Lock()

def add():
  global x
  with lock:
    for i in range(COUNTER):
      x += 1

def subtract():
  global x
  with lock:
    for i in range(COUNTER):
      x -= 1
x = 0
t0 = threading.Thread(target = add)
t1 = threading.Thread(target = subtract)
t0.start()
t1.start()
print(x)
# The output shall be zero isn't it?

I made this code based on a code I saw in a course, that actually hasn't worked as well. When sharing a variable, threads are working pretty wrong with the data

Body:
The corrected code is:

import threading

COUNTER = 100000

lock = threading.Lock()

def add():
    global x
    with lock:
        for i in range(COUNTER):
            x += 1

def subtract():
    global x
    with lock:
        for i in range(COUNTER):
            x -= 1

x = 0
t0 = threading.Thread(target=add)
t1 = threading.Thread(target=subtract)
t0.start()
t1.start()
# Added the below lines
t0.join()
t1.join()
# END
print(x)

The reason of your error is your main thread is not waiting for your child threads to finish there processes. That's why you are getting unusual output as you are printing the value of x in between.


问:
Single column dataframe containing 1D lists using a numpy 2D array
I want to create a new single column pandas dataframe using a 2D numpy array. Apparently, each row should contain 1D lists. Following is a simplified reproducible example.

```<code>import pandas as pd
import numpy as np

arr = np.ones((4,3)) # could be any 2D array
</code>```

What I want is,

```<code>       lists
0  [1, 1, 1]
1  [1, 1, 1]
2  [1, 1, 1]
3  [1, 1, 1]
</code>```

Now, df  = pd.DataFrame(arr, columns=['lists']) gives the error,

```<code>ValueError: Shape of passed values is (4, 3), indices imply (4, 1)
</code>```

And df = pd.DataFrame(list(arr), columns=['lists']) gives the error,

```<code>ValueError: 1 columns passed, passed data had 3 columns
</code>```

Finally, df = pd.DataFrame(arr.flatten(), columns=['lists']) gives a wrong dataframe with all cells having a scalar 1.

How do I get what I want?

答:
Get all rows of the array, create dataframe with them. Transpose then add column name.

import pandas as pd
import numpy as np

# ones array
arr = np.ones((4,3), dtype=int)

# get all rows of the array transpose and add column name
df  = pd.DataFrame([list(arr)]).T
df.columns = ['lists']
df
```

Body:
I want to create a new single column pandas dataframe using a 2D numpy array. Apparently, each row should contain 1D lists. Following is a simplified reproducible example.

import pandas as pd
import numpy as np

arr = np.ones((4,3)) # could be any 2D array

What I want is,

       lists
0  [1, 1, 1]
1  [1, 1, 1]
2  [1, 1, 1]
3  [1, 1, 1]

Now, df  = pd.DataFrame(arr, columns=['lists']) gives the error,

ValueError: Shape of passed values is (4, 3), indices imply (4, 1)

And df = pd.DataFrame(list(arr), columns=['lists']) gives the error,

ValueError: 1 columns passed, passed data had 3 columns

Finally, df = pd.DataFrame(arr.flatten(), columns=['lists']) gives a wrong dataframe with all cells having a scalar 1.

How do I get what I want?


问:
Exception Failed to parse time string
I looked a couple of questions with similar title but my case is quiet different. I am trying to move data from one table to another using laravel task. The table from which I want to copy the data from is using varchar for date while the table I am copying to has a date column type. So I must convert the string to valid carbon date before inserting into the new table. Unfortunately the old table has the dates mixed in different format so I have to check and convert before insert but I keep getting this error when dealing with a particular string format

Exception  : DateTime::__construct(): Failed to parse time string (26/02/1991) at position 0 (2): Unexpected character

Here's what my code for converting the strings to date format looks like

```<code>if ($user->profile->date_of_birth === null) {
    $dob = null;
    Log::info([$user->profile->date_of_birth, $dob]);
} else if (Carbon::parse($user->profile->date_of_birth)->toDateString() == true) {

    $dob = Carbon::parse($user->profile->date_of_birth)->toDateString();
    Log::info([$user->profile->date_of_birth, $dob]);
} else if (Carbon::createFromFormat('d/m/Y',   $user->profile->date_of_birth)->format('Y-m-d') == true) {

    $formattedDate = Carbon::createFromFormat('d/m/Y', $user->profile->date_of_birth)->format('Y-m-d');
    $dob = Carbon::parse($formattedDate)->toDateString();
    Log::info([$user->profile->date_of_birth, $dob]);
}
</code>```

Using laravel's artisan tinker, I am actually able to convert the string to date format as can be seen here

Why do I keep getting an error when I run my task and it encounters that particular string?

答:
Use ::createFromFormat('d/m/Y'...) instead of ::parse() like you did in the other places.

But it sounds like ->profile is a DB object, so I would highly recommend not to handle ->date_of_birth as a string, you should keep it as a Carbon instances by adding it in the $dates fields of your model; then use createFromFormat only when you get the input from the user.

Title: Exception Failed to parse time string

Body:
I looked a couple of questions with similar title but my case is quiet different. I am trying to move data from one table to another using laravel task. The table from which I want to copy the data from is using varchar for date while the table I am copying to has a date column type. So I must convert the string to valid carbon date before inserting into the new table. Unfortunately the old table has the dates mixed in different format so I have to check and convert before insert but I keep getting this error when dealing with a particular string format

Exception  : DateTime::__construct(): Failed to parse time string (26/02/1991) at position 0 (2): Unexpected character

Here's what my code for converting the strings to date format looks like

if ($user->profile->date_of_birth === null) {
    $dob = null;
    Log::info([$user->profile->date_of_birth, $dob]);
} else if (Carbon::parse($user->profile->date_of_birth)->toDateString() == true) {

    $dob = Carbon::parse($user->profile->date_of_birth)->toDateString();
    Log::info([$user->profile->date_of_birth, $dob]);
} else if (Carbon::createFromFormat('d/m/Y',   $user->profile->date_of_birth)->format('Y-m-d') == true) {

    $formattedDate = Carbon::createFromFormat('d/m/Y', $user->profile->date_of_birth)->format('Y-m-d');
    $dob = Carbon::parse($formattedDate)->toDateString();
    Log::info([$user->profile->date_of_birth, $dob]);
}

Using laravel's artisan tinker, I am actually able to convert the string to date format as can be seen here

Why do I keep getting an error when I run my task and it encounters that particular string?


问:
Problem with EMA using Security() in Pine Script Tradingview
I´m need to code an indicator that let me know the value of an ema from another TF (part of a bigger indicator).

This is my code to get a 9 period ema over a bbw on 15 minutes TF:

```<code>bbw2 = security(syminfo.tickerid, "15", bbw(src, length, mult))
emabbw2 = ema(bbw2, 9)
</code>```

But the value I get of emabbw2 when I am in 1M is not the same I get when I´m in 15M, so how can I code this to get the correct ema value from 15M when I´m in 1M chart?

Thank you!

答:
Need to let security() make the calcs in its context:

```<code>bbw2 = bbw(src, length, mult)
emabbw2 = security(syminfo.tickerid, "15", ema(bbw2, 9))
</code>```

Body:
I´m need to code an indicator that let me know the value of an ema from another TF (part of a bigger indicator).

This is my code to get a 9 period ema over a bbw on 15 minutes TF:

bbw2 = security(syminfo.tickerid, "15", bbw(src, length, mult))
emabbw2 = ema(bbw2, 9)

But the value I get of emabbw2 when I am in 1M is not the same I get when I´m in 15M, so how can I code this to get the correct ema value from 15M when I´m in 1M chart?

Thank you!

Body:
Need to let security() make the calcs in its context:

bbw2 = bbw(src, length, mult)
emabbw2 = security(syminfo.tickerid, "15", ema(bbw2, 9))


问:
Check if a string contains a specific number of given values
I am trying to decode a message provided as a morse code via command line argument. If the provided string contains 7 spaces it means that I need to print a space to the decoded string.
This is the way I am trying to check if string contains 7 spaces via for loop:

```<code>                if ((str[i] == ' ' && str[i + 1] == ' ' &&
                 str[i + 2] == ' ' && str[i + 3] == ' ' &&
                 str[i + 4] == ' ' && str[i + 5] == ' ' &&
                 str[i + 6] == ' ')) {
                mx_printchar(' ');
               }
</code>```

Please let me know if any efficient way could be used for this purpose.
Currently, I cannot use linked lists or structs, but maybe there is any other way, please advise

答:
You could use substr() instead as shown below :

```<code>if (str.substr(i,7) == "       ") {
     //do your task here
}
</code>```

This will check for the substring from i to i+7(this index included) and if this substring is equal to 7 spaces, then it will do the required task.

Body:
I am trying to decode a message provided as a morse code via command line argument. If the provided string contains 7 spaces it means that I need to print a space to the decoded string.
This is the way I am trying to check if string contains 7 spaces via for loop:

                if ((str[i] == ' ' && str[i + 1] == ' ' &&
                 str[i + 2] == ' ' && str[i + 3] == ' ' &&
                 str[i + 4] == ' ' && str[i + 5] == ' ' &&
                 str[i + 6] == ' ')) {
                mx_printchar(' ');
               }

Please let me know if any efficient way could be used for this purpose.
Currently, I cannot use linked lists or structs, but maybe there is any other way, please advise

Body:
You could use substr() instead as shown below :

if (str.substr(i,7) == "       ") {
     //do your task here
}

This will check for the substring from i to i+7(this index included) and if this substring is equal to 7 spaces, then it will do the required task.


问:
Price calculations (tax and discount)
What is the correct way of calculating product (and order) prices when a coupon is applied (considering the product is taxable). I've noticed that the taxes and discounts are disconnected. They are both applied on product's row price (and then summed up for the total price). I need to apply the tax on discounted product price:

(price - discount) + tax(discounted price)

What is the best approach to implement such calculation?

答:
This behavior is not customizable from UI.

But you can change it in customization:

Decorate OrderLineItemMapper or OrderMapper, depending on your requirements

Use there a price with an applied discount that you can fetch from oro_promotion.promotion_executor service.

Title: Price calculations (tax and discount)


问:
Capture Request Headers whenever a static file is requested in Flask App
All,

I'm able to capture request headers whenever a request is made to an endpoint but I was wondering how to capture the request headers whenever a static file is requested.

For example, whenever a request is made to get an image through this endpoint, I'm able to write the headers to a .txt file with a timestamp like below.

https://<host_name>/img

Request Headers example:

```<code>============================
28/05/2020, 14:31:03
Request Headers:
Host: <host_name>
Connection: close
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,kn;q=0.8
X-Request-Id: 00a79a7f-84eb-4fb3-b949-76254a93a001
X-Forwarded-For: 157.49.191.87
X-Forwarded-Proto: https
X-Forwarded-Port: 443
Via: 1.1 vegur
Connect-Time: 0
X-Request-Start: 1590676263802
Total-Route-Time: 0

============================
</code>```

But when someone directly accesses the static objects like this:

```<code>https://<host_name>/static/img/<img_name>.png
</code>```

How to capture the request headers for the static objects when requested directly without any route or a view as the above endpoint?

Currently, I'm capturing the request headers using request.headers in Flask. My function for an img endpoint looks like this:

```<code>@app.route('/img')
def img_func():
    req_headers = request.headers
    dir = "static"
    full_path = os.path.join(dir, "logs")
    filename = full_path +'/request_headers_img.txt'

    if os.path.exists(filename):
        append_write = 'a'  # append if already exists
    else:
        append_write = 'w'  # make a new file if not

    now = datetime.datetime.now()
    date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
    app_logs = open(filename, append_write)
    app_logs.write("============================" + '\n')
    app_logs.write(date_time + '\n')
    app_logs.write("Request Headers: " + '\n' + str(req_headers))
    app_logs.write("============================"+ '\n')
    app_logs.close()

    fn = os.path.join(dir, "img") + '/<file_name>.png'

    return send_file(fn)
</code>```

As I did check some online links, someone mentioned making use of request.path('static') but not sure on how to implement this & capture the request headers.

One more thing which was mentioned there that the static files are being served from the webserver like Nginx or Apache, not from the flask app if static files are requested directly as I mentioned above. If so is there a way to capture these static request headers at the webserver level?

FYI:
The app is built using Flask, Python 3 & deployed to Heroku using CI/CD from Github.

Any help around this or if someone can point to the resources where I can read & implement this will be very useful guys.

Thanks in advance!

答:
Ok so I am going to answer

(a) Capture Request Headers whenever a static file is requested in Flask App?

```<code>@app.route("/static/<var1>/<var2>")
def test(var1,var2):
    print(request.headers)
    return "hehe"
</code>```

Let me know if that works for you, and answers part (a) of your question

Body:
All,

I'm able to capture request headers whenever a request is made to an endpoint but I was wondering how to capture the request headers whenever a static file is requested.

For example, whenever a request is made to get an image through this endpoint, I'm able to write the headers to a .txt file with a timestamp like below.

https://<host_name>/img

Request Headers example:

============================
28/05/2020, 14:31:03
Request Headers:
Host: <host_name>
Connection: close
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,kn;q=0.8
X-Request-Id: 00a79a7f-84eb-4fb3-b949-76254a93a001
X-Forwarded-For: 157.49.191.87
X-Forwarded-Proto: https
X-Forwarded-Port: 443
Via: 1.1 vegur
Connect-Time: 0
X-Request-Start: 1590676263802
Total-Route-Time: 0

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

But when someone directly accesses the static objects like this:

https://<host_name>/static/img/<img_name>.png

How to capture the request headers for the static objects when requested directly without any route or a view as the above endpoint?

Currently, I'm capturing the request headers using request.headers in Flask. My function for an img endpoint looks like this:

@app.route('/img')
def img_func():
    req_headers = request.headers
    dir = "static"
    full_path = os.path.join(dir, "logs")
    filename = full_path +'/request_headers_img.txt'

    if os.path.exists(filename):
        append_write = 'a'  # append if already exists
    else:
        append_write = 'w'  # make a new file if not

    now = datetime.datetime.now()
    date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
    app_logs = open(filename, append_write)
    app_logs.write("============================" + '\n')
    app_logs.write(date_time + '\n')
    app_logs.write("Request Headers: " + '\n' + str(req_headers))
    app_logs.write("============================"+ '\n')
    app_logs.close()

    fn = os.path.join(dir, "img") + '/<file_name>.png'

    return send_file(fn)

As I did check some online links, someone mentioned making use of request.path('static') but not sure on how to implement this & capture the request headers.

One more thing which was mentioned there that the static files are being served from the webserver like Nginx or Apache, not from the flask app if static files are requested directly as I mentioned above. If so is there a way to capture these static request headers at the webserver level?

FYI:
The app is built using Flask, Python 3 & deployed to Heroku using CI/CD from Github.

Any help around this or if someone can point to the resources where I can read & implement this will be very useful guys.

Thanks in advance!

Body:
Ok so I am going to answer

(a) Capture Request Headers whenever a static file is requested in Flask App?

@app.route("/static/<var1>/<var2>")
def test(var1,var2):
    print(request.headers)
    return "hehe"

Let me know if that works for you, and answers part (a) of your question


问:
Closing applications / windows in TCL
I wish to know how to close an open application in TCL specifically (the TK commands aren’t installed on my system so I can’t use destroy).

I am running a script which launches an image viewer which also has command line options Currently I have:

```<code>exec cmd /c ".\image_viewer -specified_option"
</code>```

Since this is what I’d put into the command line to run the viewer with the added option.

It then launches a window with the title “image_viewer.exe”.

How do I get it to close the window above and continue with its other steps?

Also I need to know how to do a screen capture and save for that image. Can you screen capture a specific / designated portion of the screen?

答:
If you put the command into the backround, you can get the process id back:

```<code>set pid [exec cmd /c ".\image_viewer -specified_option" &]
</code>```

Then, for example kill the process after 10 seconds:

```<code>proc killpid { pid } {
   if { $::tcl_platform(platform) eq "windows" } {
      set cmd "taskkill.exe /f /fi \"pid eq $pid\" 2>nul"
      exec -ignorestderr -- {*}$cmd 2>@1
   } else {
      exec kill $pid
   }
}

after 10000 [list killpid $pid]
</code>```

Title: Closing applications / windows in TCL

Body:
I wish to know how to close an open application in TCL specifically (the TK commands aren’t installed on my system so I can’t use destroy).

I am running a script which launches an image viewer which also has command line options Currently I have:

exec cmd /c ".\image_viewer -specified_option"

Since this is what I’d put into the command line to run the viewer with the added option.

It then launches a window with the title “image_viewer.exe”.

How do I get it to close the window above and continue with its other steps?

Also I need to know how to do a screen capture and save for that image. Can you screen capture a specific / designated portion of the screen?

Body:
If you put the command into the backround, you can get the process id back:

set pid [exec cmd /c ".\image_viewer -specified_option" &]

Then, for example kill the process after 10 seconds:

proc killpid { pid } {
   if { $::tcl_platform(platform) eq "windows" } {
      set cmd "taskkill.exe /f /fi \"pid eq $pid\" 2>nul"
      exec -ignorestderr -- {*}$cmd 2>@1
   } else {
      exec kill $pid
   }
}

after 10000 [list killpid $pid]