问:
.innerHTML not working or am I using it wrong?
If I understand right, .innerHTML should overwrite whatever was in a certain div or span.
For example:

```<code><table width="90%" border="0" align="center" cellpadding="5" cellspacing="0">

  <tr>
    <td colspan="2" align="left">Via Email:</td>
    <td width="1070" align="right"></td>
  </tr>

  <script>
  $('#addEmail').click(function()       {
document.getElementById('emailList').innerHTML = "12345";
  });
  </script>

      <span  id="emailList">
   <tr>
    <td width="27" align="left"><img src="icon_mail.png" width="24" height="24"></td>
    <td width="228" align="left">123obama@whitehouse.com</td>
    <td align="right"><a href="#" id="dialog_link" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-close"></span>remove</a></td>
  </tr>
     </span>

  <tr>
    <td colspan="3" align="left"><br>
      <input name="input4" type="text" value="vova@kremlin.ru" size="20">
      <a href="#" id="addEmail" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-mail-closed"></span>Add Email</a></td>
    </tr>
</table>
</code>```

Therefor upon click of #addEmail button, everything inside  would be removed and replaced by "12345".

Yet in reality it doesn't do anything to that span, but just prints out 12345 in the place, where the script is.

Any ideas what could be wrong?

答:
It's actually your span that's wrong. A span can't ... span (I know, I know) over table rows, so it gets opened and closed somewhere between the rows (or outside the table on some browsers), so when you're overwriting it's html, it ends up somewhere else.

You should name the tr instead and overwrite its html, that should work.

Body:
If I understand right, .innerHTML should overwrite whatever was in a certain div or span.
For example:

    Via Email:

    123obama@whitehouse.com
    remove

      <input name="input4" type="text" value="vova@kremlin.ru" size="20">
      Add Email

Therefor upon click of #addEmail button, everything inside  would be removed and replaced by "12345".

Yet in reality it doesn't do anything to that span, but just prints out 12345 in the place, where the script is.

Any ideas what could be wrong?


来源: stackexchange

问:
Two NSArrays combine to a NSDictionary with alternating values
Hi I am very new to Objective-c please excuse my ignorance. So basically this is what I want to happened. I have two arrays of numbers

```<code>Array1: (1,3,5);
Array2: (2,4,6);
</code>```

and I want them to be like this after combining them in a dictionary

```<code>"dictionary":{"1":2,: "3":4, "5":6}
</code>```

Any feedback will be appreciated!

答:
You can try it use this code: </p>

```<code>- (NSDictionary *)convertToDicFromKeys:(NSArray *)keys andValues:(NSArray *)values
{

    NSInteger count = MIN(keys.count, values.count);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:count];
    for (int i = 0; i < count; i++) {
        dic[keys[i]] = values[i];
    }
    return dic;
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi I am very new to Objective-c please excuse my ignorance. So basically this is what I want to happened. I have two arrays of numbers

Array1: (1,3,5);
Array2: (2,4,6);

and I want them to be like this after combining them in a dictionary

"dictionary":{"1":2,: "3":4, "5":6}

Any feedback will be appreciated!

Body:
You can try it use this code:

- (NSDictionary *)convertToDicFromKeys:(NSArray *)keys andValues:(NSArray *)values
{

    NSInteger count = MIN(keys.count, values.count);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:count];
    for (int i = 0; i < count; i++) {
        dic[keys[i]] = values[i];
    }
    return dic;
}


问:
Creating a df starting from a timestamp value and ending on a timestamp value increment by one hour in Spark scala
Can anyone help me to create a data frame were starting and ending timestamp value is given and we need to print all the hour increment by one?

Example
Starting timestamp: 02-05-2020 01:00

Ending timestamp: 03-05-2020 02:00

So the df should have all those values:

```<code>
02-05-2020 01:00
02-05-2020 02:00
02-05-2020 03:00
02-05-2020 04:00
02-05-2020 05:00
.
.
.
03-05-2020 02:00

</code>```

Body:
Can anyone help me to create a data frame were starting and ending timestamp value is given and we need to print all the hour increment by one?

Example
Starting timestamp: 02-05-2020 01:00

Ending timestamp: 03-05-2020 02:00

So the df should have all those values:

02-05-2020 01:00
02-05-2020 02:00
02-05-2020 03:00
02-05-2020 04:00
02-05-2020 05:00
.
.
.
03-05-2020 02:00

Body:
Another approach which is not covered in other answers currently-

val startTimeStamp = "02-05-2020 01:00"
    val endTimeStamp = "03-05-2020 02:00"
    spark.range(1).selectExpr(
      s"""
        |explode(sequence(
        |      to_timestamp('$startTimeStamp', 'dd-MM-yyyy HH:mm'),
        |      to_timestamp('$endTimeStamp', 'dd-MM-yyyy HH:mm'),
        |      interval 1 hour
        |    )) as generated_timestamp
      """.stripMargin
    ).show(false)

    /**
      * +-------------------+
      * |generated_timestamp|
      * +-------------------+
      * |2020-05-02 01:00:00|
      * |2020-05-02 02:00:00|
      * |2020-05-02 03:00:00|
      * |2020-05-02 04:00:00|
      * |2020-05-02 05:00:00|
      * |2020-05-02 06:00:00|
      * |2020-05-02 07:00:00|
      * |2020-05-02 08:00:00|
      * |2020-05-02 09:00:00|
      * |2020-05-02 10:00:00|
      * |2020-05-02 11:00:00|
      * |2020-05-02 12:00:00|
      * |2020-05-02 13:00:00|
      * |2020-05-02 14:00:00|
      * |2020-05-02 15:00:00|
      * |2020-05-02 16:00:00|
      * |2020-05-02 17:00:00|
      * |2020-05-02 18:00:00|
      * |2020-05-02 19:00:00|
      * |2020-05-02 20:00:00|
      * +-------------------+
      * only showing top 20 rows
      */


问:
how to open a new window from menu widget in tkinter
i'm trying to develop a simple Gui that display different pages when the button in the menu is clicked and i have been able to make other buttons work but the menu is giving me errors.
just like other apps that from the menu person can navicate the app.
when i run the code and click on newtest in file menu, i get this error

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "/home/pi/Documents/py script/helium1/test.py", line 34, in <lambda>
    command=lambda: controller.show_frame(PageOne))
AttributeError: 'Frame' object has no attribute 'show_frame'
</code>```

here is the code

```<code>import tkinter as tk
from tkinter import *
import datetime
import time
import paho.mqtt.client as mqtt

LARGE_FONT= ("Verdana", 12)

def messageFunction (client, userdata, message):
    topic = str(message.topic)
    message = str(message.payload.decode("utf-8"))
    print(topic + " " + message)

HeliumClient = mqtt.Client("xokaxvwt")
HeliumClient.username_pw_set(username = "xokaxvwt", password="MGlEiIwOHM9-")
HeliumClient.connect("m16.cloudmqtt.com", 15998)
HeliumClient.subscribe("Switch_1")
HeliumClient.subscribe("Switch_2")
HeliumClient.on_message = messageFunction
HeliumClient.loop_start()

class MenuBar(tk.Menu):
    def __init__(self, parent, controller):
        tk.Menu.__init__(self, controller)
        self.controller = controller

        fileMenu = tk.Menu(self, tearoff=0)
        self.add_cascade(label="File", underline=0, menu=fileMenu)
        fileMenu.add_command(label="New Test",
                         command=lambda: controller.show_frame(PageOne))
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit")

class Helium(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        self.controller = controller

        self.menubar = MenuBar(self, parent)
        self.controller.config(menu=self.menubar)

        label = tk.Label(self, text="Start Page", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button = tk.Button(self, text="Visit Page 1", command=lambda: controller.show_frame(PageOne))
        button.pack()

        button2 = tk.Button(self, text="Visit Page 2", command=lambda: controller.show_frame(PageTwo))
        button2.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = tk.Button(self, text="Page Two", command=lambda: controller.show_frame(PageTwo))
        button2.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, con):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = tk.Button(self, text="Page One", command=lambda: controller.show_frame(PageOne))
        button2.pack()

app = Helium()

#creating Date/time
def display_time():
    Date = datetime.datetime.now()
    Date_Label['text'] = Date
    app.after(1000, display_time)

Date_Frame = LabelFrame(app, text= "Date/time")
Date_Frame.place(x=790, y=5, height=35, width=200)
Date_Label = Label(Date_Frame)
Date_Label.grid(column=0, row=0)

app.geometry('1000x450')
app.title("Helium")
app.resizable(False, False)
display_time()
app.mainloop()
</code>```

答:
You are passing parent argument to MenuBar but it's expecting a controller. You also need to pass the parent to the superclass, not controller. You need to create MenuBar like this:

```<code>class MenuBar(tk.Menu):
    def __init__(self, parent, controller):
        tk.Menu.__init__(self, parent)
    ...

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        ...
        self.menubar = MenuBar(self)
        ...
</code>```

Body:
i'm trying to develop a simple Gui that display different pages when the button in the menu is clicked and i have been able to make other buttons work but the menu is giving me errors.
just like other apps that from the menu person can navicate the app.
when i run the code and click on newtest in file menu, i get this error

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "/home/pi/Documents/py script/helium1/test.py", line 34, in <lambda>
    command=lambda: controller.show_frame(PageOne))
