问:
SetWindowsHookEx failing with google chrome. Error code 87 invalid parameter
I am making a tutorial based program and want to be able to hook my code into certain apps to get the tutorial interacting with the app.

My hook code works for most apps except google chrome. I have stripped my code down to the following so you can see it going wrong.

Main.cpp

```<code>#include <Windows.h>
#include <iostream>
#include <psapi.h>
#include <Tlhelp32.h>

unsigned long GetProcId( const std::string& name )
{
    unsigned long res = 0 ;

    HANDLE hSnapShot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    PROCESSENTRY32 processInfo ;
    processInfo.dwSize=sizeof(PROCESSENTRY32W);

    if( !Process32First( hSnapShot, &processInfo ) )
    {
        CloseHandle( hSnapShot );
        return res ;
    }

    do
    {
        if( NULL != ( strstr ( strlwr ( processInfo.szExeFile ), name.c_str() ) ) )
        {
            res = processInfo.th32ProcessID ;
            break ;
        }
    } while(Process32Next( hSnapShot,&processInfo ));

    CloseHandle( hSnapShot ) ;
    return res ;
}

typedef LRESULT (CALLBACK *DllHookProc)(int nCode, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
               LPSTR lpCmdLine, int nCmdShow)
{
    unsigned int processid = GetProcId( "chrome.exe" ) ;

    if (processid == 0)
    {
        return 0 ;
    }

    HINSTANCE dllInstance = LoadLibrary("mydll.dll") ;

    if (dllInstance == NULL)
    {
        return 0 ;
    }

    DllHookProc hookProc = (DllHookProc)::GetProcAddress(dllInstance, "HookProc");

    if ( hookProc == NULL)
    {
        FreeLibrary(dllInstance);
        return 0 ;
    }

    HHOOK hook = SetWindowsHookEx(WH_CALLWNDPROC,(HOOKPROC)hookProc,
        dllInstance, processid );

    if (hook == NULL)
    {
        FreeLibrary(dllInstance);
        return 0 ;
    }

    return 0 ;
}
</code>```

Test Dll (mydll.dll)

```<code>LRESULT CALLBACK HookProc (int nCode, WPARAM wParam, LPARAM lParam )
{
    //Pass to the next chain in the process list
    return CallNextHookEx( 0, nCode, wParam, lParam);
}

BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
    return TRUE;
}
</code>```

Definition file

```<code>LIBRARY "MYDLL"
EXPORTS
HookProc @1
</code>```

Everything works fine (including getting processId and loading library and getprocaddress) up to the SetWindowsHookEx which returns NULL with error code 87 (invalid parameter).

Both chrome.exe and my code are 32 bit.

Does this work for anyone else or does anyone know what it doesnt work?

Thanks

答:
You realize that chrome uses a multi-process model, right?  There are many chrome instances cooperating, and some of them might not have an event queue.

Most certainly your GetProcId code is not going to work for chrome because it only finds one matching process.

Body:
I am making a tutorial based program and want to be able to hook my code into certain apps to get the tutorial interacting with the app.

My hook code works for most apps except google chrome. I have stripped my code down to the following so you can see it going wrong.

Main.cpp

#include <Windows.h>
#include <iostream>
#include <psapi.h>
#include <Tlhelp32.h>

unsigned long GetProcId( const std::string& name )
{
    unsigned long res = 0 ;

    HANDLE hSnapShot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    PROCESSENTRY32 processInfo ;
    processInfo.dwSize=sizeof(PROCESSENTRY32W);

    if( !Process32First( hSnapShot, &processInfo ) )
    {
        CloseHandle( hSnapShot );
        return res ;
    }

    do
    {
        if( NULL != ( strstr ( strlwr ( processInfo.szExeFile ), name.c_str() ) ) )
        {
            res = processInfo.th32ProcessID ;
            break ;
        }
    } while(Process32Next( hSnapShot,&processInfo ));

    CloseHandle( hSnapShot ) ;
    return res ;
}

typedef LRESULT (CALLBACK *DllHookProc)(int nCode, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
               LPSTR lpCmdLine, int nCmdShow)
{
    unsigned int processid = GetProcId( "chrome.exe" ) ;

    if (processid == 0)
    {
        return 0 ;
    }

    HINSTANCE dllInstance = LoadLibrary("mydll.dll") ;

    if (dllInstance == NULL)
    {
        return 0 ;
    }

    DllHookProc hookProc = (DllHookProc)::GetProcAddress(dllInstance, "HookProc");

    if ( hookProc == NULL)
    {
        FreeLibrary(dllInstance);
        return 0 ;
    }

    HHOOK hook = SetWindowsHookEx(WH_CALLWNDPROC,(HOOKPROC)hookProc,
        dllInstance, processid );

    if (hook == NULL)
    {
        FreeLibrary(dllInstance);
        return 0 ;
    }

    return 0 ;
}

Test Dll (mydll.dll)

LRESULT CALLBACK HookProc (int nCode, WPARAM wParam, LPARAM lParam )
{
    //Pass to the next chain in the process list
    return CallNextHookEx( 0, nCode, wParam, lParam);
}

BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
    return TRUE;
}

Definition file

LIBRARY "MYDLL"
EXPORTS
HookProc @1

Everything works fine (including getting processId and loading library and getprocaddress) up to the SetWindowsHookEx which returns NULL with error code 87 (invalid parameter).

Both chrome.exe and my code are 32 bit.

Does this work for anyone else or does anyone know what it doesnt work?

Thanks


来源: stackexchange

答:
This is what I would do:

```<code>s = df.groupby('IP').Port.diff()
new_df = (df.groupby(['IP', s.ne(1).groupby(df['IP']).cumsum()])
            .Port.agg(['min','max','count'])
            .reset_index('Port', drop=True)
         )
new_df['out'] = np.where(new_df['count']==1,
                         new_df['min'],
                         new_df[['min','max']].astype(str).agg('-'.join, axis=1))
new_df.groupby('IP')['out'].apply(list)
</code>```

Output:

```<code>IP
1.1.1.1                     [1-14]
1.1.1.2    [15-16, 18, 20, 22, 27]
1.1.1.3                    [40-47]
Name: out, dtype: object
</code>```

ContentLicense: CC BY-SA 4.0

Title: Pandas - turn list values (1, 2, 3) into a range (1-3)?

Body:
Is there any simple way to take a range of numbers i.e (1, 2, 3, 4, 5) and turn them into an easily-readable range (1-5)?

I'm taking IP/port combinations and attempting to list the range of ports seen on a single IP, where I might have 50,000+ ports seen on a single IP but I'd like to be able to see something like [1-50,000] instead of listing out every single one.

    IP  Port
0   1.1.1.1     1
1   1.1.1.1     2
2   1.1.1.1     3
3   1.1.1.1     4
4   1.1.1.1     5
5   1.1.1.1     6
6   1.1.1.1     7
7   1.1.1.1     8
8   1.1.1.1     9
9   1.1.1.1    10
10  1.1.1.1    11
11  1.1.1.1    12
12  1.1.1.1    13
13  1.1.1.1    14
14  1.1.1.2    15
15  1.1.1.2    16
16  1.1.1.2    18
17  1.1.1.2    20
18  1.1.1.2    22
19  1.1.1.2    27
20  1.1.1.3    40
21  1.1.1.3    41
22  1.1.1.3    42
23  1.1.1.3    43
24  1.1.1.3    44
25  1.1.1.3    45
26  1.1.1.3    46
27  1.1.1.3    47

//code//

df.groupby('IP')['Port'].apply(list)

//result//

1.1.1.1    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
1.1.1.2                           [15, 16, 18, 20, 22, 27]
1.1.1.3                   [40, 41, 42, 43, 44, 45, 46, 47]

//desired result//

1.1.1.1                     [1-14]
1.1.1.2    [15-16, 18, 20, 22, 27]
1.1.1.3                    [40-47]

Body:
This is what I would do:

s = df.groupby('IP').Port.diff()
new_df = (df.groupby(['IP', s.ne(1).groupby(df['IP']).cumsum()])
            .Port.agg(['min','max','count'])
            .reset_index('Port', drop=True)
         )
new_df['out'] = np.where(new_df['count']==1,
                         new_df['min'],
                         new_df[['min','max']].astype(str).agg('-'.join, axis=1))
new_df.groupby('IP')['out'].apply(list)

Output:

IP
1.1.1.1                     [1-14]
1.1.1.2    [15-16, 18, 20, 22, 27]
1.1.1.3                    [40-47]
Name: out, dtype: object


问:
How to hide a single key in R?
Just to be clear: I am relatively new to R, and the code I am using is borrowed from someone else.

I have this graph for polling averages:

Here is my code: https://pastebin.com/qvQERRUH

```<code>library("tidyverse")

polls <- read.csv("polls_Paris.csv")

polls <- polls %>%
  mutate(
    date = format(as.Date(c(paste(year,month, day, sep="-")), by = "days"))
  )

for(i in c("LFI", "PS", "EELV", "PP", "Griveaux", "LREM", "Villani", "Agir", "LR", "RN", "LP")) {
  polls <- within(polls, {
    assign(paste0("ci_", i), 1.96 * sqrt(( get(paste0("liste_", i)) * (100 - get(paste0("liste_", i)))) / n))
  }
  )
}

polls.10m <- polls[polls$date > seq(as.Date(Sys.Date()), length = 2, by = "-10 months")[2],]
polls.100 <- polls[order(as.Date(polls$date)),] %>% top_n(5000, as.Date(polls$date))
#Results = data.frame(date = as.Date("2019-12-01"), support = c(69.1,30.9))

svg('Opinion polling for the 2020 Paris municipal election.svg', width = 12, height = 6)
polls.100 %>%
  gather(party, support, c(liste_LFI,liste_PS,liste_EELV,liste_PP,liste_Griveaux,liste_LREM,liste_Villani,liste_Agir,liste_LR,liste_RN,liste_LP), factor_key=TRUE) %>%
  ggplot(aes(x=as.Date(date), y=support, colour=party)) +
  geom_point(size=2.5, alpha=0.275) +
  geom_smooth(se=FALSE, method="loess", span=1) +
  labs(y = NULL,
       x = NULL) +
  guides(colour = guide_legend(ncol = 1, override.aes = list(linetype = 0, size = 3, alpha = 1))) +
  scale_colour_manual(labels = c("Simonnet (LFI)", "Hidalgo (PS-PCF-G·s)", "Belliard (EELV)", "Gantzer (DVG)", "Griveaux (LREM-MR-UDI)", "Griveaux (avant diss. de Villani)", "Villani (Diss. LREM-PRG)", "Bournazel (Agir)", "Dati (LR)", "Federbusch (DVD-RN)", "Campion (SE)"), values = c("#cc2443", "#FF8080", "#00c000", "#ffc0c0", "#ffeb00", "#ffeb00", "#FF7F50", "#adc1fd", "#0066CC", "#0D378A", "#808080", "#808080")) +
  theme(
    plot.margin = margin(t = 0, unit = "cm"),
    plot.background = element_blank(), panel.background = element_rect(fill = "grey92", colour = NA),
    panel.border = element_blank(), legend.background = element_rect(fill = "transparent", colour = NA),
    legend.key = element_rect(fill = "transparent", colour = NA), legend.title = element_blank(),
    strip.background = element_rect(fill = "transparent", colour = NA),
    panel.grid.major = element_line(colour = "#FFFFFF"), panel.grid.minor = element_line(colour = "#FFFFFF", size = 0.25),
    axis.ticks = element_line(colour = "grey20"), axis.line = element_blank(),
    plot.title = element_text(size = 12, hjust = 0),
    plot.subtitle = element_text(size = 12, hjust = 0),
    plot.caption = element_text(size = 12, colour = "#212121"),
    axis.title = element_text(size = 12, face = "plain"), axis.text = element_text(size = 12, face = "plain", colour = "grey30"),
    legend.position = "right",
    legend.text = element_text(size = 12), strip.text = element_text(size = 12, face = "plain"),
    legend.margin = margin(t = 0, unit = "cm"),
  ) +
  scale_y_continuous(breaks = seq(0,33,5), minor_breaks = seq(0,33,1), limits = c(0, 33), expand = c(0, 0)) +
  scale_x_date(breaks="6 months", minor_breaks="1 month", expand = c(0, 0))
  #geom_point(data = Results, colour = c("#808080", "#E81B23"), size=4, shape=5) +
  #geom_point(data = Results, colour = c("#808080", "#E81B23"), size=3.5, shape=18)
dev.off()
</code>```