AttributeError: 'Frame' object has no attribute 'show_frame'

here is the code

import tkinter as tk
from tkinter import *
import datetime
import time
import paho.mqtt.client as mqtt

LARGE_FONT= ("Verdana", 12)

def messageFunction (client, userdata, message):
    topic = str(message.topic)
    message = str(message.payload.decode("utf-8"))
    print(topic + " " + message)

HeliumClient = mqtt.Client("xokaxvwt")
HeliumClient.username_pw_set(username = "xokaxvwt", password="MGlEiIwOHM9-")
HeliumClient.connect("m16.cloudmqtt.com", 15998)
HeliumClient.subscribe("Switch_1")
HeliumClient.subscribe("Switch_2")
HeliumClient.on_message = messageFunction
HeliumClient.loop_start()

class MenuBar(tk.Menu):
    def __init__(self, parent, controller):
        tk.Menu.__init__(self, controller)
        self.controller = controller

        fileMenu = tk.Menu(self, tearoff=0)
        self.add_cascade(label="File", underline=0, menu=fileMenu)
        fileMenu.add_command(label="New Test",
                         command=lambda: controller.show_frame(PageOne))
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit")

class Helium(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        self.controller = controller

        self.menubar = MenuBar(self, parent)
        self.controller.config(menu=self.menubar)

        label = tk.Label(self, text="Start Page", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button = tk.Button(self, text="Visit Page 1", command=lambda: controller.show_frame(PageOne))
        button.pack()

        button2 = tk.Button(self, text="Visit Page 2", command=lambda: controller.show_frame(PageTwo))
        button2.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = tk.Button(self, text="Page Two", command=lambda: controller.show_frame(PageTwo))
        button2.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, con):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = tk.Button(self, text="Page One", command=lambda: controller.show_frame(PageOne))
        button2.pack()

app = Helium()

#creating Date/time
def display_time():
    Date = datetime.datetime.now()
    Date_Label['text'] = Date
    app.after(1000, display_time)

Date_Frame = LabelFrame(app, text= "Date/time")
Date_Frame.place(x=790, y=5, height=35, width=200)
Date_Label = Label(Date_Frame)
Date_Label.grid(column=0, row=0)

app.geometry('1000x450')
app.title("Helium")
app.resizable(False, False)
display_time()
app.mainloop()

Body:
You are passing parent argument to MenuBar but it's expecting a controller. You also need to pass the parent to the superclass, not controller. You need to create MenuBar like this:

class MenuBar(tk.Menu):
    def __init__(self, parent, controller):
        tk.Menu.__init__(self, parent)
    ...

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        ...
        self.menubar = MenuBar(self)
        ...


问:
How to sent all members each server a message in 'ready'
When my bot starts up, I want it to send a message to all the members in each server, for example

I want it to say Hello.

client.on('ready', message  => {
  client.user.setActivity(`${client.guilds.cache.size} servers have members ${client.users.cache.size}`+` | !help `, { type: 'WATCHING' })

  client.guild.send("Hello")
});
```

答:
I think this code might be what you need :

```<code>client.users.cache.forEach(user => {
    try {
        user.send('Hello');
    } catch (e) {
        console.log(`Could not send the message to ${user.tag} : ${e}`);
    };
});
</code>```

This simply grabs all users the bot can communicate with, tries to send a message, and logs an error if the message could not be sent (The error will most likely be caused by the user locking their DMs / blocking the bot).

Body:
I think this code might be what you need :

client.users.cache.forEach(user => {
    try {
        user.send('Hello');
    } catch (e) {
        console.log(`Could not send the message to ${user.tag} : ${e}`);
    };
});

This simply grabs all users the bot can communicate with, tries to send a message, and logs an error if the message could not be sent (The error will most likely be caused by the user locking their DMs / blocking the bot).


问:
textbox textchanged event always firing
I have a form with a few text-boxes and a Grid-view. There is this one text-box called "Inward Number", whose text-changed event fires all the time. When i want to fire another control's event, it simply fires the text-changed event of the Inward Number text-box. This happens with all of the other controls. Can someone please help?

```<code>protected void txtInward_No_TextChanged(object sender, EventArgs e)
{
   a = 'A';
   NewRow();
}
</code>```

I have used the correct names, but still this error occurs.

```<code><asp:TextBox ID="txtInward_No" runat="server" Width="220px" CssClass="txtbox"
                    EnableViewState="False"
                    AutoPostBack="True" ontextchanged="txtInward_No_TextChanged">
</asp:TextBox>
</code>```

new row just makes a new row in my grid.

private void NewRow()
       {
        int rowIndex = 0;

```<code>        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtnew = new DataTable();
            dtnew = (DataTable)ViewState["CurrentTable"];
            DataRow drr = null;
            if (dtnew.Rows.Count > 0)
            {
                for (int i = 1; i <= dtnew.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox1");
                    TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox2");
                    TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("TextBox3");
                    TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("TextBox4");
                    TextBox box5 = (TextBox)GridView1.Rows[rowIndex].Cells[6].FindControl("TextBox5");

                    drr = dtnew.NewRow();
                    if (txtInward_No.Text =="1")
                    {
                        drr["InwardNumber"] = txtInward_No.Text + b.ToString();
                    }
                    else
                    {
                        drr["InwardNumber"] = txtInward_No.Text + a.ToString();
                    }
                    drr["Bags"] = box1.Text;
                    drr["GrossWt"] = box2.Text;
                    drr["TareWt"] = box3.Text;
                    drr["NetWt"] = box4.Text;
                    drr["DCBillWt"] = box5.Text;

                    rowIndex++;
                }
                dtnew.Rows.Add(drr);
                ViewState["CurrentTable"] = dtnew;
                GridView1.DataSource = dtnew;
                GridView1.DataBind();
            }
        }
        PrevData();
        b++;
        a++;
   }
</code>```

答:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.ontextchanged.aspx

A TextBox control must persist some values between posts to the server for this event to work correctly. Be sure that view state is enabled for this control.

Try enabling ViewState for TextBox.

ContentLicense: CC BY-SA 3.0

Title: textbox textchanged event always firing

Body:
I have a form with a few text-boxes and a Grid-view. There is this one text-box called "Inward Number", whose text-changed event fires all the time. When i want to fire another control's event, it simply fires the text-changed event of the Inward Number text-box. This happens with all of the other controls. Can someone please help?

protected void txtInward_No_TextChanged(object sender, EventArgs e)
{
   a = 'A';
   NewRow();
}

I have used the correct names, but still this error occurs.

<asp:TextBox ID="txtInward_No" runat="server" Width="220px" CssClass="txtbox"
                    EnableViewState="False"
                    AutoPostBack="True" ontextchanged="txtInward_No_TextChanged">
</asp:TextBox>

new row just makes a new row in my grid.

private void NewRow()
       {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtnew = new DataTable();
            dtnew = (DataTable)ViewState["CurrentTable"];
            DataRow drr = null;
            if (dtnew.Rows.Count > 0)
            {
                for (int i = 1; i <= dtnew.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox1");
                    TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox2");
                    TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("TextBox3");
                    TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("TextBox4");
                    TextBox box5 = (TextBox)GridView1.Rows[rowIndex].Cells[6].FindControl("TextBox5");

                    drr = dtnew.NewRow();
                    if (txtInward_No.Text =="1")
                    {
                        drr["InwardNumber"] = txtInward_No.Text + b.ToString();
                    }
                    else
                    {
                        drr["InwardNumber"] = txtInward_No.Text + a.ToString();
                    }
                    drr["Bags"] = box1.Text;
                    drr["GrossWt"] = box2.Text;
                    drr["TareWt"] = box3.Text;
                    drr["NetWt"] = box4.Text;
                    drr["DCBillWt"] = box5.Text;

                    rowIndex++;
                }
                dtnew.Rows.Add(drr);
                ViewState["CurrentTable"] = dtnew;
                GridView1.DataSource = dtnew;
                GridView1.DataBind();
            }
        }
        PrevData();
        b++;
        a++;
   }


问:
Android Studio CMake Error: Build Command failed
I'm running into an Error when I open a new project in Android Studio from the Code Samples (Hello JIN). When the Project is opened the following:

```<code>Build command failed.
Error while executing process /opt/android-sdk/cmake/3.6.4111459/bin/cmake with arguments {-H/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/src/main/cpp -B/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a -GAndroid Gradle - Ninja -DANDROID_ABI=arm64-v8a -DANDROID_NDK=/opt/android-sdk/ndk-bundle -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/build/intermediates/cmake/arm8/release/obj/arm64-v8a -DCMAKE_BUILD_TYPE=Release -DCMAKE_MAKE_PROGRAM=/opt/android-sdk/cmake/3.6.4111459/bin/ninja -DCMAKE_TOOLCHAIN_FILE=/opt/android-sdk/ndk-bundle/build/cmake/android.toolchain.cmake -DANDROID_PLATFORM=android-23 -DANDROID_TOOLCHAIN=clang}
-- Check for working C compiler: /opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang
-- Check for working C compiler: /opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang -- broken
-- Configuring incomplete, errors occurred!
See also "/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a/CMakeFiles/CMakeOutput.log".
See also "/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a/CMakeFiles/CMakeError.log".
CMake Error at /opt/android-sdk/cmake/3.6.4111459/share/cmake-3.6/Modules/CMakeTestCCompiler.cmake:61 (message):
  The C compiler
  "/opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang"
  is not able to compile a simple test program.
  It fails with the following output:
   Change Dir: /home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a/CMakeFiles/CMakeTmp
  Run Build Command:"/opt/android-sdk/cmake/3.6.4111459/bin/ninja"
  "cmTC_0053d"
  [1/2] Building C object CMakeFiles/cmTC_0053d.dir/testCCompiler.c.o
  FAILED:
  /opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang
  --target=aarch64-none-linux-android
  --gcc-toolchain=/opt/android-sdk/ndk-bundle/toolchains/aarch64-linux-android-4.9/prebuilt/linux-x86_64
  --sysroot=/opt/android-sdk/ndk-bundle/sysroot -isystem
  /opt/android-sdk/ndk-bundle/sysroot/usr/include/aarch64-linux-android
  -D__ANDROID_API__=23 -g -DANDROID -ffunction-sections -funwind-tables
  -fstack-protector-strong -no-canonical-prefixes -Wa,--noexecstack -Wformat
  -Werror=format-security -fPIE -o
  CMakeFiles/cmTC_0053d.dir/testCCompiler.c.o -c
  /home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a/CMakeFiles/CMakeTmp/testCCompiler.c
  /opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang:
  error while loading shared libraries: libncurses.so.5: cannot open shared
  object file: No such file or directory
  ninja: build stopped: subcommand failed.
  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt
</code>```

This Error drops mutliple times in the IDE

I'm using Arch-Linux 64x

Cmake.txt:

```<code>    cmake_minimum_required(VERSION 3.4.1)

add_library(hello-jni SHARED
            hello-jni.c)

# Include libraries needed for hello-jni lib
target_link_libraries(hello-jni
                      android
                      log)
</code>```

答:
I find this way can work:

not need delete below:

```<code>    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
</code>```

this is useful .and  your project just  less the  ninja file .

you can fllow this way  can build successful!

here is the result:

```<code>Make was unable to find a build program corresponding to "Ninja". CMAKE_MAKE_PROGRAM is not set. You probably need to select a different build tool.
</code>```

you should install  ninja

download ninja here ninja  download file

get the ninja file

copy the ninja file  to the /usrlocal/bin

build again .the project run successfull!!

Body:
I'm running into an Error when I open a new project in Android Studio from the Code Samples (Hello JIN). When the Project is opened the following:

Build command failed.
Error while executing process /opt/android-sdk/cmake/3.6.4111459/bin/cmake with arguments {-H/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/src/main/cpp -B/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a -GAndroid Gradle - Ninja -DANDROID_ABI=arm64-v8a -DANDROID_NDK=/opt/android-sdk/ndk-bundle -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/build/intermediates/cmake/arm8/release/obj/arm64-v8a -DCMAKE_BUILD_TYPE=Release -DCMAKE_MAKE_PROGRAM=/opt/android-sdk/cmake/3.6.4111459/bin/ninja -DCMAKE_TOOLCHAIN_FILE=/opt/android-sdk/ndk-bundle/build/cmake/android.toolchain.cmake -DANDROID_PLATFORM=android-23 -DANDROID_TOOLCHAIN=clang}
-- Check for working C compiler: /opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang
-- Check for working C compiler: /opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang -- broken
-- Configuring incomplete, errors occurred!
See also "/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a/CMakeFiles/CMakeOutput.log".
See also "/home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a/CMakeFiles/CMakeError.log".
CMake Error at /opt/android-sdk/cmake/3.6.4111459/share/cmake-3.6/Modules/CMakeTestCCompiler.cmake:61 (message):
  The C compiler
  "/opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang"
  is not able to compile a simple test program.
  It fails with the following output:
   Change Dir: /home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a/CMakeFiles/CMakeTmp
  Run Build Command:"/opt/android-sdk/cmake/3.6.4111459/bin/ninja"
  "cmTC_0053d"
  [1/2] Building C object CMakeFiles/cmTC_0053d.dir/testCCompiler.c.o
  FAILED:
  /opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang
  --target=aarch64-none-linux-android
  --gcc-toolchain=/opt/android-sdk/ndk-bundle/toolchains/aarch64-linux-android-4.9/prebuilt/linux-x86_64
  --sysroot=/opt/android-sdk/ndk-bundle/sysroot -isystem
  /opt/android-sdk/ndk-bundle/sysroot/usr/include/aarch64-linux-android
  -D__ANDROID_API__=23 -g -DANDROID -ffunction-sections -funwind-tables
  -fstack-protector-strong -no-canonical-prefixes -Wa,--noexecstack -Wformat
  -Werror=format-security -fPIE -o
  CMakeFiles/cmTC_0053d.dir/testCCompiler.c.o -c
  /home/max/Documents/AndroidStudioProjects/HelloJNI1/app/.externalNativeBuild/cmake/arm8Release/arm64-v8a/CMakeFiles/CMakeTmp/testCCompiler.c
  /opt/android-sdk/ndk-bundle/toolchains/llvm/prebuilt/linux-x86_64/bin/clang:
  error while loading shared libraries: libncurses.so.5: cannot open shared
  object file: No such file or directory
  ninja: build stopped: subcommand failed.
  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt

This Error drops mutliple times in the IDE

I'm using Arch-Linux 64x

Cmake.txt:

    cmake_minimum_required(VERSION 3.4.1)

add_library(hello-jni SHARED
            hello-jni.c)

# Include libraries needed for hello-jni lib
target_link_libraries(hello-jni
                      android
                      log)

Body:
I find this way can work:

not need delete below:

    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }

this is useful .and  your project just  less the  ninja file .

you can fllow this way  can build successful!

here is the result:

Make was unable to find a build program corresponding to "Ninja". CMAKE_MAKE_PROGRAM is not set. You probably need to select a different build tool.

you should install  ninja

download ninja here ninja  download file

get the ninja file

copy the ninja file  to the /usrlocal/bin

build again .the project run successfull!!


问:
Trying to run a Python script with cron, getting [Errno 1] Operation not permitted
So I have a Python script which just pulls information from APIs and sends an email. When I run it manually, it works. I have a cron job set up:

```<code>30 7 * * * /Users/myname/anaconda3/bin/python3 /Users/myname/Desktop/repo/somefolder/script.py >> /Users/myname/Desktop/filename.log 2>&1
</code>```

but the output in filename.log is:
/Users/myname/anaconda3/bin/python3: can't open file '/Users/myname/Desktop/repo/somefolder/script.py': [Errno 1] Operation not permitted

I've tried lots of different things involving trying out different file permissions, creating the cron job as root, adding a shebang, and different Python paths, but cannot get any output other than this error. Nothing I've found online has given a different result so far.

I'm using macOS Catalina 10.15.1.
The file permissions currently for my script:

```<code>-rwxr--r--  1 myname  staff  4161 13 Nov 18:07 /Users/myname/Desktop/repo/somefolder/script.py
</code>```

Any help would be appreciated!

答:
I had a very similar issue with attempting to run a node.js script using crontab in MacOS. In order for me to finally get it to work, I had to add cron and zsh to the Full Disk Access in my Security and Privacy settings in System Preferences.

How to add cron:
1. Apple Menu -> System Preferences -> Security & Privacy -> Full Disk Access
2. Click the Lock to Allow Changes
3. Click the + Sign
4. hit Command + Shift + G and in type '/usr/sbin/'
5. scroll to find "cron" in the list of binaries
6. Click "Open"

How to add zsh:
1. repeat steps 1 - 3
2. hit Command + Shift + G and in type '/bin'
3. scroll to find "zsh" in the list of binaries
4. Click "Open"

After I did that my cron jobs ran without issue. Hope that helps

Body:
So I have a Python script which just pulls information from APIs and sends an email. When I run it manually, it works. I have a cron job set up:

30 7 * * * /Users/myname/anaconda3/bin/python3 /Users/myname/Desktop/repo/somefolder/script.py >> /Users/myname/Desktop/filename.log 2>&1

but the output in filename.log is:
/Users/myname/anaconda3/bin/python3: can't open file '/Users/myname/Desktop/repo/somefolder/script.py': [Errno 1] Operation not permitted

I've tried lots of different things involving trying out different file permissions, creating the cron job as root, adding a shebang, and different Python paths, but cannot get any output other than this error. Nothing I've found online has given a different result so far.

I'm using macOS Catalina 10.15.1.
The file permissions currently for my script:

-rwxr--r--  1 myname  staff  4161 13 Nov 18:07 /Users/myname/Desktop/repo/somefolder/script.py

Any help would be appreciated!


问:
How to convert array byte to string in java
Before that sorry for my bad english because it's not my first language.
Excuse me, i'm trying to convert array byte to string in error handling try catch java. And if user input integers, the result will be +2.  I've tried but always error, i hope someone can help me.

Here's my code:

```<code> package exception;

    public class TugasTiga {
        public static void main (String [] args) {
            byte[] b = new byte[5];
            System.out.println("Input bilangan bulat: ");
            try { System.in.read(b);
            } catch (java.io.IOException e);
            int N = Integer.valueOf(b).intValue();
            System.out.println("Hasil: " + (N+2));
        }
    }