As you can see, Griveaux's line is split to separate the before-and-after of Villani's dissident candidacy; it's actually 2 separate lines (also separate in the dataset). Griveaux's name therefore has to appears twice.

How do I do to remove the key of a single set (remove the key for both the dots and regression line)?

答:
Here is a hack. To remove a legend key, remove it from the breaks argument to scale_*_manual or equivalent but you must keep the same number of values as there are unique values in the color/fill aesthetic.

This is better shown with an example. I will use built-in data set iris.

To remove the legend key relative to "versicolor",

```<code>levels(df1$Species)
#[1] "setosa"     "versicolor" "virginica"
</code>```

just don't include it in the breaks.

```<code>library(ggplot2)

df1 <- iris[3:5]

ggplot(df1, aes(Petal.Length, Petal.Width, color = Species)) +
  geom_point() +
  geom_smooth(se = FALSE, method = "loess", span = 1) +
  scale_color_manual(breaks = c("setosa", "virginica"),
                     values = c("red", "green", "blue"))
</code>```

Title: How to hide a single key in R?

Body:
Just to be clear: I am relatively new to R, and the code I am using is borrowed from someone else.

I have this graph for polling averages:

Here is my code: https://pastebin.com/qvQERRUH

library("tidyverse")

polls <- read.csv("polls_Paris.csv")

polls <- polls %>%
  mutate(
    date = format(as.Date(c(paste(year,month, day, sep="-")), by = "days"))
  )

for(i in c("LFI", "PS", "EELV", "PP", "Griveaux", "LREM", "Villani", "Agir", "LR", "RN", "LP")) {
  polls <- within(polls, {
    assign(paste0("ci_", i), 1.96 * sqrt(( get(paste0("liste_", i)) * (100 - get(paste0("liste_", i)))) / n))
  }
  )
}

polls.10m <- polls[polls$date > seq(as.Date(Sys.Date()), length = 2, by = "-10 months")[2],]
polls.100 <- polls[order(as.Date(polls$date)),] %>% top_n(5000, as.Date(polls$date))
#Results = data.frame(date = as.Date("2019-12-01"), support = c(69.1,30.9))

svg('Opinion polling for the 2020 Paris municipal election.svg', width = 12, height = 6)
polls.100 %>%
  gather(party, support, c(liste_LFI,liste_PS,liste_EELV,liste_PP,liste_Griveaux,liste_LREM,liste_Villani,liste_Agir,liste_LR,liste_RN,liste_LP), factor_key=TRUE) %>%
  ggplot(aes(x=as.Date(date), y=support, colour=party)) +
  geom_point(size=2.5, alpha=0.275) +
  geom_smooth(se=FALSE, method="loess", span=1) +
  labs(y = NULL,
       x = NULL) +
  guides(colour = guide_legend(ncol = 1, override.aes = list(linetype = 0, size = 3, alpha = 1))) +
  scale_colour_manual(labels = c("Simonnet (LFI)", "Hidalgo (PS-PCF-G·s)", "Belliard (EELV)", "Gantzer (DVG)", "Griveaux (LREM-MR-UDI)", "Griveaux (avant diss. de Villani)", "Villani (Diss. LREM-PRG)", "Bournazel (Agir)", "Dati (LR)", "Federbusch (DVD-RN)", "Campion (SE)"), values = c("#cc2443", "#FF8080", "#00c000", "#ffc0c0", "#ffeb00", "#ffeb00", "#FF7F50", "#adc1fd", "#0066CC", "#0D378A", "#808080", "#808080")) +
  theme(
    plot.margin = margin(t = 0, unit = "cm"),
    plot.background = element_blank(), panel.background = element_rect(fill = "grey92", colour = NA),
    panel.border = element_blank(), legend.background = element_rect(fill = "transparent", colour = NA),
    legend.key = element_rect(fill = "transparent", colour = NA), legend.title = element_blank(),
    strip.background = element_rect(fill = "transparent", colour = NA),
    panel.grid.major = element_line(colour = "#FFFFFF"), panel.grid.minor = element_line(colour = "#FFFFFF", size = 0.25),
    axis.ticks = element_line(colour = "grey20"), axis.line = element_blank(),
    plot.title = element_text(size = 12, hjust = 0),
    plot.subtitle = element_text(size = 12, hjust = 0),
    plot.caption = element_text(size = 12, colour = "#212121"),
    axis.title = element_text(size = 12, face = "plain"), axis.text = element_text(size = 12, face = "plain", colour = "grey30"),
    legend.position = "right",
    legend.text = element_text(size = 12), strip.text = element_text(size = 12, face = "plain"),
    legend.margin = margin(t = 0, unit = "cm"),
  ) +
  scale_y_continuous(breaks = seq(0,33,5), minor_breaks = seq(0,33,1), limits = c(0, 33), expand = c(0, 0)) +
  scale_x_date(breaks="6 months", minor_breaks="1 month", expand = c(0, 0))
  #geom_point(data = Results, colour = c("#808080", "#E81B23"), size=4, shape=5) +
  #geom_point(data = Results, colour = c("#808080", "#E81B23"), size=3.5, shape=18)
dev.off()

As you can see, Griveaux's line is split to separate the before-and-after of Villani's dissident candidacy; it's actually 2 separate lines (also separate in the dataset). Griveaux's name therefore has to appears twice.

How do I do to remove the key of a single set (remove the key for both the dots and regression line)?

Body:
Here is a hack. To remove a legend key, remove it from the breaks argument to scale_*_manual or equivalent but you must keep the same number of values as there are unique values in the color/fill aesthetic.

This is better shown with an example. I will use built-in data set iris.

To remove the legend key relative to "versicolor",

levels(df1$Species)
#[1] "setosa"     "versicolor" "virginica"

just don't include it in the breaks.

library(ggplot2)

df1 <- iris[3:5]

ggplot(df1, aes(Petal.Length, Petal.Width, color = Species)) +
  geom_point() +
  geom_smooth(se = FALSE, method = "loess", span = 1) +
  scale_color_manual(breaks = c("setosa", "virginica"),
                     values = c("red", "green", "blue"))


问:
scheduling a task in r through task scheduler for a script to run monthly shows error
I am trying to schedule a r script to run monthly, however I receive the error below

```<code>"ERROR: Invalid value for /D option."     "Type \"SCHTASKS /CREATE /?\" for usage."
attr(,"status").
</code>```

I tried creating task through task scheduler however it appears that this does not work when the schedule time is monthly. It works perfectly for other options such as daily and once.

```<code>library(taskscheduleR)
myscript <- system.file("extdata", "New_Plan_Monthly.R", package = "taskscheduleR")
cat(readLines(myscript), sep = "\n")

taskscheduler_create(taskname = "myfancyscriptMonthly", rscript = myscript,
                     schedule = "MONTHLY", starttime = "14:00", startdate = format(Sys.Date()+25, "%m/%d/%Y"))
</code>```

答:
I just figured this out here is a snippet of my code which seems similar to yours.

The error below is referring to day hence /D option
"ERROR: Invalid value for /D option."

"Type \"SCHTASKS /CREATE /?\" for usage."

Here is my code example:

```<code>myscript <- system.file("extdata", "Script.R", package = "taskscheduleR")
cat(readLines(myscript), sep = "\n")

taskscheduler_create(taskname = "Name_of_Task", rscript = myscript, schedule =
"MONTHLY", starttime = "09:10",startdate = format(Sys.Date(),
"%m/%d/%Y"),days="01", months = "MAY")
</code>```

So it appears that you need to specify what day(numeric value) of the month you want to run this script. In this case I am running my script the first of may. I could have it run the first of every month by changing "months" to 'months = "*" '

Body:
I am trying to schedule a r script to run monthly, however I receive the error below

"ERROR: Invalid value for /D option."     "Type \"SCHTASKS /CREATE /?\" for usage."
attr(,"status").

I tried creating task through task scheduler however it appears that this does not work when the schedule time is monthly. It works perfectly for other options such as daily and once.

library(taskscheduleR)
myscript <- system.file("extdata", "New_Plan_Monthly.R", package = "taskscheduleR")
cat(readLines(myscript), sep = "\n")

taskscheduler_create(taskname = "myfancyscriptMonthly", rscript = myscript,
                     schedule = "MONTHLY", starttime = "14:00", startdate = format(Sys.Date()+25, "%m/%d/%Y"))

Body:
I just figured this out here is a snippet of my code which seems similar to yours.

The error below is referring to day hence /D option
"ERROR: Invalid value for /D option."

"Type \"SCHTASKS /CREATE /?\" for usage."

Here is my code example:

myscript <- system.file("extdata", "Script.R", package = "taskscheduleR")
cat(readLines(myscript), sep = "\n")

taskscheduler_create(taskname = "Name_of_Task", rscript = myscript, schedule =
"MONTHLY", starttime = "09:10",startdate = format(Sys.Date(),
"%m/%d/%Y"),days="01", months = "MAY")

So it appears that you need to specify what day(numeric value) of the month you want to run this script. In this case I am running my script the first of may. I could have it run the first of every month by changing "months" to 'months = "*" '


问:
Show functions in Eclipse's Project Explorer
I accidently closed the Project Explorer in Eclipse and the opportunity to expand all functions used in my php files is missing when I opened it again via Window -> Show View.

Does anyone know how to get this back?

答: Under the project manager view menu, under "project presentation", check to see that you are in "hierarchical". When I lost the function list in my Java project, it brought back the function list.  </p>

ContentLicense: CC BY-SA 3.0


问:
Where does a template(.t) file belong if i already have a header?
I should be able get these 4 files to compile without changing anything. I first thought the .t file was a header file but then it makes it a (.h) file, and i already have "arrayi.h" for that? Can anyone help me format them correctly? Please and thank you.

I have this 4 files to put in 1 project: .h / .t / .cpp / client driver.cpp.

.t below

```<code>// File name         : arrayi.t

#ifndef ARRAYI_T_
#define ARRAYI_T_

#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace::std;

// Default constructor for class Array
template<typename T>
Array<T>::Array(int arraySize)
{
    cout << "calling the constructor \n";
}

// Overloaded output operator for class Array
template<typename T>
ostream &operator<<(ostream &output, const Array<T> &a)
{

  int i;
  output << "{ ";

  for (i = 0; i < a.size; i++)
    {
      output << a.ptr[i] << ' ';

      if ((i + 1) % 10 == 0)
        output << "}" << endl;
    }  //end for

  if (i % 10 != 0)
    output << "}" << endl;

  return output;   // enables cout << x << y;
}

#endif

</code>```