</code>```

答:
To convert a byte[] to String use s=new String(bytes,"UTF-8") or whatever encoding has been used.

However I assume that you misunderstood how the console works because you asked for a conversion to string but you need integer. We normally use the Scanner class to read interactive input and convert it.

Take a look at this tutorial, which explains how to use the scanner class: https://www.w3schools.com/java/java_user_input.asp

Body:
Before that sorry for my bad english because it's not my first language.
Excuse me, i'm trying to convert array byte to string in error handling try catch java. And if user input integers, the result will be +2.  I've tried but always error, i hope someone can help me.

Here's my code:

 package exception;

    public class TugasTiga {
        public static void main (String [] args) {
            byte[] b = new byte[5];
            System.out.println("Input bilangan bulat: ");
            try { System.in.read(b);
            } catch (java.io.IOException e);
            int N = Integer.valueOf(b).intValue();
            System.out.println("Hasil: " + (N+2));
        }
    }


问:
How do Typescript interface scope is working ? How to make interfaces global?
I'm a new user of Typescript and Deno and I don't really understand how the interfaces scope are working.

I have a tree layer application :

The first layer (App.ts) is my application, this is where the core logic part of my application is. This part can be any file that need to refer to the second layer (API.ts).

The second layer (API.ts) is the entry point where I can communicate with any distant API (like Facebook, stripe, Google API)

The third layer is a bunch of .ts file. The second layer (API.ts) can communicate with each of them. Every file handles a very precise part of a particular API. I have for example one FB_page.ts to handle the part of the Facebook API responsible for pages, another file STRP_Subscription that handle the part of the Stripe API responsible for subscriptions, etc.

My problem is

I have a lot of interfaces to handle every type of parameter, every error and every response an API call can input or output. And I need these interfaces in every layer of my application.

It would be very cool if I can put interfaces of a particular API part inside the file that is responsible for it. For example, if I need several interfaces for the Facebook page API, I would like to put then inside the FB_page.ts file.

But it's tedious to have to import the FB_page.ts file if I need them in the first layer of my application App.ts like this :
import {IPost, IPost_Error, IPost_Response} from '../lib/FB_page.ts';

So I put them inside .d.ts files, but they seem not to be global either ?

How can I have access to my interfaces without having to import them everywhere in my application ?

Thank you for your help.

答:
Try exporting namespaces</p>

```<code>export as namespace ICalendar;
import { Document } from "mongoose";

export interface Calendar extends Document {
userId?: Object
}
</code>```

Body:
Try exporting namespaces

export as namespace ICalendar;
import { Document } from "mongoose";

export interface Calendar extends Document {
userId?: Object
}


答:
Just like that:</p>

```<code>byte[] bytes = new byte[5];
String stringFromByteArray = new String(bytes);
</code>```

Title: How to convert array byte to string in java

Body:
Just like that:

byte[] bytes = new byte[5];
String stringFromByteArray = new String(bytes);


问:
How can I access the text property to split it at every colon?
I wonder why this code snippet in javascript does not work. How can I access the text property?

```<code>lst = [{"antwort1" : {"text": [{"text": "hallo1, hallo2"}]}}, "antwort2"];

text = lst[0].antwort1.text.text.split(",")
</code>```

Thank you very much for helping

答:
It is a simple error of forgetting to index an array. Your approach does not throw an error due to the text method of strings.</p>

```<code>lst[0].antwort1.text[0].text.split(",")
</code>```

Body:
I wonder why this code snippet in javascript does not work. How can I access the text property?

lst = [{"antwort1" : {"text": [{"text": "hallo1, hallo2"}]}}, "antwort2"];

text = lst[0].antwort1.text.text.split(",")

Thank you very much for helping

Body:
It is a simple error of forgetting to index an array. Your approach does not throw an error due to the text method of strings.

lst[0].antwort1.text[0].text.split(",")


问:
Vue - Switching between components
Imagine I have a order form with 3 stages - Personal details, Order details, payment.

I want to toggle the next component from within the previous one (hoping to adjust the value of 'step')

```<code><Component1 v-if="step = 1"></Component1>
<Component2 v-else-if="step = 2"></Component2>
<Component3 v-else></Component3>
</code>```

So, with those on my view, is it possible for me to pass the value of 'step' in to component1 and do something like

```<code><button v-on:click="step = 2">
   Submit
</button>
</code>```

then on that click, update the value of step on my main view (with the 3 components) and with that, hide my first completed component and displaying the second?

Thanks for any insight!

答:
Why you dont use dynamic components?

On your parent component you listen to the event that changes yours step, i named it here nextStep. This event triggers the method changeStep that changes the component name.

```<code><component @nextStep="changeStep" :name="selectedComponent"></component>

import component1 from "../components/component1.vue";
import component2 from "../components/component2.vue";
import component3 from "../components/component3.vue";
export default {
   data(){
      return {
         selectedComponent: "component1"
      }
   }
},
methods: {
   changeStep(step){
      this.selectedComponent = step;
   }
},
components: {
   component1,
   component2,
   component3
}
</code>```

//in the child component

```<code>method: {
   changeStep(){
      this.$emit("nextStep", "component2");
   }
}
</code>```

This is how you emit the event to the parent to change the component

You just need to change the property selectedComponent to the component name you want and it will change it

Title: Vue - Switching between components

Body:
Imagine I have a order form with 3 stages - Personal details, Order details, payment.

I want to toggle the next component from within the previous one (hoping to adjust the value of 'step')

<Component1 v-if="step = 1"></Component1>
<Component2 v-else-if="step = 2"></Component2>
<Component3 v-else></Component3>

So, with those on my view, is it possible for me to pass the value of 'step' in to component1 and do something like

<button v-on:click="step = 2">
   Submit
</button>

then on that click, update the value of step on my main view (with the 3 components) and with that, hide my first completed component and displaying the second?

Thanks for any insight!

Body:
Why you dont use dynamic components?

On your parent component you listen to the event that changes yours step, i named it here nextStep. This event triggers the method changeStep that changes the component name.

<component @nextStep="changeStep" :name="selectedComponent"></component>

import component1 from "../components/component1.vue";
import component2 from "../components/component2.vue";
import component3 from "../components/component3.vue";
export default {
   data(){
      return {
         selectedComponent: "component1"
      }
   }
},
methods: {
   changeStep(step){
      this.selectedComponent = step;
   }
},
components: {
   component1,
   component2,
   component3
}

//in the child component

method: {
   changeStep(){
      this.$emit("nextStep", "component2");
   }
}

This is how you emit the event to the parent to change the component

You just need to change the property selectedComponent to the component name you want and it will change it


答:
You can't put a
 inside a  like that.  Anyway if you're using jQuery, you should probably use its API around ".innerHTML"

```<code>$('#emailList').html("hello world");
</code>```

That will do some important cleanup work for you. It's not absolutely required, but unless you know for sure what you're doing it's probably a safer option.

Title: .innerHTML not working or am I using it wrong?

Body:
If I understand right, .innerHTML should overwrite whatever was in a certain div or span.
For example:

    Via Email:

    123obama@whitehouse.com
    remove

      <input name="input4" type="text" value="vova@kremlin.ru" size="20">
      Add Email

Therefor upon click of #addEmail button, everything inside  would be removed and replaced by "12345".

Yet in reality it doesn't do anything to that span, but just prints out 12345 in the place, where the script is.

Any ideas what could be wrong?

Body:
You can't put a <tr> inside a <span> like that.  Anyway if you're using jQuery, you should probably use its API around ".innerHTML"

$('#emailList').html("hello world");

That will do some important cleanup work for you. It's not absolutely required, but unless you know for sure what you're doing it's probably a safer option.


问:
KafkaConsumer 0.10 Java API error message: No current assignment for partition
I am using KafkaConsumer 0.10 Java api. I want to consume from a specific partition and specific offset. I looked up and found that there is a seek method but its throwing an exception. Anyone had a similar use case or solution ?

Code:

```<code>KafkaConsumer<String, byte[]> consumer = new KafkaConsumer<>(consumerProps);
consumer.seek(new TopicPartition("mytopic", 1), 4);
</code>```

Exception

```<code>java.lang.IllegalStateException: No current assignment for partition mytopic-1
    at org.apache.kafka.clients.consumer.internals.SubscriptionState.assignedState(SubscriptionState.java:251)
    at org.apache.kafka.clients.consumer.internals.SubscriptionState.seek(SubscriptionState.java:276)
    at org.apache.kafka.clients.consumer.KafkaConsumer.seek(KafkaConsumer.java:1135)
    at xx.xxx.xxx.Test.main(Test.java:182)
</code>```

答:
Please use consumer.assign with consumer.seek and not consumer.subscribe

After these changes, it will execute fine.

Body:
I am using KafkaConsumer 0.10 Java api. I want to consume from a specific partition and specific offset. I looked up and found that there is a seek method but its throwing an exception. Anyone had a similar use case or solution ?

Code:

KafkaConsumer<String, byte[]> consumer = new KafkaConsumer<>(consumerProps);
consumer.seek(new TopicPartition("mytopic", 1), 4);

Exception

java.lang.IllegalStateException: No current assignment for partition mytopic-1
    at org.apache.kafka.clients.consumer.internals.SubscriptionState.assignedState(SubscriptionState.java:251)
    at org.apache.kafka.clients.consumer.internals.SubscriptionState.seek(SubscriptionState.java:276)
    at org.apache.kafka.clients.consumer.KafkaConsumer.seek(KafkaConsumer.java:1135)
    at xx.xxx.xxx.Test.main(Test.java:182)


问:
How to pause and then resume a Kubernetes service in Google cloud?
I have a service named Foo that is currently running. It directs traffic it receives to a running Pod as well. Since the service is of type LoadBalancer and runs in Google Cloud - it has it's own external IP.

I'm currently doing maintenance and testing on various services and would like to temporarily STOP service Foo from working, then RESUMING it again. That is, anyone that hits the IP for service Foo would get a 404, but then later on I resume it - they would start getting answers back.

The reason why I don't just flat out delete the service then create a new one is because I wish to maintain the original IP address for the Foo service. I have tests that directly reference that IP and do not wish to have to continuously change them. i also have a few clients in production relying on that IP so I can't risk losing it.

Any indication then on how to temporarily STOP / RESUME a kubernetes service in Google cloud, while preserving it's IP?

Thanks

答:
Kubernetes itself does not have mechanism to stop a service.

When you create a Service type of LoadBalancer in GKE, it automatically creates a forwarding rule for external access. You can disable that rule (not delete!) to stop external traffic accessing your Service.

To disable the forwarding rule:

Check the associated IP address with a LoadBalancer by either:

issuing: $ kubectl get svc

going to: GCP Dashboard -> Kubernetes Engine -> Services & Ingress

Go to GCP Dashboard -> VPC Network -> External IP addresses

Find your LB's IP and copy name of the forwarding rule associated with it

Go to GCP Dashboard -> VPC Network -> Firewall

Search for mentioned forwarding rule

Edit it

On the bottom of edit site you should have an option to disable it like picture below:

From a GKE perspective you can create a service type of LoadBalancer with a static IP address that will be bound and available to your project as long as it's not released. Even if you delete a Service in your GKE cluster it will still be available to bound to your recreated Service.

You can do it by either:

Reserving static IP address before Service creation

Go to GCP Dashboard -> VPC Network -> External IP addresses -> Reserve Static Address

Create a static IP

Note the IP address created

Create a Service type of LoadBalancer with previously created IP address. Example below:

apiVersion: v1
kind: Service
metadata:
  name: hello-service-lb
spec:
  selector:
    app: hello
  ports:
    - name: hello-port
      port: 80
      targetPort: 50001
      nodePort: 30051
  type: LoadBalancer
  loadBalancerIP: PASTE_HERE_IP_ADDRESS
```

<p>Please take a specific look on part: </p>

<pre class="lang-yaml prettyprint-override"><code>  loadBalancerIP: PASTE_HERE_IP_ADDRESS
</code>```

as this line is required to have previously created static IP address.

Deleting this Service will:

Delete a Service in GKE

Delete the association between Service and IP address in GCP Dashboard

It will not delete the reserved static IP address

Creating a Service before reserving static IP address

Assuming that you have already created a Service type of LoadBalancer you can:

Go to GCP Dashboard -> VPC Network -> External IP addresses

Found the IP address associated with your LoadBalancer

Change type of this IP address from: Ephemeral to Static. This will ensure that this IP will not be released when Service got deleted.

You will need to edit your Service definition when recreating it to include:

  loadBalancerIP: PASTE_HERE_IP_ADDRESS
```

If you changed your IP address type from Ephemeral to Static, deleting your Service will not release your Static IP address.

Please take a look on additional documentation:

Cloud.google.com: IP addresses: Reserve static external IP

Cloud.google.com: Kubernetes Engine: LoadBalancer

Please let me know if you have any questions in that.

Body:
Kubernetes itself does not have mechanism to stop a service.

When you create a Service type of LoadBalancer in GKE, it automatically creates a forwarding rule for external access. You can disable that rule (not delete!) to stop external traffic accessing your Service.

To disable the forwarding rule:

Check the associated IP address with a LoadBalancer by either:

issuing: $ kubectl get svc

going to: GCP Dashboard -> Kubernetes Engine -> Services & Ingress

Go to GCP Dashboard -> VPC Network -> External IP addresses

Find your LB's IP and copy name of the forwarding rule associated with it

Go to GCP Dashboard -> VPC Network -> Firewall

Search for mentioned forwarding rule

Edit it

On the bottom of edit site you should have an option to disable it like picture below:

From a GKE perspective you can create a service type of LoadBalancer with a static IP address that will be bound and available to your project as long as it's not released. Even if you delete a Service in your GKE cluster it will still be available to bound to your recreated Service.

You can do it by either:

Reserving static IP address before Service creation

Go to GCP Dashboard -> VPC Network -> External IP addresses -> Reserve Static Address

Create a static IP

Note the IP address created

Create a Service type of LoadBalancer with previously created IP address. Example below:

apiVersion: v1
kind: Service
metadata:
  name: hello-service-lb
spec:
  selector:
    app: hello
  ports:
    - name: hello-port
      port: 80
      targetPort: 50001
      nodePort: 30051
  type: LoadBalancer
  loadBalancerIP: PASTE_HERE_IP_ADDRESS

Please take a specific look on part:

  loadBalancerIP: PASTE_HERE_IP_ADDRESS

as this line is required to have previously created static IP address.

Deleting this Service will:

Delete a Service in GKE

Delete the association between Service and IP address in GCP Dashboard

It will not delete the reserved static IP address

Creating a Service before reserving static IP address

Assuming that you have already created a Service type of LoadBalancer you can:

Go to GCP Dashboard -> VPC Network -> External IP addresses

Found the IP address associated with your LoadBalancer

Change type of this IP address from: Ephemeral to Static. This will ensure that this IP will not be released when Service got deleted.

You will need to edit your Service definition when recreating it to include:

  loadBalancerIP: PASTE_HERE_IP_ADDRESS

If you changed your IP address type from Ephemeral to Static, deleting your Service will not release your Static IP address.

Please take a look on additional documentation:

Cloud.google.com: IP addresses: Reserve static external IP

Cloud.google.com: Kubernetes Engine: LoadBalancer

Please let me know if you have any questions in that.


问:
How can I use IF ELSE in WHERE clause on the basis of a string variable?
I have an SP. It returns some number of rows. Here is the SP:

```<code>ALTER PROCEDURE [dbo].[spGetClients]
</code>```

(
    @orderBy varchar(50),
    @startAge int,
    @endAge int,
    @sex char,
    @staffId nvarchar(1024),
    @statusId nvarchar(1024),
    @ethnicityId nvarchar(1024),
    @treatmentProviderId nvarchar(1024)
)
AS
BEGIN
    SET NOCOUNT ON;

```<code>IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, dbo.GetClientFullName(c.FirstName, c.MiddleInit, c.LastName) AS ClientName,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex,
    dbo.GetClientStatus(c.Id, @statusId) AS Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id, @ethnicityId) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id, @staffId) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS HealthProvider,
    dbo.GetClientTreatmentProviders(c.Id, @treatmentProviderId) AS TreatmentProvider
    FROM Client c
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    LEFT OUTER JOIN GeneralStatus gs on gs.Id = c.StatusId
    where gs.Name <> 'Deleted'
    and (dbo.GetAge(c.DateOfBirth, GETDATE()) BETWEEN @startAge and @endAge)
    and ((@sex = 'M' and c.sex = 'M') or (@sex = 'F' and c.Sex = 'F') or (@sex = '' and (c.Sex in ('M', 'F', ''))))
    and dbo.GetClientStaffContacts(c.Id, @staffId) is not null
    and dbo.GetClientStaffContacts(c.Id, @staffId) is not null
    and dbo.GetClientStatus(c.Id, @statusId) is not null
    and dbo.GetEthnicity(c.Id, @ethnicityId) is not null
    and dbo.GetClientTreatmentProviders(c.Id, @treatmentProviderId) is not null
    ORDER BY ClientName
END
END
</code>```

The UDFs(User defined functions) are dbo.GetClientStaffContacts(c.Id, @staffId) and other. They return some rows which are having null as well. That's why I'm using last 5 statements in where clause so that only non null values can be collected. Everything is working fine but the problem is, I want this check of non null only when these variables are NOT empty string:

```<code>@staffId nvarchar(1024),
@statusId nvarchar(1024),
@ethnicityId nvarchar(1024),
@treatmentProviderId nvarchar(1024)
</code>```

How can I resolve this issue?
I want something like this:

If @staffId <> '' then dbo.GetClientStaffContacts(c.Id, @staffId) is not null

答:
```<code> AND  ((@staffId = "") OR (dbo.GetClientStaffContacts(c.Id, @staffId) is not null))
</code>```

Body:
I have an SP. It returns some number of rows. Here is the SP:

ALTER PROCEDURE [dbo].[spGetClients]

(
    @orderBy varchar(50),
    @startAge int,
    @endAge int,
    @sex char,
    @staffId nvarchar(1024),
    @statusId nvarchar(1024),
    @ethnicityId nvarchar(1024),
    @treatmentProviderId nvarchar(1024)
)
AS
BEGIN
    SET NOCOUNT ON;