.h below

```<code>// File name         : arrayi.h

#ifndef ARRAYI_H_
#define ARRAYI_H_

#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace::std;

template<typename T> class Array;
template<typename T>
ostream &operator<< (ostream& output, const Array<T> &a);

template<typename T>
class Array
{
    friend ostream &operator<< <>(ostream &output, const Array<T> &a);

public:
    Array(int = 10);    //constructor

  private:

};

#include "arrayi.t"

#endif
</code>```

.cpp below

```<code>// File name         : arrayi.cpp

#include "arrayi.h"

#include "arrayi.t"
</code>```

client driver.cpp below

```<code>// File name         : client_driver.cpp

#include<iostream>
using namespace::std;

#include "arrayi.h"
</code>```

答:
You only need to include the .h file in your .cpp files. Then compile the .cpp files, but not the .h and .t files, as translation units.

The .t is basically only meant to separate the template implementation into another file. It really belongs into the header file and that is why it is included in the .h. Other code need not bother with it at all.

Body:
I should be able get these 4 files to compile without changing anything. I first thought the .t file was a header file but then it makes it a (.h) file, and i already have "arrayi.h" for that? Can anyone help me format them correctly? Please and thank you.

I have this 4 files to put in 1 project: .h / .t / .cpp / client driver.cpp.

.t below

// File name         : arrayi.t

#ifndef ARRAYI_T_
#define ARRAYI_T_

#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace::std;

// Default constructor for class Array
template<typename T>
Array<T>::Array(int arraySize)
{
    cout << "calling the constructor \n";
}

// Overloaded output operator for class Array
template<typename T>
ostream &operator<<(ostream &output, const Array<T> &a)
{

  int i;
  output << "{ ";

  for (i = 0; i < a.size; i++)
    {
      output << a.ptr[i] << ' ';

      if ((i + 1) % 10 == 0)
        output << "}" << endl;
    }  //end for

  if (i % 10 != 0)
    output << "}" << endl;

  return output;   // enables cout << x << y;
}

#endif

.h below

// File name         : arrayi.h

#ifndef ARRAYI_H_
#define ARRAYI_H_

#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace::std;

template<typename T> class Array;
template<typename T>
ostream &operator<< (ostream& output, const Array<T> &a);

template<typename T>
class Array
{
    friend ostream &operator<< <>(ostream &output, const Array<T> &a);

public:
    Array(int = 10);    //constructor

  private:

};

#include "arrayi.t"

#endif

.cpp below

// File name         : arrayi.cpp

#include "arrayi.h"

#include "arrayi.t"

client driver.cpp below

// File name         : client_driver.cpp

#include<iostream>
using namespace::std;

#include "arrayi.h"


问:
Phing - how to checkout from svn, then upload via ftp and chmod directories
I have been reading the Phing documentation and it makes sense, but I'm not able to find out from there or on Google (or here) how to do what I would consider to be a fairly normal build procedure - checkout from svn, then upload the checked out copy via ftp and then chmod certain directories (for uploading files).

Is this possible with Phing, or would I have to write my own task class to do it?

答:
Just looked at Phing: Wow, it does look a lot like Ant.

You need to look at the Optional Tasks in Appendix C. There, you'll see a bunch of svn tasks, and the scp task that can copy files from one system to another. Worse comes to worse, you can use the exec task to call the command line ftp command. With that, you can define .netrc file that will automatically login and transfer files.

They have a sample build file, but I don't know Phing, so I'm not going to try to write one.


问:
IO values into haskell function
I currently have a function with definition:

```<code>f :: [Int] -> Int -> [[Int]]
</code>```

And have two variables of type IO [Int] and IO Int. I want to pass these variables to this function f. I am able to do this when it is just one variable being passed to the function, but when it is 2 I can't get it to work.

答:
You can write a do block:

```<code>f' :: <b>IO</b> [[Int]]
f' = do
    x <- val1
    y <- val2
    return (f x y)</code>```

with val1 :: IO [Int] and val2 :: IO Int the values you want to pass as parameters.

or in an applicative style:

```<code>f' :: IO [[Int]]
f' = f <b><$></b> val1 <b><*></b> val2</code>```

or we can make use of liftA2 :: (a -> b -> c) -> f a -> f b -> f c:

```<code>f' :: IO [[Int]]
f' = <b>liftA2</b> f val1 val2</code>```

Title: IO values into haskell function

Body:
I currently have a function with definition:

f :: [Int] -> Int -> [[Int]]

And have two variables of type IO [Int] and IO Int. I want to pass these variables to this function f. I am able to do this when it is just one variable being passed to the function, but when it is 2 I can't get it to work.

Body:
You can write a do block:

f' :: IO [[Int]]
f' = do
    x <- val1
    y <- val2
    return (f x y)

with val1 :: IO [Int] and val2 :: IO Int the values you want to pass as parameters.

or in an applicative style:

f' :: IO [[Int]]
f' = f <$> val1 <*> val2

or we can make use of liftA2 :: (a -> b -> c) -> f a -> f b -> f c:

f' :: IO [[Int]]
f' = liftA2 f val1 val2


问:
Looping HTML5 video flashes a black screen on loop
I have a 20 second HTML5 video that loops via jquery. But every time the video starts, a black screen flashes quickly and it's very jarring because it's supposed to blend in with a white background.

I tried using CSS to make the video background white to no avail. Any ideas how may I achieve the desired effect?

```<code><video id="projects-video" width="841px" height="490px" autoplay poster="video/map1280-poster.jpg" >
    <source src="video/map841.mp4" type="video/mp4"/>
    Your browser does not support the video tag. I suggest you upgrade your browser.
 </video>

<script>
   $("#projects-video").bind('ended', function(){
            this.play();
     });
</script>
</code>```

答:
I had the same issues with short videos with duration non-proportional to seconds(for example, 10 seconds and 400 milliseconds). The solution was to trim that part that possibly was added by some encoding issue:

```<code>ffmpeg -i in.mp4 -ss 00:00:00.0 -t 00:00:10.0 -an out.mp4
</code>```

I also used native looping and auto-play approach:

```<code><video muted autoPlay loop poster="/static/index/background.jpg" css={videoStyleSheet}>
    <source src="/static/index/output.mp4" type="video/mp4" />
</video>
</code>```

Body:
I have a 20 second HTML5 video that loops via jquery. But every time the video starts, a black screen flashes quickly and it's very jarring because it's supposed to blend in with a white background.

I tried using CSS to make the video background white to no avail. Any ideas how may I achieve the desired effect?

<video id="projects-video" width="841px" height="490px" autoplay poster="video/map1280-poster.jpg" >
    <source src="video/map841.mp4" type="video/mp4"/>
    Your browser does not support the video tag. I suggest you upgrade your browser.
 </video>

Body:
I had the same issues with short videos with duration non-proportional to seconds(for example, 10 seconds and 400 milliseconds). The solution was to trim that part that possibly was added by some encoding issue:

ffmpeg -i in.mp4 -ss 00:00:00.0 -t 00:00:10.0 -an out.mp4

I also used native looping and auto-play approach:

<video muted autoPlay loop poster="/static/index/background.jpg" css={videoStyleSheet}>
    <source src="/static/index/output.mp4" type="video/mp4" />
</video>


问:
How to get the original path of a portable Electron app?
I have an Portable Electron App (packed with: electron-builder + asar, portable build) on Windows. I try to get the application path but it returns a path within the user\temp folder rather than the actual '.exe' file

Is there any way to get the original app.exe path?

I've tried the following:

app.getAppPath()

__dirname

require.main.filename

app-root-path

and a few node modules

The path I'm getting from my tests:

C:\Users\xxx\AppData\Local\Temp\xxxxxx.tmp\app

the actual .exe Path (where the app launched from, and what i need):

C:\Users\XXX\Documents\test\dist

I'm just starting with Electron.

答:
I had a lot of trouble with this and was finally able to solve the issue by replacing __dirname by '.', see working example below :</p>

```<code>const path = require('path')
const myAppPath = path.resolve('.', 'myapp.exe');
</code>```

Body:
I had a lot of trouble with this and was finally able to solve the issue by replacing __dirname by '.', see working example below :

const path = require('path')
const myAppPath = path.resolve('.', 'myapp.exe');


答:
You should use <- in do notation and run the function on the unwrapped values.

-- Implementations left out
xsFn :: IO [Int]
xFn :: IO Int

main = do
  xs <- xsFn
  x <- xFn
  -- We've unwrapped the values, so now xs :: [Int] and x :: Int

  let result = f xs x -- result :: [[Int]]
  -- do something with result
  return ()
```

Title: IO values into haskell function


问:
How to combine the Output of Regex Findall in Pandas
I'm exploring regex with pandas in a jupyter notebook.
My goal is to extract housenumberadditions from an addressline, using a set of regex patterns.

I'm building upon this post: https://gist.github.com/christiaanwesterbeek/c574beaf73adcfd74997
and I use this for input from a .csv:

```<code>Afleveradres
Dorpstraat 2
Dorpstr. 2
Dorpstraat 2
Laan 1933 2
18 Septemberplein 12
Kerkstraat 42-f3
Kerk straat 2b
42nd street, 1337a
1e Constantijn Huigensstraat 9b
Maas-Waalweg 15
De Dompelaar 1 B
Kümmersbrucker Straße 2
Friedrichstädter Straße 42-46
Höhenstraße 5A
Saturnusstraat 60-75
Saturnusstraat 60 - 75
Plein \'40-\'45 10
Plein 1945 1
Steenkade t/o 56
Steenkade a/b Twee Gezusters
1, rue de l\'eglise
Herestraat 49 BOX1043
Maas-Waalweg 15 15
</code>```

My goal is to extract the streetnames, housenumbers & housenumberadditions.

So far I basically use:

```<code># get data
file_base_name = 'examples'
dfa = pd.read_csv(''+file_base_name+'.csv', sep=';')

#get number
dfa['num'] = dfa['Afleveradres'].str.extract(r"([,\s]+\d+)\s*")
dfa['num'] = dfa['num'].str.strip()

# split leftover values into street & addition
dfa['tmp']=dfa.Afleveradres.str.replace(r"([,\s]+\d+)\s*", ';')

# new data frame with split value columns
new = dfa["tmp"].str.split(";", n = 1, expand = True)
# making separate first name column from new data frame
dfa["str"]= new[0]

# making separate last name column from new data frame
dfa["add"]= new[1]
dfa.drop(['tmp'], axis=1, inplace=True)

</code>```

which results in:
listing streenames, numbers & addition:

```<code>;Afleveradres;str;add;num
0;Dorpstraat 2;Dorpstraat;;2
1;Dorpstr. 2;Dorpstr.;;2
2;Dorpstraat 2;Dorpstraat;;2
3;Laan 1933 2;Laan;2;1933
4;18 Septemberplein 12;18 Septemberplein;;12
5;Kerkstraat 42-f3;Kerkstraat;-f3;42
6;Kerk straat 2b;Kerk straat;b;2
7;42nd street, 1337a;42nd street;a;, 1337
8;1e Constantijn Huigensstraat 9b;1e Constantijn Huigensstraat;b;9
9;Maas-Waalweg 15;Maas-Waalweg;;15
10;De Dompelaar 1 B;De Dompelaar;B;1
</code>```

So far so good, for now.
Next, I'd like to correct for housenumber ranges, like '42-46' and '60 - 65'.

A re.findall returns expected values:

```<code>import re

def rem(str):
    pattern = r'[,@\'?\.$%_]'
    if re.match(pattern, str):
        tmp = 'Y'
    else:
        tmp = 'N'
    return tmp

def extract_numrange(row):
    r = ''+row['Afleveradres']
    num_range1 = re.findall(r'([,\s]+\d+\-+\d+)\s*|([,\s]+\d+\s+\-+\s+\d+)\s*',r)

    return num_range1
    # return rem(num_range1)

dfa['excep'] = dfa.apply(extract_numrange, axis=1)
dfa

</code>```

output re.findall

```<code>15  Friedrichstädter Straße 42-46   Friedrichstädter Straße -46 42  [( 42-46, )]
16  Höhenstraße 5A  Höhenstraße A   5   []
17  Saturnusstraat 60-75    Saturnusstraat  -75 60  [( 60-75, )]
18  Saturnusstraat 60 - 75  Saturnusstraat  -;  60  [(, 60 - 75)]
</code>```

But how do I clean this output, from [( 42-46, )] and [(, 60 - 75)] into something like 42-46 and 60 - 75 in a new column?

Or are there better approaches for my question?

答:
The problem comes from the fact there are two capturing groups. You need to re-vamp the pattern to use only a single capturing group, or get rid of the group altogether.

Your pattern is of the (Group1)\s*|(Group2)\s* type. As you see, all you need is to re-group the parts into (Group1|Group2)\s*.

So, the quickest fix is

```<code>([,\s]+\d+\-+\d+|[,\s]+\d+\s+\-+\s+\d+)\s*
</code>```

See the regex demo.

However, I think you do not need the whitespaces on both ends. Then, move those patterns you do not want to capture out of the grouping:

```<code>[,\s]+(\d+\-+\d+|\d+\s+\-+\s+\d+)\s*
^^^^^^
</code>```

See this regex demo.

Probably, you may reduce this even further to

```<code>[,\s](\d+(?:-+|\s+-+\s+)\d+)
</code>```

See this regex demo, the (?:-+|\s+-+\s+) is a non-capturing group that won't result in additional tuple item.

Body:
I'm exploring regex with pandas in a jupyter notebook.
My goal is to extract housenumberadditions from an addressline, using a set of regex patterns.

I'm building upon this post: https://gist.github.com/christiaanwesterbeek/c574beaf73adcfd74997
and I use this for input from a .csv:

Afleveradres
Dorpstraat 2
Dorpstr. 2
Dorpstraat 2
Laan 1933 2
18 Septemberplein 12
Kerkstraat 42-f3
Kerk straat 2b
42nd street, 1337a
1e Constantijn Huigensstraat 9b
Maas-Waalweg 15
De Dompelaar 1 B
Kümmersbrucker Straße 2
Friedrichstädter Straße 42-46
Höhenstraße 5A
Saturnusstraat 60-75
Saturnusstraat 60 - 75
Plein \'40-\'45 10
Plein 1945 1
Steenkade t/o 56
Steenkade a/b Twee Gezusters
1, rue de l\'eglise
Herestraat 49 BOX1043
Maas-Waalweg 15 15

My goal is to extract the streetnames, housenumbers & housenumberadditions.

So far I basically use:

# get data
file_base_name = 'examples'
dfa = pd.read_csv(''+file_base_name+'.csv', sep=';')

#get number
dfa['num'] = dfa['Afleveradres'].str.extract(r"([,\s]+\d+)\s*")
dfa['num'] = dfa['num'].str.strip()

# split leftover values into street & addition
dfa['tmp']=dfa.Afleveradres.str.replace(r"([,\s]+\d+)\s*", ';')

# new data frame with split value columns
new = dfa["tmp"].str.split(";", n = 1, expand = True)
# making separate first name column from new data frame
dfa["str"]= new[0]

# making separate last name column from new data frame
dfa["add"]= new[1]
dfa.drop(['tmp'], axis=1, inplace=True)

which results in:
listing streenames, numbers & addition:

;Afleveradres;str;add;num
0;Dorpstraat 2;Dorpstraat;;2
1;Dorpstr. 2;Dorpstr.;;2
2;Dorpstraat 2;Dorpstraat;;2
3;Laan 1933 2;Laan;2;1933
4;18 Septemberplein 12;18 Septemberplein;;12
5;Kerkstraat 42-f3;Kerkstraat;-f3;42
6;Kerk straat 2b;Kerk straat;b;2
7;42nd street, 1337a;42nd street;a;, 1337
8;1e Constantijn Huigensstraat 9b;1e Constantijn Huigensstraat;b;9
9;Maas-Waalweg 15;Maas-Waalweg;;15
10;De Dompelaar 1 B;De Dompelaar;B;1

So far so good, for now.
Next, I'd like to correct for housenumber ranges, like '42-46' and '60 - 65'.

A re.findall returns expected values:

import re

def rem(str):
    pattern = r'[,@\'?\.$%_]'
    if re.match(pattern, str):
        tmp = 'Y'
    else:
        tmp = 'N'
    return tmp

def extract_numrange(row):
    r = ''+row['Afleveradres']
    num_range1 = re.findall(r'([,\s]+\d+\-+\d+)\s*|([,\s]+\d+\s+\-+\s+\d+)\s*',r)

    return num_range1
    # return rem(num_range1)

dfa['excep'] = dfa.apply(extract_numrange, axis=1)
dfa

output re.findall

15  Friedrichstädter Straße 42-46   Friedrichstädter Straße -46 42  [( 42-46, )]
16  Höhenstraße 5A  Höhenstraße A   5   []
17  Saturnusstraat 60-75    Saturnusstraat  -75 60  [( 60-75, )]
18  Saturnusstraat 60 - 75  Saturnusstraat  -;  60  [(, 60 - 75)]

But how do I clean this output, from [( 42-46, )] and [(, 60 - 75)] into something like 42-46 and 60 - 75 in a new column?

Or are there better approaches for my question?

Body:
The problem comes from the fact there are two capturing groups. You need to re-vamp the pattern to use only a single capturing group, or get rid of the group altogether.

Your pattern is of the (Group1)\s*|(Group2)\s* type. As you see, all you need is to re-group the parts into (Group1|Group2)\s*.

So, the quickest fix is

([,\s]+\d+\-+\d+|[,\s]+\d+\s+\-+\s+\d+)\s*

See the regex demo.

However, I think you do not need the whitespaces on both ends. Then, move those patterns you do not want to capture out of the grouping:

[,\s]+(\d+\-+\d+|\d+\s+\-+\s+\d+)\s*
^^^^^^

See this regex demo.

Probably, you may reduce this even further to

[,\s](\d+(?:-+|\s+-+\s+)\d+)

See this regex demo, the (?:-+|\s+-+\s+) is a non-capturing group that won't result in additional tuple item.


问:
Mixing HTML and Python code - how to refer to a changing filename within the HTML code
I'm trying to automate a process where I take a snapshot everyday but change the filename to that date. For example, I'd like to reference today's file as "20200219 snapshot.png" and change it to "20200220 snapshot.png" tomorrow. The problem is, I can't input the variable name filename after the img src and have to put in the hardcoded exact String.

```<code>date = date.strftime('%Y%m%d')
filename = date + " snapshot.png"

html = """\
<html>
  <head></head>
    <body>
      <img src="Directory/snapshot.png"/>
    </body>
</html>
"""
</code>```

答:
You can use ElementTree to parse through the HTML DOM, use the find method to search for img tag. Then you can assign the src attribute value. The attributes are returned as a dict with the attrib parameter and you just need to look for the 'src' key:

```<code>import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
filename = date + " snapshot.png"
import xml.etree.ElementTree as et

html = """\
<html>
  <head></head>
    <body>
      <img src="Directory/snapshot.png"/>
    </body>
</html>
"""
tree = et.fromstring(html)
image_attributes = tree.find('body/img').attrib
for k in image_attributes.keys():
    if 'src' in k:
        image_attributes[k] = filename
html_new = et.tostring(tree)
print(html_new)
</code>```

Output:

```<code>b'<html>\n  <head />\n    <body>\n      <img src="20200220 snapshot.png" />\n    </body>\n</html>'
</code>```

To pretty print this output, you can use the method provided in official docs here and just do:

```<code>et.dump(tree)
</code>```

Output:

```<code><html>
  <head />
    <body>
      <img src="20200220 snapshot.png" />
    </body>
</html>
</code>```

Body:
I'm trying to automate a process where I take a snapshot everyday but change the filename to that date. For example, I'd like to reference today's file as "20200219 snapshot.png" and change it to "20200220 snapshot.png" tomorrow. The problem is, I can't input the variable name filename after the img src and have to put in the hardcoded exact String.

date = date.strftime('%Y%m%d')
filename = date + " snapshot.png"

html = """\

"""

Body:
You can use ElementTree to parse through the HTML DOM, use the find method to search for img tag. Then you can assign the src attribute value. The attributes are returned as a dict with the attrib parameter and you just need to look for the 'src' key:

import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
filename = date + " snapshot.png"
import xml.etree.ElementTree as et

html = """\
<html>
  <head></head>
    <body>
      <img src="Directory/snapshot.png"/>
    </body>
</html>
"""
tree = et.fromstring(html)
image_attributes = tree.find('body/img').attrib
for k in image_attributes.keys():
    if 'src' in k:
        image_attributes[k] = filename
html_new = et.tostring(tree)
print(html_new)

Output:

b'<html>\n  <head />\n    <body>\n      <img src="20200220 snapshot.png" />\n    </body>\n</html>'

To pretty print this output, you can use the method provided in official docs here and just do:

et.dump(tree)

Output:

<html>
  <head />
    <body>
      <img src="20200220 snapshot.png" />
    </body>
</html>


问:
Calculating the speed of routines?
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

```<code>// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process
</code>```

I look forward to hearing some suggestions.

Thanks.

Craig.

答:
I ask because I am currently trying to
  optimize a few functions

It is natural to think that measuring is how you find out what to optimize, but there's a better way.

If something takes a large enough fraction of time (F) to be worth optimizing, then if you simply pause it at random, F is the probability you will catch it in the act.
Do that several times, and you will see precisely why it's doing it, down to the exact lines of code.

More on that.
Here's an example.

Fix it, and then do an overall measurement to see how much you saved, which should be about F.
Rinse and repeat.

Title: Calculating the speed of routines?

Body:
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process

I look forward to hearing some suggestions.

Thanks.

Craig.


问:
Three.js usage with stencil buffer
I can't get the following to draw the scene into the shape created as a stencil mask. Instead the code just seems to render the stencil itself as a black object.

http://signaturefloors.dev.flooradvisor.com.au/productapp/floor_align.php

My render function is:

```<code>var gl = floor_align.renderer.domElement.getContext('webgl') || floor_align.renderer.domElement.getContext('experimental-webgl');
gl.clearStencil(0);
gl.clear(gl.STENCIL_BUFFER_BIT);
gl.enable(gl.STENCIL_TEST);
gl.stencilFunc(gl.ALWAYS, 1, 1);
gl.stencilOp(gl.KEEP, gl.REPLACE, gl.REPLACE);
gl.colorMask(0, 0, 0, 0);