IF(@orderBy = 'Consumer Name')
BEGIN
    SELECT c.Id, dbo.GetClientFullName(c.FirstName, c.MiddleInit, c.LastName) AS ClientName,
    c.DateOfBirth, dbo.GetAge(c.DateOfBirth, GETDATE()) AS Age, c.Sex,
    dbo.GetClientStatus(c.Id, @statusId) AS Status, ca.Address, co.Phone,
    dbo.GetEthnicity(c.Id, @ethnicityId) AS Ethnicity, dbo.GetDevelopmentalDisabilities(c.Id) AS Disabilities,
    dbo.GetClientStaffContacts(c.Id, @staffId) AS Staff, dbo.GetClientContacts(c.Id) AS Contact,
    dbo.GetClientInsuranceProviders(c.Id) AS HealthProvider,
    dbo.GetClientTreatmentProviders(c.Id, @treatmentProviderId) AS TreatmentProvider
    FROM Client c
    LEFT OUTER JOIN(
        SELECT ca.ParentEntityId, ca.Address
        FROM ContactAddress ca
        INNER JOIN EntityName en ON en.Id = ca.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON ca.glAddressTypeId = gl.Id AND gl.LookupItem = 'Primary'
    ) ca ON c.Id = ca.ParentEntityId
    LEFT OUTER JOIN(
        SELECT co.ParentEntityId, co.ContactData Phone
        FROM ContactOther co
        INNER JOIN EntityName en ON en.Id = co.EntityNameId AND en.Name = 'Client'
        INNER JOIN GeneralLookup gl ON co.glContactTypeId = gl.Id AND gl.LookupItem = 'Home'
    ) co ON c.Id = co.ParentEntityId
    LEFT OUTER JOIN GeneralStatus gs on gs.Id = c.StatusId
    where gs.Name <> 'Deleted'
    and (dbo.GetAge(c.DateOfBirth, GETDATE()) BETWEEN @startAge and @endAge)
    and ((@sex = 'M' and c.sex = 'M') or (@sex = 'F' and c.Sex = 'F') or (@sex = '' and (c.Sex in ('M', 'F', ''))))
    and dbo.GetClientStaffContacts(c.Id, @staffId) is not null
    and dbo.GetClientStaffContacts(c.Id, @staffId) is not null
    and dbo.GetClientStatus(c.Id, @statusId) is not null
    and dbo.GetEthnicity(c.Id, @ethnicityId) is not null
    and dbo.GetClientTreatmentProviders(c.Id, @treatmentProviderId) is not null
    ORDER BY ClientName
END
END

The UDFs(User defined functions) are dbo.GetClientStaffContacts(c.Id, @staffId) and other. They return some rows which are having null as well. That's why I'm using last 5 statements in where clause so that only non null values can be collected. Everything is working fine but the problem is, I want this check of non null only when these variables are NOT empty string:

@staffId nvarchar(1024),
@statusId nvarchar(1024),
@ethnicityId nvarchar(1024),
@treatmentProviderId nvarchar(1024)

How can I resolve this issue?
I want something like this:

If @staffId <> '' then dbo.GetClientStaffContacts(c.Id, @staffId) is not null


问:
The right way to pass a input to the typescript file
I know about this way to send a input from the user to the typescript (angular) :

```<code>    <form >
    <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" />
    </form>
</code>```

But its looking for not very effective , i create a reference to the DOM with #input and after that send the input.value .

After all, I am very confused about the input.value does he refer to #input or to to (input)=...;.

Bottom line, is there a more efficient way to pass the value the user puts into the box, into the typescript file and then use it for another tag in the HTML file?

For example the user put a size of text and i want to use with the use on another tag on HTML ....

答:
First of you you have used ngModel with input, so your inputcolor will have that value, and you can use it. But if you want it passed to a method you can do it like :-

```<code><input type="text" [(ngModel)]="inputColor" (change)="sentInput($event.target.value) />
</code>```

Change event will be fired as soon as user is done typing and click anywhere else.

then have a sendInput method in ts to copy received value in a property

```<code>public sendInput(value) {
  this.data = value;
}
</code>```

OR

If you don't need two way binding, you can use ngModel for one way binding as well like :-

```<code><input type="text" (ngModel)="inputColor" />
</code>```

After this typescript value change will not impact, only change in template will be reflected in typescript variable.

Body:
I know about this way to send a input from the user to the typescript (angular) :

    <form >
    <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" />
    </form>

But its looking for not very effective , i create a reference to the DOM with #input and after that send the input.value .

After all, I am very confused about the input.value does he refer to #input or to to (input)=...;.

Bottom line, is there a more efficient way to pass the value the user puts into the box, into the typescript file and then use it for another tag in the HTML file?

For example the user put a size of text and i want to use with the use on another tag on HTML ....

Body:
First of you you have used ngModel with input, so your inputcolor will have that value, and you can use it. But if you want it passed to a method you can do it like :-

<input type="text" [(ngModel)]="inputColor" (change)="sentInput($event.target.value) />

Change event will be fired as soon as user is done typing and click anywhere else.

then have a sendInput method in ts to copy received value in a property

public sendInput(value) {
  this.data = value;
}

OR

If you don't need two way binding, you can use ngModel for one way binding as well like :-

<input type="text" (ngModel)="inputColor" />

After this typescript value change will not impact, only change in template will be reflected in typescript variable.


问:
Showing the paperclip icon on a particular message when there are no attachments
In order to save space, I have different VBA modules designed to automatically remove attachments from sent mail or to manually (on macro run) remove attachments from received mail.  The attachments are saved to my local hard drive and the Outlook.Mailitem.HTMLBody is updated with links to the saved attachments.

Naturally, when the attachments are removed from a particular message, the paperclip icon disappears.  I would like the paperclip icon to remain visible for those particular messages despite them no longer having attachments.

I could create a small attachment and add that to the message in order to make the icon appear, but I would prefer not to.  Is it possible to manually set the property that causes the paperclip icon to be visible?

I was thinking I could use PropertyAccessor.SetProperty to set the SmartNoAttach property in such a way that the icon appears, but I am not sure how, nor if it's even possible.

Here is my code that I have in ThisOutlookSession that automatically removes attachments from sent mail.  I am not a strong coder so any feedback on this code is welcome.

```<code>Public WithEvents objSentMails As Outlook.Items

Private Sub Application_Startup()

    Set objSentMails = Outlook.Application.Session.GetDefaultFolder(olFolderSentMail).Items
End Sub

Private Sub objSentMails_ItemAdd(ByVal Item As Object)

    Dim objSentMail As Outlook.MailItem
    Dim objAttachments As Outlook.Attachments
    Dim i As Long
    Dim lngCount As Long
    Dim strAttachmentInfo As String
    Dim strFile As String
    Dim strFilename As String
    Dim strDeletedFiles As String

On Error Resume Next

    'Only work on emails
    If Item.Class = olMail Then

        Set objSentMail = Item
        strFolderpath = "H:\Desktop\Attachments\Sent\" & Format(objSentMail.SentOn, "yyyy.mm.dd") & "\"

        'creates subdirectory based on sent date
        If Dir(strFolderpath, vbDirectory) = "" Then
            MkDir strFolderpath
        End If

        'converts emails to HTML format
        If objSentMail.BodyFormat <> olFormatHTML Then
            objSentMail.BodyFormat = olFormatHTML
            objSentMail.Save
        End If

        Set objAttachments = objSentMail.Attachments
        lngCount = objAttachments.Count

        strDeletedFiles = ""

        'cycles through all attachments, saves them, and removes them from the message

        If lngCount > 0 Then
            For i = lngCount To 1 Step -1
                strFile = objAttachments.Item(i).FileName
                strFilename = strFile
                strFile = strFolderpath & strFile

                'ignores small files (e.g. embedded social media logos)
                If objAttachments.Item(i).Size > 6000 Then
                    objAttachments.Item(i).SaveAsFile strFile
                    strDeletedFiles = strDeletedFiles & "<br><a style='color: #ffffff; !important;' href='file://" & strFile & "'>" & strFilename & "</a>"
                    objAttachments.Item(i).Delete
                End If
            Next i

            'Insert the information of removed attachments to the body
            If strDeletedFiles <> "" Then
                '90s style drop-shadow table
                objSentMail.HTMLBody = "<p><table style='border-spacing: 0;border-collapse: collapse;'><tr style='height: 5px'><td style='background:#54A5CB; width: 8px'></td><td style='background:#54A5CB; border-color:#54A5CB'></td><td style='background: #54A5CB;'></td><td style='width:8px'></td></tr><tr><td style='background: #54A5CB;'></td><td style='background: #54A5CB; color: #ffffff; padding: 0px; font-family:calibri;'><strong style='font-size: 18px'>Attachments:</strong> " & strDeletedFiles & "</td><td style='background: #54A5CB;'></td><td style='background: #264957; width: 8px'></td></tr><tr style='height: 5px'><td style='background: #54A5CB; width: 8px'></td><td style='background: #54A5CB;'></td><td style='background: #54A5CB;'></td><td style='background: #264957; width:8px'></td></tr><tr style='height: 5px'><td></td><td style='background: #264957'></td><td style='background: #264957'></td><td style='background: #264957'></td></tr></table></p><br>" & objSentMail.HTMLBody
                objSentMail.Save
            End If
        End If
    End If

Set objAttachments = Nothing
Set objSentMail = Nothing

End Sub
</code>```