// Floor Mask (Create a stencil that we render the next pass into)
floor_align.renderer.render(floor_align.maskScene, floor_align.maskCamera);

gl.colorMask(1, 1, 1, 1);
gl.stencilFunc(gl.NOTEQUAL, 1, 1);
gl.stencilOp(gl.KEEP, gl.REPLACE, gl.REPLACE);

// Render a floor pass
floor_align.renderer.render(floor_align.scene, floor_align.camera);

gl.disable(gl.STENCIL_TEST);
</code>```

The renderer has autoClear = false;

答:
Accepted answer don't work on latest threejs. If anyone interested, here's an up-to-date version that works (using r111):

        gl.enable(gl.STENCIL_TEST);
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);

        //renderer.clear(); <-- works without this too

        gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
        gl.stencilMask(0xFF);
        renderer.render(maskScene, camera);

        gl.stencilFunc(gl.EQUAL, 1, 0xFF);
        gl.stencilMask(0x00);

        renderer.render(scene, camera);
        gl.stencilMask(0xFF);
        gl.disable(gl.STENCIL_TEST);
```

Also in my case I didn't disable auto-clear and it still works.

Title: Three.js usage with stencil buffer

Body:
I can't get the following to draw the scene into the shape created as a stencil mask. Instead the code just seems to render the stencil itself as a black object.

http://signaturefloors.dev.flooradvisor.com.au/productapp/floor_align.php

My render function is:

var gl = floor_align.renderer.domElement.getContext('webgl') || floor_align.renderer.domElement.getContext('experimental-webgl');
gl.clearStencil(0);
gl.clear(gl.STENCIL_BUFFER_BIT);
gl.enable(gl.STENCIL_TEST);
gl.stencilFunc(gl.ALWAYS, 1, 1);
gl.stencilOp(gl.KEEP, gl.REPLACE, gl.REPLACE);
gl.colorMask(0, 0, 0, 0);

// Floor Mask (Create a stencil that we render the next pass into)
floor_align.renderer.render(floor_align.maskScene, floor_align.maskCamera);

gl.colorMask(1, 1, 1, 1);
gl.stencilFunc(gl.NOTEQUAL, 1, 1);
gl.stencilOp(gl.KEEP, gl.REPLACE, gl.REPLACE);

// Render a floor pass
floor_align.renderer.render(floor_align.scene, floor_align.camera);

gl.disable(gl.STENCIL_TEST);

The renderer has autoClear = false;

Body:
Accepted answer don't work on latest threejs. If anyone interested, here's an up-to-date version that works (using r111):

        gl.enable(gl.STENCIL_TEST);
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);

        //renderer.clear(); <-- works without this too

        gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
        gl.stencilMask(0xFF);
        renderer.render(maskScene, camera);

        gl.stencilFunc(gl.EQUAL, 1, 0xFF);
        gl.stencilMask(0x00);

        renderer.render(scene, camera);
        gl.stencilMask(0xFF);
        gl.disable(gl.STENCIL_TEST);

Also in my case I didn't disable auto-clear and it still works.


问:
Ruby undefined method '**'
I'm attempting to write a function that uses array methods to do a variety of things. I need to use the each method to print the cube of each element in the array. Here's my code.

```<code>def foo(a)

    a.each { |x| puts x ** 3 }

    a.each_slice(3) { |x| puts x }
    a.select do |x|

        if x%5 == 0
            puts x
        end
    end

    a.map { |x| x ** 3 }
    aa.inject(0) { |x, y| x * y }

end

a = Array.new(50)
a.each { |x| x = rand(10..100) }

foo(a)
</code>```

I keep getting this error:

```<code>Traceback (most recent call last):
        3: from task2.rb:21:in `<main>'
        2: from task2.rb:3:in `foo'
        1: from task2.rb:3:in `each'
task2.rb:3:in `block in foo': undefined method `**' for nil:NilClass (NoMethodError)
</code>```

答:
You're not modifying your array of 50 nil values.  Try map! instead.

```<code>a.map! { |x| x = rand(10..100) }
</code>```

Not sure exactly what the rest of your code is supposed to do but this seems more likely it.

```<code>def foo(a)
  a.each { |x| puts x ** 3 }
  a.each_slice(3) { |x| puts x }
  a.each do |x| # not sure why you wanted select, does not make sense here
    if x % 5 == 0
      puts x
    end
  end

  a.map { |x| x ** 3 }
   .inject(0) { |x, y| x * y }
end

array = Array.new(50)
array.map! { |x| x = rand(10..100) }

foo(array)
</code>```

Title: Ruby undefined method '**'

Body:
I'm attempting to write a function that uses array methods to do a variety of things. I need to use the each method to print the cube of each element in the array. Here's my code.

def foo(a)

    a.each { |x| puts x ** 3 }

    a.each_slice(3) { |x| puts x }
    a.select do |x|

        if x%5 == 0
            puts x
        end
    end

    a.map { |x| x ** 3 }
    aa.inject(0) { |x, y| x * y }

end

a = Array.new(50)
a.each { |x| x = rand(10..100) }

foo(a)

I keep getting this error:

Traceback (most recent call last):
        3: from task2.rb:21:in `'
        2: from task2.rb:3:in `foo'
        1: from task2.rb:3:in `each'
task2.rb:3:in `block in foo': undefined method `**' for nil:NilClass (NoMethodError)

Body:
You're not modifying your array of 50 nil values.  Try map! instead.

a.map! { |x| x = rand(10..100) }

Not sure exactly what the rest of your code is supposed to do but this seems more likely it.

def foo(a)
  a.each { |x| puts x ** 3 }
  a.each_slice(3) { |x| puts x }
  a.each do |x| # not sure why you wanted select, does not make sense here
    if x % 5 == 0
      puts x
    end
  end

  a.map { |x| x ** 3 }
   .inject(0) { |x, y| x * y }
end

array = Array.new(50)
array.map! { |x| x = rand(10..100) }

foo(array)


问:
How to fix react-native-gesture-handler error not working
I create a new project in react-native ,then install (npm install --save react-navigation npm install --save react-native-gesture-handler),
the latest version (react-native: 0.60.0) auto linking so,I not link ,but still is showing error,
!https://prnt.sc/oaxxuc

Task :react-native-gesture-handler:compileDebugJavaWithJavac **FAILED**

After I uninstall gesture-handler this kind of error showing
!https://prnt.sc/oaxx8i

Please help to solve this error

The react-native latest version:-

```<code> System:
     OS: Linux 4.15 Ubuntu 16.04.5 LTS (Xenial Xerus)
     react: 16.8.6 => 16.8.6
     react-native: 0.60.0 => 0.60.0    npmGlobalPackages:
     react-native-cli: 2.0.1
</code>```

thanks

答:
You should paste import 'react-native-gesture-handler'; on the top of index.js which is standard in react native out of the box.

the entry of your app. This is the file where you import your App.js file, its written clearly in the documentations.

documents here https://reactnavigation.org/docs/en/getting-started.html

Body:
I create a new project in react-native ,then install (npm install --save react-navigation npm install --save react-native-gesture-handler),
the latest version (react-native: 0.60.0) auto linking so,I not link ,but still is showing error,
!https://prnt.sc/oaxxuc

Task :react-native-gesture-handler:compileDebugJavaWithJavac **FAILED**

After I uninstall gesture-handler this kind of error showing
!https://prnt.sc/oaxx8i

Please help to solve this error

The react-native latest version:-

 System:
     OS: Linux 4.15 Ubuntu 16.04.5 LTS (Xenial Xerus)
     react: 16.8.6 => 16.8.6
     react-native: 0.60.0 => 0.60.0    npmGlobalPackages:
     react-native-cli: 2.0.1

thanks


问:
Unable to render Mp4 Video in R Shiny App
All I get is a solid white background where there should be a video playing. If you click the download link in the shiny app video box, you can download a video that plays as expected in Quicktime.

Link to the source video is here. I placed the video in a www folder where my app.R file lives. I'm on a Mac using Chrome and Safari.

```<code>library(shiny)

ui <- fluidPage(

    # Application title
    titlePanel("Video Compatibility"),

    sidebarLayout(
        sidebarPanel(
            "side bar text"
        ),

        mainPanel(
            p("Video Below"),
            tags$video(
                src = "SampleVideo_640x360_1mb.mp4",
                type = "video/mp4",
                autoplay=TRUE,
                muted=TRUE,
                playsinline=TRUE,
                loop=TRUE,
                controls=TRUE),
            p("Video above")

        )
    )
)

server <- function(input, output) {

}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

答:
It looks like when you use shinyApp it will not automatically serve files from the www folder. This is likely because you are passing in functions rather than a path to an application folder so it doesn't assume you want to look in your current directory for files.

Before running shinyApp, you could run

```<code>addResourcePath("vid", directoryPath = './www')
</code>```

and update your path for the video to be

```<code>src = "vid/SampleVideo_640x360_1mb.mp4",
</code>```

This will tell shiny where to look for files with a given URL path prefix.

Body:
All I get is a solid white background where there should be a video playing. If you click the download link in the shiny app video box, you can download a video that plays as expected in Quicktime.

Link to the source video is here. I placed the video in a www folder where my app.R file lives. I'm on a Mac using Chrome and Safari.

library(shiny)

ui <- fluidPage(

    # Application title
    titlePanel("Video Compatibility"),

    sidebarLayout(
        sidebarPanel(
            "side bar text"
        ),

        mainPanel(
            p("Video Below"),
            tags$video(
                src = "SampleVideo_640x360_1mb.mp4",
                type = "video/mp4",
                autoplay=TRUE,
                muted=TRUE,
                playsinline=TRUE,
                loop=TRUE,
                controls=TRUE),
            p("Video above")

        )
    )
)

server <- function(input, output) {

}

# Run the application
shinyApp(ui = ui, server = server)

Body:
It looks like when you use shinyApp it will not automatically serve files from the www folder. This is likely because you are passing in functions rather than a path to an application folder so it doesn't assume you want to look in your current directory for files.

Before running shinyApp, you could run

addResourcePath("vid", directoryPath = './www')

and update your path for the video to be

src = "vid/SampleVideo_640x360_1mb.mp4",

This will tell shiny where to look for files with a given URL path prefix.


问:
Are my Apache2 RewriteEngine On and AllowOverride All changes secure?
I made some changes to my website configuration in order to get friendly urls working on Xenforo2 running on Apache2.

a) I turned RewriteEngine "On" in my .htaccess file

b) I modified RewriteBase  to '/' in my .htaccess file

c) I changed AllowOverride from "None" to "All" in the  section of my Apache2 configuration.

Do any of these changes open me up to security problems down the line?
My apache2 version is 2.4.25 (Debian)

答:
No. Those 3 additions/modifications to your .htaccess file and apache config pose no direct security risk.

Turning on RewriteEngine is simply that. Allowing htaccess to make redirects etc.

Changing the RewriteBase simply sets the base url that redirects will happen from. More information can be found here: How does RewriteBase work in .htaccess

Setting AllowOverride from None to All in your apache configuration allows your .htaccess file to work at all. If it was set to None, your .htaccess would not work, as htaccess is an override of your apache config.


问:
How can I refer to an ng-template using a string?
I have the following in my angular component.html file:

<nz-collapse *ngFor="let optimization of optimizations; trackBy: trackByTip">
  <nz-collapse-panel [nzHeader]="header" [nzExtra]="optimization.type">
    <ng-template #header>
    </ng-template>
    <ng-template #HAS_TOO_FEW>
    </ng-template>
  </nz-collapse-panel>
</nz-collapse>
```

The value of optimization.type in this case is a string. As I loop through each item (optimization), I want the appropriate template, if available, to be referenced. For this case, optimization.type yields string "HAS_TOO_FEW" which should refer to the #HAS_TOO_FEW template. How can I get the string to refer to the template this way?

Note that if a template doesn't exist for the corresponding optimization.type, I want the value to be effectively [nzExtra]="null".

I'm very new to Angular so if my entire approach is wrong or not idiomatic, please suggest a different approach. Thank you.

答:
You can use NgSwitch to select various templates based on the value of optimization.type.

If you wrap that whole NgSwitch chunk in an <ng-template> block, you can pass that in as a TemplateRef input.

<nz-collapse *ngFor="let optimization of optimizations; trackBy: trackByTip">
    <nz-collapse-panel [nzHeader]="header" [nzExtra]="optimizationTypeTemplate">

        <ng-template #header>
        </ng-template>

        <ng-template #optimizationTypeTemplate>
            <ng-container [ngSwitch]="optimization.type">
                <ng-container *ngSwitchCase="'HAS_TOO_FEW'">
                    Too few!!
                </ng-container>
                <ng-container *ngSwitchCase="'HAS_TOO_MANY'">
                    Too many!!
                </ng-container>
                <ng-container *ngSwitchDefault>
                    This is the null case
                </ng-container>
            </ng-container>
        </ng-template>

    </nz-collapse-panel>
</nz-collapse>
```

Body:
I have the following in my angular component.html file:

<nz-collapse *ngFor="let optimization of optimizations; trackBy: trackByTip">
  <nz-collapse-panel [nzHeader]="header" [nzExtra]="optimization.type">
    <ng-template #header>
    </ng-template>
    <ng-template #HAS_TOO_FEW>
    </ng-template>
  </nz-collapse-panel>
</nz-collapse>

The value of optimization.type in this case is a string. As I loop through each item (optimization), I want the appropriate template, if available, to be referenced. For this case, optimization.type yields string "HAS_TOO_FEW" which should refer to the #HAS_TOO_FEW template. How can I get the string to refer to the template this way?

Note that if a template doesn't exist for the corresponding optimization.type, I want the value to be effectively [nzExtra]="null".

I'm very new to Angular so if my entire approach is wrong or not idiomatic, please suggest a different approach. Thank you.


问:
Implementing XSD's Exception Classes in Spring Web Service (SOAP)
I'm creating a SOAP web service in Spring Boot using Spring WS.  The service I am recreating is a clone of a Service running on older technology which uses JavaX JWS, with the classes generated from an XSD.

The issues I have are linked/the same really:
1. I can't seem to 'receive' Exceptions thrown in the 'new' Web Service back to the consumer.

2. When querying the endpoint in SOAPUI, the Exception class for the Web Service appears as if it is a one-way method.

I believe this is because Spring WS isn't correctly implementing/understanding the Exception classes.

When an exception is thrown in the new service, the consumer receives a com.sun.xml.internal.ws.fault.ServerSOAPFaultException, rather than the Exception thrown in the Web Service.

The original JavaX service returns (using TestException as an example):

```<code><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
         <faultcode>S:Server</faultcode>
         <faultstring>Test</faultstring>
         <detail>
            <ns2:TestException xmlns:ns2="http://test.co.uk/">
               <code>abc123</code>
               <message>Test</message>
            </ns2:TestException>
         </detail>
      </S:Fault>
   </S:Body>
</S:Envelope>
</code>```

I can't find any documentation or guidance on how the exception should be build/configured to produce the same <ns2> nested element.  Is there a way to accurately pass the exception back so that it appears the same as it would in the service?

答: Here are some examples of implementing custom exception resolver which extends AbstractEndpointExceptionResolver and defines SOAP fault mapping for different exception types: example 1, example 2, example 3.</p>

Body:
I'm creating a SOAP web service in Spring Boot using Spring WS.  The service I am recreating is a clone of a Service running on older technology which uses JavaX JWS, with the classes generated from an XSD.

The issues I have are linked/the same really:
1. I can't seem to 'receive' Exceptions thrown in the 'new' Web Service back to the consumer.

2. When querying the endpoint in SOAPUI, the Exception class for the Web Service appears as if it is a one-way method.

I believe this is because Spring WS isn't correctly implementing/understanding the Exception classes.

When an exception is thrown in the new service, the consumer receives a com.sun.xml.internal.ws.fault.ServerSOAPFaultException, rather than the Exception thrown in the Web Service.

The original JavaX service returns (using TestException as an example):

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
         <faultcode>S:Server</faultcode>
         <faultstring>Test</faultstring>
         <detail>
            <ns2:TestException xmlns:ns2="http://test.co.uk/">
               abc123
               <message>Test</message>
            </ns2:TestException>
         </detail>
      </S:Fault>
   </S:Body>
</S:Envelope>

I can't find any documentation or guidance on how the exception should be build/configured to produce the same <ns2> nested element.  Is there a way to accurately pass the exception back so that it appears the same as it would in the service?


问:
Is there a way to disable the scrollbar / list bounce effect in flex 4.5 (mobile)?
I'm trying to make my own component that behaves like a list and supports infinite scrolling (in 1-dimension : vertical or horizontal) - both directions. For eg, a vertically laid out list which the user can scroll up or down forever - without ever hitting the 'last' or 'first' item. A good use for this: a calendar that displays each month as a list item.

Anyway, there are a bunch of things to overcome. The first of which, I think, is to disable the scrollbar's bounce effects (introduced in the latest Flex 4.5 (mobile) SDK).

If I can disable the bounce effects, I'm guessing I can then add/remove items as needed to the list and it would scroll infinitely.

Any ideas?

Krishna

答:
Personally, an infinite list would mean a lot of rework of the core List component.  It's a lot of work to reverse engineer and you'll probably hit a wall.  I think what you want to do is create a component from scratch and extends SkinnableContainer.

From here on out, you need to decide how to implement and what's the user interaction for an infinite list, then need to implement proper practices and reuse your item renderers.


问:
UIView in UITableView is changing frame automatically
I have this UIView added to my UITableView:

```<code>self.tableView.addSubview(viewInfoPlus)
self.viewInfoPlus.frame = CGRect.init(x: kWidth - 193 - 32, y: 751, width: 193, height: 103)
</code>```

The one signaled with the red arrow.

The UIView in the screenshot have the right frame but when I try to reload the UITableView or just some cell/cells using:

```<code>let indexPath = IndexPath.init(row: 0, section: TableSection.plus.rawValue)
UIView.setAnimationsEnabled(false)
self.tableView.beginUpdates()
tableView.reloadRows(at: [indexPath], with: .none)
self.tableView.endUpdates()
UIView.setAnimationsEnabled(true)
</code>```

The UIView automatically change the frame to the wrong one as you can see in this screenshot.
But when the user scroll to the top of UITableVIew the UIView automatically change again their frame to the right one.
Obviously I never changed the frame in the code.

答:
Use Constraints instead of frame.

Setting Frames there is no guarantee when resize.  Autolayout allows view that dynamically adjust to different size classes and positions. Check following example

Example:

```<code>viewInfoPlus.translatesAutoresizingMaskIntoConstraints = false
viewInfoPlus.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
viewInfoPlus.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 20).isActive = true
viewInfoPlus.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
viewInfoPlus.heightAnchor.constraint(equalToConstant: 103).isActive = true
</code>```

Body:
I have this UIView added to my UITableView:

self.tableView.addSubview(viewInfoPlus)
self.viewInfoPlus.frame = CGRect.init(x: kWidth - 193 - 32, y: 751, width: 193, height: 103)

The one signaled with the red arrow.

The UIView in the screenshot have the right frame but when I try to reload the UITableView or just some cell/cells using:

let indexPath = IndexPath.init(row: 0, section: TableSection.plus.rawValue)
UIView.setAnimationsEnabled(false)
self.tableView.beginUpdates()
tableView.reloadRows(at: [indexPath], with: .none)
self.tableView.endUpdates()
UIView.setAnimationsEnabled(true)

The UIView automatically change the frame to the wrong one as you can see in this screenshot.
But when the user scroll to the top of UITableVIew the UIView automatically change again their frame to the right one.
Obviously I never changed the frame in the code.

Body:
Use Constraints instead of frame.

Setting Frames there is no guarantee when resize.  Autolayout allows view that dynamically adjust to different size classes and positions. Check following example

Example:

viewInfoPlus.translatesAutoresizingMaskIntoConstraints = false
viewInfoPlus.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
viewInfoPlus.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 20).isActive = true
viewInfoPlus.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
viewInfoPlus.heightAnchor.constraint(equalToConstant: 103).isActive = true


问:
Spring Boot metrics http.client.requests do not work for WebClient reactive applications
I have a spring boot 2.2.2 microservices, which integrations with other services using WebClient (rective). According to Spring documentation, the actuator should return "http.client.requests" metrics by default as Timer is enabled by default. But it does not work for me. I am able to get http.server.requests" metrics.

My WebClient is a bean configured and build with WebClient.builder(), as documented here: https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-metrics-http-clients

答:
Use Spring Boot's preconfigured WebClient.Builder instead of WebClient.builder() to have an instance of WebClient.

You can find more detail here.

As in the following you can have a bean of WebClient.

```<code>@Configuration
public class ClientConfiguration {

    @Bean
    public WebClient webClient(WebClient.Builder webClientBuilder) {
        return webClientBuilder
                .baseUrl("https://example.org")
                .build();
    }
}
</code>```

WebClient.Builder is an Auto-configuration, means the injected point above will receive a newly cloned instance of the builder.

Here is the source for WebClientAutoConfiguration

Body:
Use Spring Boot's preconfigured WebClient.Builder instead of WebClient.builder() to have an instance of WebClient.

You can find more detail here.

As in the following you can have a bean of WebClient.

@Configuration
public class ClientConfiguration {

    @Bean
    public WebClient webClient(WebClient.Builder webClientBuilder) {
        return webClientBuilder
                .baseUrl("https://example.org")
                .build();
    }
}

WebClient.Builder is an Auto-configuration, means the injected point above will receive a newly cloned instance of the builder.

Here is the source for WebClientAutoConfiguration


问:
Return complete XML response from ASP .NET Core Web API method
I'm approaching ASP.NET Core taking advantage of a customer request about a web service.

The request is a web method that returns data in XML format, like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Person>
  <Name>John</Name>
  <Surname>Doe</Surname>
  . . .
</Person>
</code>```

I can make the web service return text/xml data as requested forcing it in the ConfigureServices method inside Startup.cs like following:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddMvc(options =>
    {
        options.Filters.Add(new ProducesAttribute("text/xml"));
    }).AddXmlSerializerFormatters();
}
</code>```

The problem is that when I call the method that should return data I don't have the XML declaration header, required by the customer for some reason:

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

This is the result:

```<code><Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Name>John</Name>
    <Surname>Doe</Surname>