答:
You are on the right avenue, you can use the PropertyAccessor.SetProperty method which sets the property specified by SchemaName to the value specified by Value.

```<code>Sub DemoPropertyAccessorSetProperty()
 Dim myProp As String
 Dim myValue As Variant
 Dim oMail As Outlook.MailItem
 Dim oPA As Outlook.PropertyAccessor
 'Get first item in the inbox
 Set oMail = _
 Application.Session.GetDefaultFolder(olFolderInbox).Items(1)
 'Name for custom property using the MAPI string namespace
 myProp = "http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B"
 myValue = True
 'Set value with SetProperty call
 'If the property does not exist, then SetProperty
 'adds the property to the object when saved.
 'The type of the property is the type of the element
 'passed in myValue.
 On Error GoTo ErrTrap
 Set oPA = oMail.PropertyAccessor
 oPA.SetProperty myProp, myValue

 'Save the item
 oMail.Save
 Exit Sub
ErrTrap:
 Debug.Print Err.Number, Err.Description
End Sub
</code>```

Body:
In order to save space, I have different VBA modules designed to automatically remove attachments from sent mail or to manually (on macro run) remove attachments from received mail.  The attachments are saved to my local hard drive and the Outlook.Mailitem.HTMLBody is updated with links to the saved attachments.

Naturally, when the attachments are removed from a particular message, the paperclip icon disappears.  I would like the paperclip icon to remain visible for those particular messages despite them no longer having attachments.

I could create a small attachment and add that to the message in order to make the icon appear, but I would prefer not to.  Is it possible to manually set the property that causes the paperclip icon to be visible?

I was thinking I could use PropertyAccessor.SetProperty to set the SmartNoAttach property in such a way that the icon appears, but I am not sure how, nor if it's even possible.

Here is my code that I have in ThisOutlookSession that automatically removes attachments from sent mail.  I am not a strong coder so any feedback on this code is welcome.

Public WithEvents objSentMails As Outlook.Items

Private Sub Application_Startup()

    Set objSentMails = Outlook.Application.Session.GetDefaultFolder(olFolderSentMail).Items
End Sub

Private Sub objSentMails_ItemAdd(ByVal Item As Object)

    Dim objSentMail As Outlook.MailItem
    Dim objAttachments As Outlook.Attachments
    Dim i As Long
    Dim lngCount As Long
    Dim strAttachmentInfo As String
    Dim strFile As String
    Dim strFilename As String
    Dim strDeletedFiles As String

On Error Resume Next

    'Only work on emails
    If Item.Class = olMail Then

        Set objSentMail = Item
        strFolderpath = "H:\Desktop\Attachments\Sent\" & Format(objSentMail.SentOn, "yyyy.mm.dd") & "\"

        'creates subdirectory based on sent date
        If Dir(strFolderpath, vbDirectory) = "" Then
            MkDir strFolderpath
        End If

        'converts emails to HTML format
        If objSentMail.BodyFormat <> olFormatHTML Then
            objSentMail.BodyFormat = olFormatHTML
            objSentMail.Save
        End If

        Set objAttachments = objSentMail.Attachments
        lngCount = objAttachments.Count

        strDeletedFiles = ""

        'cycles through all attachments, saves them, and removes them from the message

        If lngCount > 0 Then
            For i = lngCount To 1 Step -1
                strFile = objAttachments.Item(i).FileName
                strFilename = strFile
                strFile = strFolderpath & strFile

                'ignores small files (e.g. embedded social media logos)
                If objAttachments.Item(i).Size > 6000 Then
                    objAttachments.Item(i).SaveAsFile strFile
                    strDeletedFiles = strDeletedFiles & "
" & strFilename & ""
                    objAttachments.Item(i).Delete
                End If
            Next i

            'Insert the information of removed attachments to the body
            If strDeletedFiles <> "" Then
                '90s style drop-shadow table
                objSentMail.HTMLBody = "

	Attachments: " & strDeletedFiles & "

" & objSentMail.HTMLBody
                objSentMail.Save
            End If
        End If
    End If

Set objAttachments = Nothing
Set objSentMail = Nothing

End Sub

Body:
You are on the right avenue, you can use the PropertyAccessor.SetProperty method which sets the property specified by SchemaName to the value specified by Value.

Sub DemoPropertyAccessorSetProperty()
 Dim myProp As String
 Dim myValue As Variant
 Dim oMail As Outlook.MailItem
 Dim oPA As Outlook.PropertyAccessor
 'Get first item in the inbox
 Set oMail = _
 Application.Session.GetDefaultFolder(olFolderInbox).Items(1)
 'Name for custom property using the MAPI string namespace
 myProp = "http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B"
 myValue = True
 'Set value with SetProperty call
 'If the property does not exist, then SetProperty
 'adds the property to the object when saved.
 'The type of the property is the type of the element
 'passed in myValue.
 On Error GoTo ErrTrap
 Set oPA = oMail.PropertyAccessor
 oPA.SetProperty myProp, myValue

 'Save the item
 oMail.Save
 Exit Sub
ErrTrap:
 Debug.Print Err.Number, Err.Description
End Sub


问:
Is there a way to perform all Modernizr tests all at once?
I'm new to Modernizr and I'm just looking for a simple way to check for overall browser compatibility. I've generated a Modernizr script to test for only the most essential components of my web application, which is highly dependent on HTML5, CSS3, and modern JavaScript methods. Is there a way to run all of these tests simultaneously? Looking over the documentation, I see plenty of ways to test each feature one by one, but I'm not seeing a way to do it all at once. I'm hoping to do something like this:

Pseudocode

```<code>if (Modernizr.testAll()) {
  // Load site
} else {
  // Redirect to compatibility page
}
</code>```

答:
Use this Code if you want to display all feature detections in the browser:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Modernizr Test</title>

Feature Detection