</Person>
</code>```

Here is the method:

```<code>[HttpGet("getperson")]
public Person GetPerson()
{
    return new Person
    {
        Name = "John",
        Surname = "Doe",
    };
}
</code>```

And here the class Person:

```<code>public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
}
</code>```

I researched a lot, but everything I found didn't help me at all. I'd like to use the framework's features serializing my classes instead of having to build the XML structure node by node, so I was hoping in some settings inside the services that would allow me to do so.

Any changes to the GetPerson method can be done if necessary, this is just a really simplified test.

Thank you in advance for the help!

答:
You need to configure XML output formatter like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddMvc(options =>
    {
        options.Filters.Add(new ProducesAttribute("text/xml"));
        options.OutputFormatters.Add(new XmlSerializerOutputFormatter(new XmlWriterSettings
        {
            OmitXmlDeclaration = false
        }));
    }).AddXmlSerializerFormatters();
}
```

<p>Sample output:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <string>value1</string>
    <string>value2</string>
</ArrayOfString>
</code>```

Body:
I'm approaching ASP.NET Core taking advantage of a customer request about a web service.

The request is a web method that returns data in XML format, like this:

<?xml version="1.0" encoding="UTF-8"?>
<Person>
  <Name>John</Name>
  <Surname>Doe</Surname>
  . . .
</Person>

I can make the web service return text/xml data as requested forcing it in the ConfigureServices method inside Startup.cs like following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddMvc(options =>
    {
        options.Filters.Add(new ProducesAttribute("text/xml"));
    }).AddXmlSerializerFormatters();
}

The problem is that when I call the method that should return data I don't have the XML declaration header, required by the customer for some reason:

<?xml version="1.0" encoding="UTF-8"?>

This is the result:

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Name>John</Name>
    <Surname>Doe</Surname>
</Person>

Here is the method:

[HttpGet("getperson")]
public Person GetPerson()
{
    return new Person
    {
        Name = "John",
        Surname = "Doe",
    };
}

And here the class Person:

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

I researched a lot, but everything I found didn't help me at all. I'd like to use the framework's features serializing my classes instead of having to build the XML structure node by node, so I was hoping in some settings inside the services that would allow me to do so.

Any changes to the GetPerson method can be done if necessary, this is just a really simplified test.

Thank you in advance for the help!

Body:
You need to configure XML output formatter like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddMvc(options =>
    {
        options.Filters.Add(new ProducesAttribute("text/xml"));
        options.OutputFormatters.Add(new XmlSerializerOutputFormatter(new XmlWriterSettings
        {
            OmitXmlDeclaration = false
        }));
    }).AddXmlSerializerFormatters();
}

Sample output:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <string>value1</string>
    <string>value2</string>
</ArrayOfString>


问:
Google Colab (tensorflow) aan visulizer
I am trying to visualise my neural network architecture on Google Colab. However, for some reason it is not producing any visual outcome. Could you tell me why my code does not work on Colab? I cannot use anything like python IDE. It has to be Google Colab.</p>

```<code>!pip3 install keras
!pip3 install ann_visualizer
!pip install graphviz

from keras.models import Sequential
from keras.layers import Dense
from ann_visualizer.visualize import ann_viz

network = Sequential()
#Hidden Layer#1
network.add(Dense(units=2, activation='relu',  kernel_initializer='uniform', input_dim=2))
#Output Layer
network.add(Dense(units=1, activation='sigmoid', kernel_initializer='uniform'))
ann_viz(network, title="")
</code>```

答:
One workaround would be to give your call to ann_viz a filename and then download the file.

```<code>ann_viz(network, view=True, title="test", filename="visualized")
</code>```

Now when you click the file folder on the left, you'll see the output file as a PDF with the filename 'visualized'.

Title: Google Colab (tensorflow) aan visulizer

Body:
I am trying to visualise my neural network architecture on Google Colab. However, for some reason it is not producing any visual outcome. Could you tell me why my code does not work on Colab? I cannot use anything like python IDE. It has to be Google Colab.

!pip3 install keras
!pip3 install ann_visualizer
!pip install graphviz

from keras.models import Sequential
from keras.layers import Dense
from ann_visualizer.visualize import ann_viz

network = Sequential()
#Hidden Layer#1
network.add(Dense(units=2, activation='relu',  kernel_initializer='uniform', input_dim=2))
#Output Layer
network.add(Dense(units=1, activation='sigmoid', kernel_initializer='uniform'))
ann_viz(network, title="")

Body:
One workaround would be to give your call to ann_viz a filename and then download the file.

ann_viz(network, view=True, title="test", filename="visualized")

Now when you click the file folder on the left, you'll see the output file as a PDF with the filename 'visualized'.


答:
This line:

```<code>a.each { |x| x = rand(10..100) }
</code>```

doesn't do what you think it does.  Each does not alter the original array.  If you want to change the original values of a you need a map!.

```<code>irb(main):025:0> a = Array.new(50)
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
irb(main):026:0> a.each { |x| x = rand(10..100) }
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
irb(main):027:0> a
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
irb(main):028:0> a.map { |x| x = rand(10..100) }
=> [67, 34, 96, 50, 52, 68, 14, 88, 67, 19, 83, 40, 35, 98, 88, 98, 39, 73, 41, 60, 25, 47, 33, 73, 20, 41, 32, 19, 65, 67, 47, 14, 11, 67, 32, 32, 13, 36, 23, 100, 14, 10, 73, 20, 59, 94, 54, 25, 57, 28]
irb(main):029:0>
a
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

 a.map! { |x| x = rand(10..100) }
=> [97, 83, 52, 54, 22, 54, 39, 32, 42, 70, 84, 15, 69, 32, 28, 40, 50, 98, 66, 79, 25, 37, 97, 28, 30, 11, 98, 57, 73, 77, 99, 75, 72, 40, 67, 62, 87, 41, 58, 10, 88, 24, 98, 10, 31, 94, 53, 43, 98, 17]
irb(main):032:0> a
=> [97, 83, 52, 54, 22, 54, 39, 32, 42, 70, 84, 15, 69, 32, 28, 40, 50, 98, 66, 79, 25, 37, 97, 28, 30, 11, 98, 57, 73, 77, 99, 75, 72, 40, 67, 62, 87, 41, 58, 10, 88, 24, 98, 10, 31, 94, 53, 43, 98, 17]
irb(main):033:0>
</code>```

Also the preferred way to do this is with a range IMO.

Title: Ruby undefined method '**'

Body:
This line:

a.each { |x| x = rand(10..100) }

doesn't do what you think it does.  Each does not alter the original array.  If you want to change the original values of a you need a map!.

irb(main):025:0> a = Array.new(50)
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
irb(main):026:0> a.each { |x| x = rand(10..100) }
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
irb(main):027:0> a
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
irb(main):028:0> a.map { |x| x = rand(10..100) }
=> [67, 34, 96, 50, 52, 68, 14, 88, 67, 19, 83, 40, 35, 98, 88, 98, 39, 73, 41, 60, 25, 47, 33, 73, 20, 41, 32, 19, 65, 67, 47, 14, 11, 67, 32, 32, 13, 36, 23, 100, 14, 10, 73, 20, 59, 94, 54, 25, 57, 28]
irb(main):029:0>
a
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

 a.map! { |x| x = rand(10..100) }
=> [97, 83, 52, 54, 22, 54, 39, 32, 42, 70, 84, 15, 69, 32, 28, 40, 50, 98, 66, 79, 25, 37, 97, 28, 30, 11, 98, 57, 73, 77, 99, 75, 72, 40, 67, 62, 87, 41, 58, 10, 88, 24, 98, 10, 31, 94, 53, 43, 98, 17]
irb(main):032:0> a
=> [97, 83, 52, 54, 22, 54, 39, 32, 42, 70, 84, 15, 69, 32, 28, 40, 50, 98, 66, 79, 25, 37, 97, 28, 30, 11, 98, 57, 73, 77, 99, 75, 72, 40, 67, 62, 87, 41, 58, 10, 88, 24, 98, 10, 31, 94, 53, 43, 98, 17]
irb(main):033:0>

Also the preferred way to do this is with a range IMO.


问:
Use equivalent of jQuery.get() in wix corvid
I created a Chrome plug-in extension with the following code :

```<code>$.ajax({
  type: 'GET',
  url: page_url
  success: function(responseText){ ...
</code>```

In Wix corvid, I tried to use a fetch request by it is blocked due to CORS policy at the web server.

Aynone would know how to translate the equivalent of an ajax get request in Wix corvid ?

Thanks,

Hugues

答:
If you want to use GET do this.

```<code>//myfile.jsw

export async function myBackendFnc() {
   const response = await fetch("https://api.website.com", {
      method: 'GET',
   });
   const json = await response.json();
   return json;
}
</code>```

If the external web server is blocking this request then that is something you need to figure out with the external server on how to whitelist your ip.

You can use the GET from both your page or a server side code using a backend file.

Body:
I created a Chrome plug-in extension with the following code :

$.ajax({
  type: 'GET',
  url: page_url
  success: function(responseText){ ...

In Wix corvid, I tried to use a fetch request by it is blocked due to CORS policy at the web server.

Aynone would know how to translate the equivalent of an ajax get request in Wix corvid ?

Thanks,

Hugues

Body:
If you want to use GET do this.

//myfile.jsw

export async function myBackendFnc() {
   const response = await fetch("https://api.website.com", {
      method: 'GET',
   });
   const json = await response.json();
   return json;
}

If the external web server is blocking this request then that is something you need to figure out with the external server on how to whitelist your ip.

You can use the GET from both your page or a server side code using a backend file.


问:
list connected bluetooth devices?
How can I list all connected bluetooth devices on android ?

thanks!

答:
So you get the list of paired devices.</p>

```<code> BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevicesList = btAdapter.getBondedDevices();

    for (BluetoothDevice pairedDevice : pairedDevicesList) {
    Log.d("BT", "pairedDevice.getName(): " + pairedDevice.getName());
    Log.d("BT", "pairedDevice.getAddress(): " + pairedDevice.getAddress());

    saveValuePreference(getApplicationContext(), pairedDevice.getName(), pairedDevice.getAddress());

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: list connected bluetooth devices?

Body:
So you get the list of paired devices.

 BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevicesList = btAdapter.getBondedDevices();

    for (BluetoothDevice pairedDevice : pairedDevicesList) {
    Log.d("BT", "pairedDevice.getName(): " + pairedDevice.getName());
    Log.d("BT", "pairedDevice.getAddress(): " + pairedDevice.getAddress());

    saveValuePreference(getApplicationContext(), pairedDevice.getName(), pairedDevice.getAddress());

}


问:
How can I do natural sort in Snowflake?
I am trying to sort Jira stories with several potential structures: 3 to 5 characters followed by dash followed by 3 or 4 digits e.g. XXX-###, XXX-####, XXXX-### etc.</p>

答:
I'm not quite sure what you mean by a natural sort, but you can sort by a regex. For example, to get just the number of a JiraID string.

```<code>--This Returns '123'
select REGEXP_SUBSTR( 'xx-123' , '\\d+');

--This Returns 'xx'
select REGEXP_SUBSTR( 'xx-123' , '\\w+');

--So this would sort by just the number in a Jira number column based on the number part
... order by REGEXP_SUBSTR( JiraID , '\\d+')::int;

--This would order first by IDs with the same string, and then order by Number
... order by REGEXP_SUBSTR( JiraID , '\\w+'), REGEXP_SUBSTR( JiraID , '\\d+')::int;
</code>```

More complex examples are possible if you provide a sample input with a desired output ordering

Title: How can I do natural sort in Snowflake?

Body:
I'm not quite sure what you mean by a natural sort, but you can sort by a regex. For example, to get just the number of a JiraID string.

--This Returns '123'
select REGEXP_SUBSTR( 'xx-123' , '\\d+');

--This Returns 'xx'
select REGEXP_SUBSTR( 'xx-123' , '\\w+');

--So this would sort by just the number in a Jira number column based on the number part
... order by REGEXP_SUBSTR( JiraID , '\\d+')::int;

--This would order first by IDs with the same string, and then order by Number
... order by REGEXP_SUBSTR( JiraID , '\\w+'), REGEXP_SUBSTR( JiraID , '\\d+')::int;

More complex examples are possible if you provide a sample input with a desired output ordering


问:
Getting "Running the docker.exe login command failed." while trying to publish to Azure container registery
I am trying to publish my .Net core app docker image to Azure Container Registry using Visual Studio 2019.

It was working fine, but suddenly I started to see the following error:

Publish has encountered an error. Running the docker.exe login command
failed.

WARNING! Using --password via the CLI is insecure. Use
--password-stdin.Error response from daemon: Get https://app.azurecr.io:443/v2/: unauthorized: authentication
required

A diagnostic log has been written to the following location:
"C:\Users\user\AppData\Local\Temp\tmp768.tmp"

When running the following CMD command:

```<code>docker login https://app.azurecr.io
</code>```

I am getting:

Authenticating with existing credentials...

Login Succeeded

I restarted Visual Studio and Docker, And I am running Visual Studio as Administrator.

Anyone ran into similar issue?

答:
The solution was to:

1- run the cmd command:

docker login https://app.azurecr.io:443 port included

2- providing username and password again.

3- Publish from Visual Studio.

Note:-  'app' in the above url is the name of the registry

Body:
I am trying to publish my .Net core app docker image to Azure Container Registry using Visual Studio 2019.

It was working fine, but suddenly I started to see the following error:

Publish has encountered an error. Running the docker.exe login command
failed.

WARNING! Using --password via the CLI is insecure. Use
--password-stdin.Error response from daemon: Get https://app.azurecr.io:443/v2/: unauthorized: authentication
required

A diagnostic log has been written to the following location:
"C:\Users\user\AppData\Local\Temp\tmp768.tmp"

When running the following CMD command:

docker login https://app.azurecr.io

I am getting:

Authenticating with existing credentials...

Login Succeeded

I restarted Visual Studio and Docker, And I am running Visual Studio as Administrator.

Anyone ran into similar issue?


问:
Naive Bayes classifier not working for sentiment analysis
I am trying to train a Naive Bayes classifier to predict whether a movie review is good or bad.
I am following this tutorial but have run into an error when trying to train the model:

https://medium.com/@MarynaL/analyzing-movie-review-data-with-natural-language-processing-7c5cba6ed922

I have followed all steps until training the model. My data and code looks as such:

```<code>                                                 Reviews  Labels
0      For fans of Chris Farley, this is probably his...       1
1      Fantastic, Madonna at her finest, the film is ...       1
2      From a perspective that it is possible to make...       1
3      What is often neglected about Harold Lloyd is ...       1
4      You'll either love or hate movies such as this...       1
                                              ...     ...
14995  This is perhaps the worst movie I have ever se...       0
14996  I was so looking forward to seeing this film t...       0
14997  It pains me to see an awesome movie turn into ...       0
14998  "Grande Ecole" is not an artful exploration of...       0
14999  I felt like I was watching an example of how n...       0

gnb = MultinomialNB()
gnb.fit(all_train_set['Reviews'], all_train_set['Labels'])
</code>```

However when trying to fit the model I receive this error:

```<code>ValueError: could not convert string to float: 'For fans of Chris Farley, this is probably his best film. David Spade pl
</code>```

If anyone could help me decide why following this tutorial has gone wrong it would e greatly appreciated.

Many Thanks

答:
Indeed with Scikit-learn you have to convert texts to numbers before calling a classifier. You can do so by using, for instance, the CountVectorizer or the TfidfVectorizer.

If you want to use the more modern word embeddings, you can use the Zeugma package (install it with pip install zeugma in a terminal), e.g.

```<code>from zeugma.embeddings import EmbeddingTransformer

embedding = EmbeddingTransformer('glove')

X = embedding.transform(all_train_set['Reviews'])
y = all_train_set['Labels']

gnb = MultinomialNB()
gnb.fit(X, y)
</code>```

I hope it helps!

Body:
I am trying to train a Naive Bayes classifier to predict whether a movie review is good or bad.
I am following this tutorial but have run into an error when trying to train the model:

https://medium.com/@MarynaL/analyzing-movie-review-data-with-natural-language-processing-7c5cba6ed922

I have followed all steps until training the model. My data and code looks as such:

                                                 Reviews  Labels
0      For fans of Chris Farley, this is probably his...       1
1      Fantastic, Madonna at her finest, the film is ...       1
2      From a perspective that it is possible to make...       1
3      What is often neglected about Harold Lloyd is ...       1
4      You'll either love or hate movies such as this...       1
                                              ...     ...
14995  This is perhaps the worst movie I have ever se...       0
14996  I was so looking forward to seeing this film t...       0
14997  It pains me to see an awesome movie turn into ...       0
14998  "Grande Ecole" is not an artful exploration of...       0
14999  I felt like I was watching an example of how n...       0

gnb = MultinomialNB()
gnb.fit(all_train_set['Reviews'], all_train_set['Labels'])

However when trying to fit the model I receive this error:

ValueError: could not convert string to float: 'For fans of Chris Farley, this is probably his best film. David Spade pl

If anyone could help me decide why following this tutorial has gone wrong it would e greatly appreciated.

Many Thanks

Body:
Indeed with Scikit-learn you have to convert texts to numbers before calling a classifier. You can do so by using, for instance, the CountVectorizer or the TfidfVectorizer.

If you want to use the more modern word embeddings, you can use the Zeugma package (install it with pip install zeugma in a terminal), e.g.

from zeugma.embeddings import EmbeddingTransformer

embedding = EmbeddingTransformer('glove')

X = embedding.transform(all_train_set['Reviews'])
y = all_train_set['Labels']

gnb = MultinomialNB()
gnb.fit(X, y)

I hope it helps!


问:
Importing CSV file into Google Colab using numpy loadtxt
I'm trying to migrate a JupyterLab notebook to Google Colab. In JupyterLab, when I have the notebook file and the associated csv files in the same directory, it is easy to import the data using numpy's loadtxt function as follows:

```<code>import numpy as np
filein = "testfile.csv"
data = np.loadtxt(open(filein, "rb"), delimiter=",", skiprows=1)
</code>```

For various reasons I'd like to continue to use np.loadtxt in Colab. However when I try the same code there, it can't find the csv file despite it residing in the same Google Drive location as the notebook file. I get this error: "FileNotFoundError: [Errno 2] No such file or directory: 'testfile.csv'".

I gather I somehow need to provide a path to the file, but haven't been able to figure out how to do this. Is there any straightforward way to use np.loadtxt?

答:
Shorter and without command

```<code># mount gdrive with this code
from google.colab import drive
drive.mount('/content/drive')
#below where the file is in gdrive, change with your
data_path = "/content/drive/My Drive/Colab Notebooks/test/"
yearsBase, meanBase = np.loadtxt(data_path + 'file.csv', delimiter=',', unpack=True)
</code>```

done, no other code needed
ciao

Body:
I'm trying to migrate a JupyterLab notebook to Google Colab. In JupyterLab, when I have the notebook file and the associated csv files in the same directory, it is easy to import the data using numpy's loadtxt function as follows:

import numpy as np
filein = "testfile.csv"
data = np.loadtxt(open(filein, "rb"), delimiter=",", skiprows=1)

For various reasons I'd like to continue to use np.loadtxt in Colab. However when I try the same code there, it can't find the csv file despite it residing in the same Google Drive location as the notebook file. I get this error: "FileNotFoundError: [Errno 2] No such file or directory: 'testfile.csv'".

I gather I somehow need to provide a path to the file, but haven't been able to figure out how to do this. Is there any straightforward way to use np.loadtxt?

Body:
Shorter and without command

# mount gdrive with this code
from google.colab import drive
drive.mount('/content/drive')
#below where the file is in gdrive, change with your
data_path = "/content/drive/My Drive/Colab Notebooks/test/"
yearsBase, meanBase = np.loadtxt(data_path + 'file.csv', delimiter=',', unpack=True)

done, no other code needed
ciao


问:
How to add the menu items using android navigation component
I'm trying to add a menu to the the toolbar of the application

My app is based on single-activity multi-fragment

and I'm using the navigation component my app style is:

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

and I'm configuring the grapp in the MainActivity's onCreate method like that:

```<code>appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController,appBarConfiguration)
</code>```

My question is how to add different custom menu items for the different fragments?
also, I have added the back button how to handle it's clicks and hide it on the first fragment?

答: You seems to have it setup correctly. Please make sure your fragments have setHasOptionsMenu(true) (can be under onViewCreated) and that you are actually inflating menus under onCreateOptionsMenu of your fragments. Important to note your fragments title will be managed based on nav location (what is specified under android:label)

Body:
I'm trying to add a menu to the the toolbar of the application

My app is based on single-activity multi-fragment

and I'm using the navigation component my app style is:

and I'm configuring the grapp in the MainActivity's onCreate method like that:

appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController,appBarConfiguration)

My question is how to add different custom menu items for the different fragments?
also, I have added the back button how to handle it's clicks and hide it on the first fragment?


问:
How to protect react-native app from reverse engineering?
I have recently created an app with react-native and my concern is about react-native security.  I heard that react-native is not compiled and the code exists as it is in development.

So if we have some sensitive data in variables, what can we do for protecting that?

答:
If you want to protect your react-native app in release, consider the following.

always save your sensitive data in shared preferences on
android and keychain on ios, here is a nice package: https://github.com/oblador/react-native-keychain

use react-native proguard

Encrypt your data and decrypt when you need it.

If possible save your data on server side


问:
What is more efficient? Storing a split string in an array, or calling the split method everytime you need it
What is going to be faster, storing a split string into an array and using this array within my program, or could I call the .split() method on the string whenever I needed an array to iterate through?

```<code>String main = "1,2,3,4,5,6";
String[] array = main.split(",");
</code>```

vs

```<code>main.split(",");
</code>```

whenever I need to use the input values?

I realise it will be way more readable if I were to store the string in an array. I'd just like to know if the .split() takes more computing time than using an array. Since the split method returns an array containing the split strings.

A simple example(?) loop to go with the question:

```<code>for (int i = main.length - 1; i >= 0; i--){}
</code>```

vs

```<code>for (int i = main.split(",") - 1; i >= 0; i--){}
</code>```

答:
It's a trade off, like most such things in programming.  If you split just once and use the array directly from then on, you'll save processing time at the expense of memory.  If you split every time, you'll save memory at the expense of processing time.

One is more time efficient, the other is more space efficient.

Body:
What is going to be faster, storing a split string into an array and using this array within my program, or could I call the .split() method on the string whenever I needed an array to iterate through?

String main = "1,2,3,4,5,6";
String[] array = main.split(",");

vs

main.split(",");

whenever I need to use the input values?

I realise it will be way more readable if I were to store the string in an array. I'd just like to know if the .split() takes more computing time than using an array. Since the split method returns an array containing the split strings.

A simple example(?) loop to go with the question:

for (int i = main.length - 1; i >= 0; i--){}

vs

for (int i = main.split(",") - 1; i >= 0; i--){}