```

Body:
I'm new to Modernizr and I'm just looking for a simple way to check for overall browser compatibility. I've generated a Modernizr script to test for only the most essential components of my web application, which is highly dependent on HTML5, CSS3, and modern JavaScript methods. Is there a way to run all of these tests simultaneously? Looking over the documentation, I see plenty of ways to test each feature one by one, but I'm not seeing a way to do it all at once. I'm hoping to do something like this:

Pseudocode

if (Modernizr.testAll()) {
  // Load site
} else {
  // Redirect to compatibility page
}

Body:
Use this Code if you want to display all feature detections in the browser:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Modernizr Test</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.0.6/modernizr.min.js"></script>

</head>
<body>
<h1>Feature Detection</h1>
<div id="feature-detection-result">

</div>
<script>
    var features = Object.keys(Modernizr);
    features = features.sort();

    features.forEach(feature => {
        if (typeof Modernizr[feature] === "boolean") {
            var element = document.createElement('p');
            element.innerHTML = feature + ' ' + Modernizr[feature];
            document.getElementById('feature-detection-result').appendChild(
                element
            );
            console.log(feature, Modernizr[feature]);
        }
        }
    );
</script>
</body>
</html>


问:
TeamCity agent error “failed to perform checkout on agent. exit code: 128”
This  link do not help me.

VCS parameters: Fetch URL: http://***.com:7990/scm/clear/pro.git
  Default branch: refs/heads/master Branch specification:+:refs/heads/*
  Authentication method: Password

Connection test complete successfully

I see files in repository

checkout rules:

```<code>+:. => pro
</code>```

Build log

```<code>[15:56:00] :     [Updating sources] VCS Root: pro (1s)
[15:56:00] :         [VCS Root: pro] checkout rules: =>pro; revision: 10e1d06cce989c706b1ca0bfce6376cf47416bb8
[15:56:00] :         [VCS Root: pro] Git version: 2.8.2.0
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe show-ref
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe show-ref refs/heads/master
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe show-ref refs/heads/master
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master
[15:56:00] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master] C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat store: C:BuildAgenttempbuildTmpcredHelper211792100691636860.bat: command not found
[15:56:00] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master] fatal: remote error: Repository does not exist
[15:56:00] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master] The requested repository does not exist, or you do not have permission to
[15:56:00] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master] access it.
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe init --bare
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe remote add origin http://user@vm-cint03.unix.com:7990/scm/clear/pro.git
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master
[15:56:01] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master] C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat store: C:BuildAgenttempbuildTmpcredHelper2255037882340038481.bat: command not found
[15:56:01] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master] fatal: remote error: Repository does not exist
[15:56:01] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master] The requested repository does not exist, or you do not have permission to
[15:56:01] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master] access it.
[15:56:01]E:     [Updating sources] Failed to perform checkout on agent: 'git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master' command failed.
exit code: 128
stderr: C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat store: C:BuildAgenttempbuildTmpcredHelper2255037882340038481.bat: command not found
fatal: remote error: Repository does not exist
The requested repository does not exist, or you do not have permission to
access it.
</code>```

I have a permission and I can clone it.

What could be the cause and how to fix?

答:
In my case (teamcity 2020), I had to replace

```<code>url = git@github.com:'Projectname'.git
</code>```

with

```<code>url = https://github.com/'Projectname'.git
</code>```

in the git config file of the agents.

Not sure why, however, it solved the issue...

Body:
This  link do not help me.

VCS parameters: Fetch URL: http://***.com:7990/scm/clear/pro.git
  Default branch: refs/heads/master Branch specification:+:refs/heads/*
  Authentication method: Password

Connection test complete successfully

I see files in repository

checkout rules:

+:. => pro

Build log

[15:56:00] :     [Updating sources] VCS Root: pro (1s)
[15:56:00] :         [VCS Root: pro] checkout rules: =>pro; revision: 10e1d06cce989c706b1ca0bfce6376cf47416bb8
[15:56:00] :         [VCS Root: pro] Git version: 2.8.2.0
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe show-ref
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe show-ref refs/heads/master
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe show-ref refs/heads/master
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master
[15:56:00] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master] C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat store: C:BuildAgenttempbuildTmpcredHelper211792100691636860.bat: command not found
[15:56:00] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master] fatal: remote error: Repository does not exist
[15:56:00] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master] The requested repository does not exist, or you do not have permission to
[15:56:00] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper211792100691636860.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass8519024404529146114.bat fetch --progress origin +refs/heads/master:refs/heads/master] access it.
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe init --bare
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe remote add origin http://user@vm-cint03.unix.com:7990/scm/clear/pro.git
[15:56:00] :         [VCS Root: pro] [C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master
[15:56:01] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master] C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat store: C:BuildAgenttempbuildTmpcredHelper2255037882340038481.bat: command not found
[15:56:01] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master] fatal: remote error: Repository does not exist
[15:56:01] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master] The requested repository does not exist, or you do not have permission to
[15:56:01] :             [[C:\BuildAgent\system\git\git-2EAC5546.git]: git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master] access it.
[15:56:01]E:     [Updating sources] Failed to perform checkout on agent: 'git.exe -c credential.helper=C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat -c core.askpass=C:\BuildAgent\temp\buildTmp\pass7759894979385805778.bat fetch --progress origin +refs/heads/master:refs/heads/master' command failed.
exit code: 128
stderr: C:\BuildAgent\temp\buildTmp\credHelper2255037882340038481.bat store: C:BuildAgenttempbuildTmpcredHelper2255037882340038481.bat: command not found
fatal: remote error: Repository does not exist
The requested repository does not exist, or you do not have permission to
access it.

I have a permission and I can clone it.

What could be the cause and how to fix?

Body:
In my case (teamcity 2020), I had to replace

url = git@github.com:'Projectname'.git

with

url = https://github.com/'Projectname'.git

in the git config file of the agents.

Not sure why, however, it solved the issue...


问:
Using dictConfig() with variable log file name
I have configuration dictionary for python scripts that I import from another module like below

```<code>LOG_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {
        '': {
        'handlers': ['consoleHandler', 'fileHandler'],
        'level': 'DEBUG'
    }
},
'handlers': {
    'consoleHandler': {
        'level': 'INFO',
        'formatter': 'consoleFormatter',
        'class': 'logging.StreamHandler',
        'stream': 'ext://sys.stdout',
    },
    'fileHandler': {
        'level': 'INFO',
        'formatter': 'fileFormatter',
        'class': 'logging.FileHandler',
        'mode': 'w',
    }
},
'formatters': {
    'fileFormatter': {
        'format': '%(asctime)s - %(levelname)s -  %(name)s - %(module)s - %(funcName)s - %(message)s',
                    'datefmt': '%Y-%m-%d %H:%M:%S',
                    'class': 'logging.Formatter'
    },
    'consoleFormatter': {
        'format': 'UAC_API>> %(levelname)s - %(message)s'
    },
},

}
</code>```

I want log filename to be variable. When loading configuration from a file, I used:

```<code>logging.config.fileConfig(config_file,
                          defaults={'logfilename': logfullpath},
                          disable_existing_loggers=False)
</code>```

Where logfullpath is path to the log file.

But defaults={'logfilename': logfullpath} does not work with dictConfig (comparing to logging.config.fileConfig has just one agument). Would anybody help me with that please?

答:
Found a workaround if anyone has the same problem. Since the LOG_CONFIG is the dictionary I expanded it like can be seen below (added filename:logfullpath  as key value pair for fileHandler).  Then I used it as argument for dictConfig.

```<code>LOG_CONFIG['handlers']['fileHandler']['filename'] = logfullpath

logging.config.dictConfig(LOG_CONFIG)
</code>```

Body:
I have configuration dictionary for python scripts that I import from another module like below

LOG_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'loggers': {
        '': {
        'handlers': ['consoleHandler', 'fileHandler'],
        'level': 'DEBUG'
    }
},
'handlers': {
    'consoleHandler': {
        'level': 'INFO',
        'formatter': 'consoleFormatter',
        'class': 'logging.StreamHandler',
        'stream': 'ext://sys.stdout',
    },
    'fileHandler': {
        'level': 'INFO',
        'formatter': 'fileFormatter',
        'class': 'logging.FileHandler',
        'mode': 'w',
    }
},
'formatters': {
    'fileFormatter': {
        'format': '%(asctime)s - %(levelname)s -  %(name)s - %(module)s - %(funcName)s - %(message)s',
                    'datefmt': '%Y-%m-%d %H:%M:%S',
                    'class': 'logging.Formatter'
    },
    'consoleFormatter': {
        'format': 'UAC_API>> %(levelname)s - %(message)s'
    },
},

}

I want log filename to be variable. When loading configuration from a file, I used:

logging.config.fileConfig(config_file,
                          defaults={'logfilename': logfullpath},
                          disable_existing_loggers=False)

Where logfullpath is path to the log file.

But defaults={'logfilename': logfullpath} does not work with dictConfig (comparing to logging.config.fileConfig has just one agument). Would anybody help me with that please?

Body:
Found a workaround if anyone has the same problem. Since the LOG_CONFIG is the dictionary I expanded it like can be seen below (added filename:logfullpath  as key value pair for fileHandler).  Then I used it as argument for dictConfig.

LOG_CONFIG['handlers']['fileHandler']['filename'] = logfullpath

logging.config.dictConfig(LOG_CONFIG)


问:
How To Get Every Alternate Object In Array In JS
I wanted to know how can we get every alternate object in a array. For EG -

```<code>arr = ["foo","bar","foo1","bar1"]
</code>```

I Need The values -

```<code>fir_alt = ["foo","foo1"]
sec_alt = ["bar","bar1"]
</code>```

If This Helps This Is My Intention -

I am trying to link localstorage and firestore using the js-sdk.. Data is in array and have to take the array to store it back in localstorage.fir_alt would be the keys and sec_alt would be values. So I Can Make it Much More Multi-Device..

Thanks In Advance

答:
You can use the filter function to filter out even and odd index's.

arr = ["foo","bar","foo1","bar1"]

fir_alt = arr.filter((element, index) => index % 2 == 0);
sec_alt = arr.filter((element, index) => index % 2 == 1);

console.log('fir_alt', fir_alt)
console.log('sec_alt', sec_alt)```

Body:
I wanted to know how can we get every alternate object in a array. For EG -

arr = ["foo","bar","foo1","bar1"]

I Need The values -

fir_alt = ["foo","foo1"]
sec_alt = ["bar","bar1"]

If This Helps This Is My Intention -

I am trying to link localstorage and firestore using the js-sdk.. Data is in array and have to take the array to store it back in localstorage.fir_alt would be the keys and sec_alt would be values. So I Can Make it Much More Multi-Device..

Thanks In Advance


问:
More efficient way to reuse vector as array in winsock?
I'm currently using vectors as c-style arrays to send and recieve data through Winsock.

I have a std::vector and I'm using that as my 'byte array'.

The problem is, I'm using two vectors, one for each send, and one for each recv, but what I'm doing seems to be fairly inefficient.

Example:

```<code>std::string EndBody("\r\n.\r\n");
std::fill(m_SendBuffer.begin(),m_SendBuffer.end(),0);
std::copy(EndBody.begin(),EndBody.end(),m_SendBuffer.begin());
SendData();
</code>```

SendData just calls send the appropriate amount of times and ensures everything works as it should.

Anyway. Unless I zero out the vector before each use I get errors with stuff overlapping. Is there a more efficient way for me to do what I'm doing? Because it seems that zeroing out the entire buffer on each call is horribly inefficient.

Thanks.

答:
you can use m_SendBuffer.clear()

otherwise the end() method would not know what is the real size of the buffer.

clear() is not a very expensive method to call. Unless you're working on some 486 or something it shouldn't affect your performances

OwnerDisplayName: Amja

ContentLicense: CC BY-SA 2.5

Body:
I'm currently using vectors as c-style arrays to send and recieve data through Winsock.

I have a std::vector and I'm using that as my 'byte array'.

The problem is, I'm using two vectors, one for each send, and one for each recv, but what I'm doing seems to be fairly inefficient.

Example:

std::string EndBody("\r\n.\r\n");
std::fill(m_SendBuffer.begin(),m_SendBuffer.end(),0);
std::copy(EndBody.begin(),EndBody.end(),m_SendBuffer.begin());
SendData();

SendData just calls send the appropriate amount of times and ensures everything works as it should.

Anyway. Unless I zero out the vector before each use I get errors with stuff overlapping. Is there a more efficient way for me to do what I'm doing? Because it seems that zeroing out the entire buffer on each call is horribly inefficient.

Thanks.

OwnerDisplayName: Eric