问:
createStackNavigator and createBottomTabNavigatorin React Navigation v.5
I am new to react native, and i'm using new react-navigation v.5 in my react-native app. When i use createStackNavigator and createBottomTabNavigator together in NavigationContainer i have errors - "undefined is not an object" and "Another navigator is already registered for this container. You likely have multiple navigators under a single "NavigationContainer" or "Screen". Make sure each navigator is under a separate "Screen" container." (in React Navigation v.5). Please tell me where i`m wrong?

AppNavigation.tsx

```<code>import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import { MainScreen } from "../screens/MainScreen";
import { PostScreen } from "../screens/PostScreen";
import { AboutScreen } from "../screens/AboutScreen";
import { BookedScreen } from "../screens/BookedScreen";
import { CreateScreen } from "../screens/CreateScreen";
import { THEME } from "../theme";
import { Platform } from "react-native";
import { AppHeaderIcon } from "../components/AppHeaderIcon";
import { HeaderButtons, Item } from "react-navigation-header-buttons";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";

type RootStackParamList = {
  Main: undefined;
  Post: { postId?: string; date?: string; booked?: boolean };
  About: undefined;
  Booked: undefined;
  Create: undefined;
};

const headerButtons = (title: string, icon: string, callback: () => void) => {
  return (
    <HeaderButtons HeaderButtonComponent={AppHeaderIcon}>
      <Item title={title} iconName={icon} onPress={() => callback()} />
    </HeaderButtons>
  );
};

export const AppNavigation = () => {
  const Stack = createStackNavigator<RootStackParamList>();
  const Tab = createBottomTabNavigator();

  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="Main"
        screenOptions={{
          headerTintColor:
            Platform.OS === "android" ? "white" : THEME.MAIN_COLOR,
          headerStyle: {
            backgroundColor:
              Platform.OS === "android" ? THEME.MAIN_COLOR : "white"
          }
        }}
      >
        <Stack.Screen
          name="Main"
          component={MainScreen}
          options={{
            headerTitle: "Мой блог",
            headerRight: () =>
              headerButtons("Сделать фото", "ios-camera", () =>
                console.log("Press camera")
              ),
            headerLeft: () =>
              headerButtons("drower", "ios-menu", () =>
                console.log("Press drower button")
              )
          }}
        />
        <Stack.Screen
          name="Post"
          component={PostScreen}
          options={({ route }) => ({
            headerTitle: `Пост от ${new Date(
              route.params.date
            ).toLocaleDateString()}`,
            headerRight: () =>
              headerButtons(
                "star",
                route.params.booked ? "ios-star" : "ios-star-outline",
                () => console.log("Press star button")
              )
          })}
        />
        <Stack.Screen name="About" component={AboutScreen} />
        <Stack.Screen name="Booked" component={BookedScreen} />
        <Stack.Screen name="Create" component={CreateScreen} />
      </Stack.Navigator>
      <Tab.Navigator>
        <Tab.Screen name="Post" component={PostScreen} />
        <Tab.Screen name="Booked" component={BookedScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
};

</code>```

App.tsx

```<code>import React, { useState } from "react";
import { AppLoading } from "expo";
import { bootstrap } from "./src/bootstrap";
import { AppNavigation } from "./src/navigation/AppNavigation";

export default function App() {
  const [isReady, setIsReady] = useState(false);

  if (!isReady) {
    //AppLoading - пока не завершится выполнение код дальше не пойдет
    return (
      <AppLoading
        startAsync={bootstrap}
        onFinish={() => setIsReady(true)}
        onError={err => console.log('AppLoading error - ', err)}
      />
    );
  }

  return <AppNavigation />;
}
</code>```

答:
This paragraph helped me to understand: "You can think of this as there being separate navigation stacks within each tab, and that's exactly how we will model it in React Navigation". II fixed some inaccuracies in my code:</p>

```<code>import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import { MainScreen } from "../screens/MainScreen";
import { PostScreen } from "../screens/PostScreen";
import { BookedScreen } from "../screens/BookedScreen";
import { THEME } from "../theme";
import { Platform } from "react-native";
import { AppHeaderIcon } from "../components/AppHeaderIcon";
import { HeaderButtons, Item } from "react-navigation-header-buttons";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { Ionicons } from "@expo/vector-icons";

type RootStackParamList = {
  Main: undefined;
  Post: { postId?: string; date?: string; booked?: boolean };
  About: undefined;
  Booked: undefined;
  Create: undefined;
};

const Stack = createStackNavigator<RootStackParamList>();

const headerButtons = (title: string, icon: string, callback: () => void) => {
  return (
    <HeaderButtons HeaderButtonComponent={AppHeaderIcon}>
      <Item title={title} iconName={icon} onPress={() => callback()} />
    </HeaderButtons>
  );
};

function PostNavigator() {
  return (
    <Stack.Navigator
      screenOptions={{
        headerTintColor: Platform.OS === "android" ? "white" : THEME.MAIN_COLOR,
        headerStyle: {
          backgroundColor:
            Platform.OS === "android" ? THEME.MAIN_COLOR : "white"
        }
      }}
    >
      <Stack.Screen
        name="Main"
        component={MainScreen}
        options={{
          headerTitle: "Мой блог",
          headerRight: () =>
            headerButtons("Сделать фото", "ios-camera", () =>
              console.log("Press camera")
            ),
          headerLeft: () =>
            headerButtons("drower", "ios-menu", () =>
              console.log("Press drower button")
            )
        }}
      />
      <Stack.Screen
        name="Post"
        component={PostScreen}
        options={({ route }) => ({
          headerTitle: `Пост от ${new Date(
            route.params.date
          ).toLocaleDateString()}`,
          headerRight: () =>
            headerButtons(
              "star",
              route.params.booked ? "ios-star" : "ios-star-outline",
              () => console.log("Press star button")
            )
        })}
      />
    </Stack.Navigator>
  );
}

function BookedNavigator() {
  return (
    <Stack.Navigator
      screenOptions={{
        headerTintColor: Platform.OS === "android" ? "white" : THEME.MAIN_COLOR,
        headerStyle: {
          backgroundColor:
            Platform.OS === "android" ? THEME.MAIN_COLOR : "white"
        }
      }}
    >
      <Stack.Screen
        name="Booked"
        component={BookedScreen}
        options={{
          headerTitle: "Избранное",
          headerRight: () =>
            headerButtons("Сделать фото", "ios-camera", () =>
              console.log("Press camera")
            )
        }}
      />
      <Stack.Screen
        name="Post"
        component={PostScreen}
        options={({ route }) => ({
          headerTitle: `Пост от ${new Date(
            route.params.date
          ).toLocaleDateString()}`,
          headerRight: () =>
            headerButtons(
              "star",
              route.params.booked ? "ios-star" : "ios-star-outline",
              () => console.log("Press star button")
            )
        })}
      />
    </Stack.Navigator>
  );
}

export const AppNavigation = () => {
  const Tab = createBottomTabNavigator();

  return (
    <NavigationContainer>
      <Tab.Navigator
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            if (route.name === "Post") {
              iconName = focused ? "ios-list-box" : "ios-list";
            } else if (route.name === "Booked") {
              iconName = focused ? "ios-star" : "ios-star-outline";
            }
            return <Ionicons name={iconName} size={size} color={color} />;
          }
        })}
        tabBarOptions={{
          activeTintColor: THEME.MAIN_COLOR,
          inactiveTintColor: "gray"
        }}
      >
        <Tab.Screen name="Post" component={PostNavigator}
        options={{
          tabBarLabel: 'Все посты'
        }}/>
        <Tab.Screen name="Booked" component={BookedNavigator}
        options={{
          tabBarLabel: 'Избранное'
        }}
        />
      </Tab.Navigator>
    </NavigationContainer>
  );
};

</code>```

Body:
I am new to react native, and i'm using new react-navigation v.5 in my react-native app. When i use createStackNavigator and createBottomTabNavigator together in NavigationContainer i have errors - "undefined is not an object" and "Another navigator is already registered for this container. You likely have multiple navigators under a single "NavigationContainer" or "Screen". Make sure each navigator is under a separate "Screen" container." (in React Navigation v.5). Please tell me where i`m wrong?

AppNavigation.tsx

import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import { MainScreen } from "../screens/MainScreen";
import { PostScreen } from "../screens/PostScreen";
import { AboutScreen } from "../screens/AboutScreen";
import { BookedScreen } from "../screens/BookedScreen";
import { CreateScreen } from "../screens/CreateScreen";
import { THEME } from "../theme";
import { Platform } from "react-native";
import { AppHeaderIcon } from "../components/AppHeaderIcon";
import { HeaderButtons, Item } from "react-navigation-header-buttons";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";

type RootStackParamList = {
  Main: undefined;
  Post: { postId?: string; date?: string; booked?: boolean };
  About: undefined;
  Booked: undefined;
  Create: undefined;
};

const headerButtons = (title: string, icon: string, callback: () => void) => {
  return (
    <HeaderButtons HeaderButtonComponent={AppHeaderIcon}>
      <Item title={title} iconName={icon} onPress={() => callback()} />
    </HeaderButtons>
  );
};

export const AppNavigation = () => {
  const Stack = createStackNavigator<RootStackParamList>();
  const Tab = createBottomTabNavigator();

  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="Main"
        screenOptions={{
          headerTintColor:
            Platform.OS === "android" ? "white" : THEME.MAIN_COLOR,
          headerStyle: {
            backgroundColor:
              Platform.OS === "android" ? THEME.MAIN_COLOR : "white"
          }
        }}
      >
        <Stack.Screen
          name="Main"
          component={MainScreen}
          options={{
            headerTitle: "Мой блог",
            headerRight: () =>
              headerButtons("Сделать фото", "ios-camera", () =>
                console.log("Press camera")
              ),
            headerLeft: () =>
              headerButtons("drower", "ios-menu", () =>
                console.log("Press drower button")
              )
          }}
        />
        <Stack.Screen
          name="Post"
          component={PostScreen}
          options={({ route }) => ({
            headerTitle: `Пост от ${new Date(
              route.params.date
            ).toLocaleDateString()}`,
            headerRight: () =>
              headerButtons(
                "star",
                route.params.booked ? "ios-star" : "ios-star-outline",
                () => console.log("Press star button")
              )
          })}
        />
        <Stack.Screen name="About" component={AboutScreen} />
        <Stack.Screen name="Booked" component={BookedScreen} />
        <Stack.Screen name="Create" component={CreateScreen} />
      </Stack.Navigator>
      <Tab.Navigator>
        <Tab.Screen name="Post" component={PostScreen} />
        <Tab.Screen name="Booked" component={BookedScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
};

App.tsx

import React, { useState } from "react";
import { AppLoading } from "expo";
import { bootstrap } from "./src/bootstrap";
import { AppNavigation } from "./src/navigation/AppNavigation";

export default function App() {
  const [isReady, setIsReady] = useState(false);

  if (!isReady) {
    //AppLoading - пока не завершится выполнение код дальше не пойдет
    return (
      <AppLoading
        startAsync={bootstrap}
        onFinish={() => setIsReady(true)}
        onError={err => console.log('AppLoading error - ', err)}
      />
    );
  }

  return <AppNavigation />;
}

Body:
This paragraph helped me to understand: "You can think of this as there being separate navigation stacks within each tab, and that's exactly how we will model it in React Navigation". II fixed some inaccuracies in my code:

import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import { MainScreen } from "../screens/MainScreen";
import { PostScreen } from "../screens/PostScreen";
import { BookedScreen } from "../screens/BookedScreen";
import { THEME } from "../theme";
import { Platform } from "react-native";
import { AppHeaderIcon } from "../components/AppHeaderIcon";
import { HeaderButtons, Item } from "react-navigation-header-buttons";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { Ionicons } from "@expo/vector-icons";

type RootStackParamList = {
  Main: undefined;
  Post: { postId?: string; date?: string; booked?: boolean };
  About: undefined;
  Booked: undefined;
  Create: undefined;
};

const Stack = createStackNavigator<RootStackParamList>();

const headerButtons = (title: string, icon: string, callback: () => void) => {
  return (
    <HeaderButtons HeaderButtonComponent={AppHeaderIcon}>
      <Item title={title} iconName={icon} onPress={() => callback()} />
    </HeaderButtons>
  );
};

function PostNavigator() {
  return (
    <Stack.Navigator
      screenOptions={{
        headerTintColor: Platform.OS === "android" ? "white" : THEME.MAIN_COLOR,
        headerStyle: {
          backgroundColor:
            Platform.OS === "android" ? THEME.MAIN_COLOR : "white"
        }
      }}
    >
      <Stack.Screen
        name="Main"
        component={MainScreen}
        options={{
          headerTitle: "Мой блог",
          headerRight: () =>
            headerButtons("Сделать фото", "ios-camera", () =>
              console.log("Press camera")
            ),
          headerLeft: () =>
            headerButtons("drower", "ios-menu", () =>
              console.log("Press drower button")
            )
        }}
      />
      <Stack.Screen
        name="Post"
        component={PostScreen}
        options={({ route }) => ({
          headerTitle: `Пост от ${new Date(
            route.params.date
          ).toLocaleDateString()}`,
          headerRight: () =>
            headerButtons(
              "star",
              route.params.booked ? "ios-star" : "ios-star-outline",
              () => console.log("Press star button")
            )
        })}
      />
    </Stack.Navigator>
  );
}

function BookedNavigator() {
  return (
    <Stack.Navigator
      screenOptions={{
        headerTintColor: Platform.OS === "android" ? "white" : THEME.MAIN_COLOR,
        headerStyle: {
          backgroundColor:
            Platform.OS === "android" ? THEME.MAIN_COLOR : "white"
        }
      }}
    >
      <Stack.Screen
        name="Booked"
        component={BookedScreen}
        options={{
          headerTitle: "Избранное",
          headerRight: () =>
            headerButtons("Сделать фото", "ios-camera", () =>
              console.log("Press camera")
            )
        }}
      />
      <Stack.Screen
        name="Post"
        component={PostScreen}
        options={({ route }) => ({
          headerTitle: `Пост от ${new Date(
            route.params.date
          ).toLocaleDateString()}`,
          headerRight: () =>
            headerButtons(
              "star",
              route.params.booked ? "ios-star" : "ios-star-outline",
              () => console.log("Press star button")
            )
        })}
      />
    </Stack.Navigator>
  );
}

export const AppNavigation = () => {
  const Tab = createBottomTabNavigator();

  return (
    <NavigationContainer>
      <Tab.Navigator
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            if (route.name === "Post") {
              iconName = focused ? "ios-list-box" : "ios-list";
            } else if (route.name === "Booked") {
              iconName = focused ? "ios-star" : "ios-star-outline";
            }
            return <Ionicons name={iconName} size={size} color={color} />;
          }
        })}
        tabBarOptions={{
          activeTintColor: THEME.MAIN_COLOR,
          inactiveTintColor: "gray"
        }}
      >
        <Tab.Screen name="Post" component={PostNavigator}
        options={{
          tabBarLabel: 'Все посты'
        }}/>
        <Tab.Screen name="Booked" component={BookedNavigator}
        options={{
          tabBarLabel: 'Избранное'
        }}
        />
      </Tab.Navigator>
    </NavigationContainer>
  );
};


来源: stackexchange

问:
Sorting with Nulls Last
I have the following:

```<code>public IEnumerable<Customer> SortByRegion(IEnumerable<Customer> customerList)
{
    return customerList.OrderBy(x => x.Region).ThenBy(x => x.ContactName);
}
</code>```

It needs to Orderby Region, then by ContactName. But have the Null Regions at the bottom. I have tried the following:

```<code>customerList.OrderBy(x => x.Region != null).ThenBy(x => x.ContactName);
</code>```

But id did not work. Been googling for a while. Cant seem to find it.

答:
You can do something like this: </p>

```<code>OrderBy(x => x.Region != null ? 1 : 0)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sorting with Nulls Last

Body:
I have the following:

public IEnumerable<Customer> SortByRegion(IEnumerable<Customer> customerList)
{
    return customerList.OrderBy(x => x.Region).ThenBy(x => x.ContactName);
}

It needs to Orderby Region, then by ContactName. But have the Null Regions at the bottom. I have tried the following:

customerList.OrderBy(x => x.Region != null).ThenBy(x => x.ContactName);

But id did not work. Been googling for a while. Cant seem to find it.

Body:
You can do something like this:

OrderBy(x => x.Region != null ? 1 : 0)


问:
Send and receive data through jQuery ajax and update database in Entity Framework in ASP.NET MVC
When I select dropdownlist I want to retrieve data from database according to dropdownlist ID.

The whole row is retrieved through an ajax call and I only want PurchasePrice and RemainingQuantity to display through label in view.

Second is: I want to update tbl_addproduct when user give some date from input text I created a function in jQuery but don't know how to update table row through PID.

Like previously I used in ASP.NET

```<code>update tbl_AddProduct
set Date = @date
where PID = @pid
</code>```

I have two model classes:

```<code>public class addproduct
{
    public int PID { get; set; }
    public int VID { get; set; }
    public string ProductName { get; set; }
    public decimal ProductQuantity { get; set; }
    public decimal PurchasePrice { get; set; }
    public decimal SellingPrice { get; set; }
    public decimal RemainingQuantity { get; set; }
    public DateTime Date { get; set; }
    public int SID { get; set; }
    public Boolean Paid { get; set; }
}
</code>```

Second view model. through this performing cascading dropdownlist

```<code>public class vendorproductVM
{
    public addproduct addpro { get; set; }
    public int VID { get; set; }
    public int PID { get; set; }
}
</code>```

Index view:

```<code>        <div class="row">
            <div class="col-sm-6">
                @Html.Label("Vendor Name")
                @if (ViewBag.vendorlist != null)
                {
                    @Html.DropDownListFor(m => m.VID, ViewBag.vendorlist as SelectList, "Select", new { @class = "  form-control" })
                }

            </div>
            <div class="col-sm-6">
                @Html.Label("Product Name")
                @Html.DropDownListFor(m => m.PID, new SelectList(" "), "--Select--", new { @class = "form-control" })

            </div>
        </div>
        <div class="row">

            <div class="col-sm-4">
                @Html.Label("Remaining Quantity")
                @Html.LabelFor(m => m.addpro.RemainingQuantity)
            </div>

            <div class="col-sm-4">
                @Html.Label("Purchase Price")
                @Html.LabelFor(m => m.addpro.PurchasePrice )
            </div>

            <div class="col-sm-4">
                @Html.Label("Date")
                <input type="text" id="txt_date" />
            </div>
        </div>
        <div>
            <div class="col-sm-4" style="align-content: center">
                <input type="button" id="btn_save" value="Save" CssClass="btn btn-success" />
                <input type="button" id="btn_cancel" value="Cancel" CssClass="btn btn-danger" />
            </div>
        </div>
<script>
$(function () {
     $("#VID").change(function () {

        var vid = $("#VID").val();
        $("#PID").empty();
        $.ajax({
            type: "post",
            url: "/ProductInventory/getproductlist",
            //datatype: "Json",
            data: { VID: vid, },
            success: function (products) {
                debugger
                $.each(products, function (index, row) {
                    $("#PID").append("<option value='" + row.PID + "'>" + row.ProductName + "</option>");
                });
                //$("productlist").append();
            },
            failure: function () {
                alert("something goes wrong")
            }
        })
    });

    $(function () {
    $("#btn_save").click(function () {
        $.ajax({
            type: "Post",
            url: "/ProductInventory/updatedate",
            data: {
                date: $("#txt_date").val(),
            },
            success: function (da) {
                alert("updated date successfully");
            },
            failure: function (da) {
                alert("error");
            },
        })
   })
})

$("#PID").change(function () {
        var pid = $("#PID").val();

        $.ajax({
            type: "post",
            url: "/ProductInventory/getremaining",
            data: { PID: pid },
            success: (function (data) {
                debugger
                $.each(data, function (index, value) {
                // I want to show remaining amount and purchase price in label
                // and I tried below code this
                $("#lblremquantity").html(parseInt(value.RemainingQuantity))
                    //$("#RemaingQuantity").append("<label value='" + value.PID + "'>" +
                    value.RemaingQuantity + "</label>");
                });
            })
        })
    });
})
</script>
</code>```

My controller:

```<code>public class ProductInventoryController : Controller
{
    private db_shopEntities db = new db_shopEntities();

    // GET: ProductInventory
    public ActionResult Index()
    {
        ViewBag.vendorlist = new SelectList(getvendorlist(), "VID", "VendorName");
        return View();
    }

    public List<tbl_AddVendor> getvendorlist()
    {
       List<tbl_AddVendor> vendors = db.tbl_AddVendor.ToList();
       return vendors;
    }

    public JsonResult getproductlist(int VID)
    {
        db.Configuration.ProxyCreationEnabled = false;
        List<tbl_AddProduct> products = db.tbl_AddProduct.Where(x => x.VID == VID).ToList();
        var pro = products;
        // ViewBag.productlist = new SelectList(products, "VID", "VendorName");
        return Json(products, JsonRequestBehavior.AllowGet);
    }

    public JsonResult getremainingquantity(int PID)
    {
        db.Configuration.ProxyCreationEnabled = false;

        List<tbl_AddProduct> remquantity = db.tbl_AddProduct.Where(x => x.PID == PID).ToList();
        return Json(remquantity, JsonRequestBehavior.AllowGet);
    }

    public JsonResult updatedate(string date)
    {
        DateTime sdate = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
        db.Configuration.ProxyCreationEnabled = false;

        // I want to update tbl_addproduct.. update date column when submit
        return Json(success, JsonRequestBehavior.AllowGet);
    }
}
</code>```

答:
If I am understanding your request, then an easy way to do this would be to utilize the Microsoft jQuery Unobtrusive Ajax Nuget Package.

Using this, you could set up your dropdowns within the Ajax submit form and have the submission update a targeted DIV id with new data from a partial view.

to do so, you would need to install it via the Nuget Package Manager and enter the following in your view:

```<code>@{using (Ajax.BeginForm("Metadata", "Applications", null, new AjaxOptions
     {
          HttpMethod = "POST",
          UpdateTargetId = "DivID",
          InsertionMode = InsertionMode.Replace,
          // ...
     }))
     {
          // Html Code (DropdownList) Here (within form)
     }}
// At the end of your view:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</code>```

This way, you can have a PartialViewResult on your controller side to load new data within a div you designate on the master page.

Additional resources:

YouTube

Tutorial

Body:
When I select dropdownlist I want to retrieve data from database according to dropdownlist ID.

The whole row is retrieved through an ajax call and I only want PurchasePrice and RemainingQuantity to display through label in view.

Second is: I want to update tbl_addproduct when user give some date from input text I created a function in jQuery but don't know how to update table row through PID.

Like previously I used in ASP.NET

update tbl_AddProduct
set Date = @date
where PID = @pid

I have two model classes:

public class addproduct
{
    public int PID { get; set; }
    public int VID { get; set; }
    public string ProductName { get; set; }
    public decimal ProductQuantity { get; set; }
    public decimal PurchasePrice { get; set; }
    public decimal SellingPrice { get; set; }
    public decimal RemainingQuantity { get; set; }
    public DateTime Date { get; set; }
    public int SID { get; set; }
    public Boolean Paid { get; set; }
}

Second view model. through this performing cascading dropdownlist

public class vendorproductVM
{
    public addproduct addpro { get; set; }
    public int VID { get; set; }
    public int PID { get; set; }
}

Index view:

                @Html.Label("Vendor Name")
                @if (ViewBag.vendorlist != null)
                {
                    @Html.DropDownListFor(m => m.VID, ViewBag.vendorlist as SelectList, "Select", new { @class = "  form-control" })
                }

                @Html.Label("Product Name")
                @Html.DropDownListFor(m => m.PID, new SelectList(" "), "--Select--", new { @class = "form-control" })

                @Html.Label("Remaining Quantity")
                @Html.LabelFor(m => m.addpro.RemainingQuantity)

                @Html.Label("Purchase Price")
                @Html.LabelFor(m => m.addpro.PurchasePrice )

                @Html.Label("Date")
                <input type="text" id="txt_date" />

                <input type="button" id="btn_save" value="Save" CssClass="btn btn-success" />
                <input type="button" id="btn_cancel" value="Cancel" CssClass="btn btn-danger" />

My controller:

public class ProductInventoryController : Controller
{
    private db_shopEntities db = new db_shopEntities();

    // GET: ProductInventory
    public ActionResult Index()
    {
        ViewBag.vendorlist = new SelectList(getvendorlist(), "VID", "VendorName");
        return View();
    }

    public List<tbl_AddVendor> getvendorlist()
    {
       List<tbl_AddVendor> vendors = db.tbl_AddVendor.ToList();
       return vendors;
    }

    public JsonResult getproductlist(int VID)
    {
        db.Configuration.ProxyCreationEnabled = false;
        List<tbl_AddProduct> products = db.tbl_AddProduct.Where(x => x.VID == VID).ToList();
        var pro = products;
        // ViewBag.productlist = new SelectList(products, "VID", "VendorName");
        return Json(products, JsonRequestBehavior.AllowGet);
    }

    public JsonResult getremainingquantity(int PID)
    {
        db.Configuration.ProxyCreationEnabled = false;

        List<tbl_AddProduct> remquantity = db.tbl_AddProduct.Where(x => x.PID == PID).ToList();
        return Json(remquantity, JsonRequestBehavior.AllowGet);
    }

    public JsonResult updatedate(string date)
    {
        DateTime sdate = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
        db.Configuration.ProxyCreationEnabled = false;

        // I want to update tbl_addproduct.. update date column when submit
        return Json(success, JsonRequestBehavior.AllowGet);
    }
}

Body:
If I am understanding your request, then an easy way to do this would be to utilize the Microsoft jQuery Unobtrusive Ajax Nuget Package.

Using this, you could set up your dropdowns within the Ajax submit form and have the submission update a targeted DIV id with new data from a partial view.

to do so, you would need to install it via the Nuget Package Manager and enter the following in your view:

@{using (Ajax.BeginForm("Metadata", "Applications", null, new AjaxOptions
     {
          HttpMethod = "POST",
          UpdateTargetId = "DivID",
          InsertionMode = InsertionMode.Replace,
          // ...
     }))
     {
          // Html Code (DropdownList) Here (within form)
     }}
// At the end of your view:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

This way, you can have a PartialViewResult on your controller side to load new data within a div you designate on the master page.

Additional resources:

YouTube

Tutorial


问:
Unwind segue is dismissing two view controllers when the presenting view controller is a child of tabbarController
Unwind segue dismissing two view controllers when the presenting view controller is a UIViewController presented by a child of tabbarController.
Here's the structure:

```<code>tabBarController (root) -> child(first tab) -> MiddleViewController -> TopViewController
</code>```

When I perform segue(unwind) from TopViewController, it gets dismissed and dismisses the MiddleViewController. Would it be because the presentingViewController of middleViewController is a child of the tabBarController? The function with segue parameter is indeed inside MiddleViewController. What would be the problem?

The TopViewController presentation style is  .OverCurrentContext

答:
You've hooked up the unwind segues incorrectly. If you hook them up correctly, you go back to the middle view controller without dismissing it (until you ask to dismiss it).

As you can see here, we go First -> Middle -> Top and then Top -> Middle -> First in good order, one at a time.

Body:
Unwind segue dismissing two view controllers when the presenting view controller is a UIViewController presented by a child of tabbarController.
Here's the structure:

tabBarController (root) -> child(first tab) -> MiddleViewController -> TopViewController

When I perform segue(unwind) from TopViewController, it gets dismissed and dismisses the MiddleViewController. Would it be because the presentingViewController of middleViewController is a child of the tabBarController? The function with segue parameter is indeed inside MiddleViewController. What would be the problem?

The TopViewController presentation style is  .OverCurrentContext


问:
Excel 2016 - Using Get Data to import CSV and format to show in a different column in the worksheet
Currently I have a CSV file that I am trying to import into excel using Get Data, and format to show each value separated in a different column within the excel workbook.  I have the CSV with the values separated in the file in such a way as seen below:

VBU|"VBU Name"|"PO Number"|"Customer Order Number"|"Line Number"|"Insert Date/Time"|"Ack Date"|"Confirm Date"|"Company Item Number"|"Vendor Model Number"|"Quantity Ordered"|"Line Status"|"Back Order Reason"|"Cancel Reason"|"Origin State"|"Destination State"|"Tracking Number"|"Expected Delivery Date"|"Expected Ship Date"|"Actual Ship Date"

I am having a hard time separating each value into it's separate column in the excel workbook after importing it using the Get Data - From Text/CSV.

Is there a step I am missing like a custom delimiter for instance, in order to have this imported and formatted in such a way that each column shows the individual value (column 1 = VBU, column 2 = VBU Name, Column 3 = PO Number), etc.?  This CSV file, all these values are crammed into the first column when I open the CSV in excel 2016.

Any help would be appreciated.

答: Nevermind, it was an anomally in one file.  Using Get Data -> From File -> From Text/CSV and setting delimiter as | did the trick and I was able to transform it and separate the values into different columns</p>


问:
How do I properly use strcat for char array?
I'm trying to concatenate another string onto arg[0].

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

int main() {

    char* arg[] = {
        "Hello",
        NULL,
        NULL,
        NULL
    };

    strcat(arg[0], " World");

}
</code>```

This returns abort trap.

What am I doing wrong?

答:
You are trying to rewrite a string literal with:

```<code>char* arg[] = { "Hello", ..... };    // "Hello" is a string literal, pointed to by "arg[0]".

strcat(arg[0], " World");       // Attempt to rewrite/modify a string literal.
</code>```

which isn´t possible.

String literals are only available to read, but not to write. That´s what make them "literal".

If you wonder about why:

```<code>char* arg[] = { "Hello", ..... };
</code>```

implies "Hello" as a string literal, You should read the answers to that question:

What is the difference between char s[] and char *s?

By the way, it would be even not possible (or at least get a segmentation fault at run-time) if you would do something like that:

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

int main() {

    char a[] = "Hello";  // 6 for holding "Hello" (5) + "\0" (1).

    strcat(a, " World");

}
</code>```

because the array a needs to have 12 characters for concatenating both strings and using strcat(a, " World"); - "Hello" (5 characters) + " World" (6 characters) + \0 (1 character) but it only has 6 characters for holding "Hello" + \0. There is no memory space added to the array automagically when using strcat().

If you execute the program with these statements, you are writing beyond the bounds of the array which is Undefined Behavior and this will get you probably prompt a Segmentation Fault error.

Body:
I'm trying to concatenate another string onto arg[0].

#include <stdio.h>
#include <string.h>

int main() {

    char* arg[] = {
        "Hello",
        NULL,
        NULL,
        NULL
    };

    strcat(arg[0], " World");

}

This returns abort trap.

What am I doing wrong?

Body:
You are trying to rewrite a string literal with:

char* arg[] = { "Hello", ..... };    // "Hello" is a string literal, pointed to by "arg[0]".

strcat(arg[0], " World");       // Attempt to rewrite/modify a string literal.

which isn´t possible.

String literals are only available to read, but not to write. That´s what make them "literal".

If you wonder about why:

char* arg[] = { "Hello", ..... };

implies "Hello" as a string literal, You should read the answers to that question:

What is the difference between char s[] and char *s?

By the way, it would be even not possible (or at least get a segmentation fault at run-time) if you would do something like that:

#include <stdio.h>
#include <string.h>

int main() {

    char a[] = "Hello";  // 6 for holding "Hello" (5) + "\0" (1).

    strcat(a, " World");

}

because the array a needs to have 12 characters for concatenating both strings and using strcat(a, " World"); - "Hello" (5 characters) + " World" (6 characters) + \0 (1 character) but it only has 6 characters for holding "Hello" + \0. There is no memory space added to the array automagically when using strcat().

If you execute the program with these statements, you are writing beyond the bounds of the array which is Undefined Behavior and this will get you probably prompt a Segmentation Fault error.


问:
Angular: form control value and form value not the same
When using the valueChanges callback in Angular I noticed the values form.get('field').value and form.value.field are not the same.

Example:

```<code>this.form = this.fb.group({
  email: ['default@example.com'],
)}

this.form.get('email').valueChanges.subscribe(value => {
  console.log(this.form.get('email').value);
  console.log(this.form.value.email);
});
</code>```

On the first change this.form.get('email').value will equal value of value (= the updated value). But this.form.value.email will still equal default@example.com.

Is this expected behavior?

Should I always use this.form.get('email').value over this.form.value.email?

You may also try out the stackblitz here https://stackblitz.com/edit/angular-8-reactive-form-jrvley?file=src/app/app.component.ts

答:
It's because you're logging from within the form control changes, and the form group probably hasn't been updated yet.

If you log the form group value from within the form group value changes observable, you see matching results.

https://stackblitz.com/edit/angular-8-reactive-form-fg8hws

I changed

```<code>this.contactForm.get('email').valueChanges.subscribe(value => {
  console.log(`VALUE: ${value}`);
  console.log(`FORM CONTROL VALUE: ${this.contactForm.get('email').value}`);
  console.log(`FORM VALUE: ${this.contactForm.value.email}`);
})
</code>```

to

```<code>this.contactForm.get('email').valueChanges.subscribe(value => {
  console.log(`VALUE: ${value}`);
  console.log(`FORM CONTROL VALUE: ${this.contactForm.get('email').value}`);
})

this.contactForm.valueChanges.subscribe(value => {
  console.log(`FORM VALUE: ${this.contactForm.value.email}`);
})
</code>```

Edit:

And to answer your other question, I always use the this.form.get('name') syntax. Mainly for compatibility with dynamically built forms.

Body:
When using the valueChanges callback in Angular I noticed the values form.get('field').value and form.value.field are not the same.

Example:

this.form = this.fb.group({
  email: ['default@example.com'],
)}

this.form.get('email').valueChanges.subscribe(value => {
  console.log(this.form.get('email').value);
  console.log(this.form.value.email);
});

On the first change this.form.get('email').value will equal value of value (= the updated value). But this.form.value.email will still equal default@example.com.

Is this expected behavior?

Should I always use this.form.get('email').value over this.form.value.email?

You may also try out the stackblitz here https://stackblitz.com/edit/angular-8-reactive-form-jrvley?file=src/app/app.component.ts

Body:
It's because you're logging from within the form control changes, and the form group probably hasn't been updated yet.

If you log the form group value from within the form group value changes observable, you see matching results.

https://stackblitz.com/edit/angular-8-reactive-form-fg8hws

I changed

this.contactForm.get('email').valueChanges.subscribe(value => {
  console.log(`VALUE: ${value}`);
  console.log(`FORM CONTROL VALUE: ${this.contactForm.get('email').value}`);
  console.log(`FORM VALUE: ${this.contactForm.value.email}`);
})

to

this.contactForm.get('email').valueChanges.subscribe(value => {
  console.log(`VALUE: ${value}`);
  console.log(`FORM CONTROL VALUE: ${this.contactForm.get('email').value}`);
})

this.contactForm.valueChanges.subscribe(value => {
  console.log(`FORM VALUE: ${this.contactForm.value.email}`);
})

Edit:

And to answer your other question, I always use the this.form.get('name') syntax. Mainly for compatibility with dynamically built forms.


问:
Request.POST.get not working for me in django, returning default value
I am trying to get input from a html form in django , python code below:

```<code>def add(request):
   n = request.POST.get('Username', 'Did not work')
   i = Item(name=n,price=0)
   i.save()
   return render(request,'tarkovdb/test.html')
</code>```

Second pic is my html code:

```<code><html>
    <head>
        <meta charset="UTF-8"›
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384—Vkoo8x4CGs0 OPaXtkKtu6ug5T0eNV6gBiFeWPGFN9Muh0f23Q9Ifjh" crossorigin="anonymous">
        <title>Tarkov Database Web App</title>
    </head>
    <body>
        <h1>This is the page to add items</h1>
            <li><a href="{% url 'tarkovdb:index' s'6}">List of Items in DataBase</a></li>

<form>
    <div class="form—group">
        <label for&username'> Username: </lable>
        <input type&text' name='Username' id.'username'> <br><br>
    </div>
        <button type="submit" class="btn btn—primary">Submit</button>
</form>
</code>```

答:
You need to set your method attribute to "post" on your HTML form tag. Like this:

```<code><form method="post">
    <!-- your fields here -->
</form>
</code>```

Otherwise you'll be sending a GET request, which is the default value of the method attribute.

PD.: Please paste your code, make it easy for the community to help you. Otherwise you'll get down voted.

Body:
I am trying to get input from a html form in django , python code below:

def add(request):
   n = request.POST.get('Username', 'Did not work')
   i = Item(name=n,price=0)
   i.save()
   return render(request,'tarkovdb/test.html')

Second pic is my html code:

        <meta charset="UTF-8"›
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384—Vkoo8x4CGs0 OPaXtkKtu6ug5T0eNV6gBiFeWPGFN9Muh0f23Q9Ifjh" crossorigin="anonymous">
        <title>Tarkov Database Web App</title>

This is the page to add items

List of Items in DataBase

<form>

         Username: </lable>
        <input type&text' name='Username' id.'username'>

        <button type="submit" class="btn btn—primary">Submit</button>
</form>

Body:
You need to set your method attribute to "post" on your HTML form tag. Like this:

<form method="post">
    <!-- your fields here -->
</form>

Otherwise you'll be sending a GET request, which is the default value of the method attribute.

PD.: Please paste your code, make it easy for the community to help you. Otherwise you'll get down voted.


问:
Cant connect to AKS internal ingress on private v-net from peered v-net
We have an original network with an number of linux VM's with docker swarm containers. We're migrating them to AKS but this is have to be done in steps. Currently we have setup up an ingress on a private subnet with an internal ingress below as below, use the following example https://learn.microsoft.com/en-us/azure/aks/ingress-internal-ip

The issue:- when connected to the original v-net We can't connect to 10.3.0.4 on the 2 subnet, i.e. 10.0.0.12:80 -> 10.3.0.4:80. On a test VM on the same subnet an the AKS cluster We can connect to the 10.3.0.4 just fine.

The strange things we can connect from the  original v-net to a service end point in the nic , i.e 10.0.0.12:80 -> 10.3.3.134:80/.

This is not a solution though as we could have multi replicas.

Any ideas why the loadbalancer is not visible to the original v-net?

Connected Devices in V-Net

```<code>original subnet
//10.0.0.0/24
10.0.0.0 - 10.0.0.255 (65536 addresses)
//10.0.1.0/24
10.0.1.0 - 10.0.1.255 (65536 addresses)
</code>```

which have peering set to each other

```<code>aks subnet
10.3.0.0/16
10.3.0.0 - 10.3.255.255 (65536 addresses)
</code>```

```<code>az aks create \
    --resource-group AKS_Workshop \
    --name workshop-aks-cluster \
    --network-plugin azure \
    --vnet-subnet-id "/subscriptions/../resourceGroups/AKS_Workshop/providers/Microsoft.Network/virtualNetworks/aksvnet/subnets/default" \
    --docker-bridge-address 172.17.0.1/16 \
    --dns-service-ip 10.4.0.2 \
    --service-cidr 10.4.0.0/16 \
    --generate-ssh-keys \
    --max-pods 96 \
    --node-vm-size Standard_DS2_v2
</code>```

```<code>controller:
  service:
    loadBalancerIP: 10.3.0.4
    annotations:
      service.beta.kubernetes.io/azure-load-balancer-internal: "true"
</code>```

```<code>helm install stable/nginx-ingress /
  --name backend-ingress /
  --namespace ingress -f ingress-basic.yaml
  --set controller.nodeSelector."beta\.kubernetes\.io/os"=linux
  --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux
</code>```

```<code>NAME                                            TYPE           CLUSTER-IP    EXTERNAL-IP   PORT(S)                      AGE
aks-helloworld                                  ClusterIP      10.4.121.75   <none>        80/TCP                       25h
backend-ingress-nginx-ingress-controller        LoadBalancer   10.4.233.18   10.3.0.4      80:30904/TCP,443:32023/TCP   23h
backend-ingress-nginx-ingress-default-backend   ClusterIP      10.4.198.93   <none>        80/TCP                       23h
ingress-demo                                    ClusterIP      10.4.53.2     <none>        80/TCP                       25h
</code>```

```<code>Name:              ingress-demo
Namespace:         ingress
Labels:            <none>
Annotations:       <none>
Selector:          app=acs-helloworld-saucy-antelope
Type:              ClusterIP
IP:                10.4.53.2
Port:              <unset>  80/TCP
TargetPort:        80/TCP
Endpoints:         10.3.3.134:80
Session Affinity:  None
Events:            <none>
</code>```

答:
Turns out the issue is relate to the 2 v-net being in different regions. Once I created a v-net in the same region I had no issues hitting the internal load balancer endpoint, as it says you can get to the internal endpoint, but if you set a number of replicas for your balancer you can only hit one of the endpoints thus rendering it pointless

VNet peering

What is VNet peering?

VNet peering (or virtual network peering) enables you to connect virtual networks. A VNet peering connection between virtual networks enables you to route traffic between them privately through IPv4 addresses. Virtual machines in the peered VNets can communicate with each other as if they are within the same network. These virtual networks can be in the same region or in different regions (also known as Global VNet Peering). VNet peering connections can also be created across Azure subscriptions.

Can I create a peering connection to a VNet in a different region?

Yes. Global VNet peering enables you to peer VNets in different regions. Global VNet peering is available in all Azure public regions, China cloud regions, and Government cloud regions. You cannot globally peer from Azure public regions to national cloud regions.

What are the constraints related to Global VNet Peering and Load Balancers?

If the two virtual networks in two different regions are peered over Global VNet Peering, you cannot connect to resources that are behind a Basic Load Balancer through the Front End IP of the Load Balancer. This restriction does not exist for a Standard Load Balancer. The following resources can use Basic Load Balancers which means you cannot reach them through the Load Balancer's Front End IP over Global VNet Peering. You can however use Global VNet peering to reach the resources directly through their private VNet IPs, if permitted.

VMs behind Basic Load Balancers
    Virtual machine scale sets with Basic Load Balancers
    Redis Cache
    Application Gateway (v1) SKU
    Service Fabric
    SQL MI
    API Management
    Active Directory Domain Service (ADDS)
    Logic Apps
    HDInsight
    Azure Batch
    App Service Environment

You can connect to these resources via ExpressRoute or VNet-to-VNet through VNet Gateways.

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

Body:
We have an original network with an number of linux VM's with docker swarm containers. We're migrating them to AKS but this is have to be done in steps. Currently we have setup up an ingress on a private subnet with an internal ingress below as below, use the following example https://learn.microsoft.com/en-us/azure/aks/ingress-internal-ip

The issue:- when connected to the original v-net We can't connect to 10.3.0.4 on the 2 subnet, i.e. 10.0.0.12:80 -> 10.3.0.4:80. On a test VM on the same subnet an the AKS cluster We can connect to the 10.3.0.4 just fine.

The strange things we can connect from the  original v-net to a service end point in the nic , i.e 10.0.0.12:80 -> 10.3.3.134:80/.

This is not a solution though as we could have multi replicas.

Any ideas why the loadbalancer is not visible to the original v-net?

Connected Devices in V-Net

original subnet
//10.0.0.0/24
10.0.0.0 - 10.0.0.255 (65536 addresses)
//10.0.1.0/24
10.0.1.0 - 10.0.1.255 (65536 addresses)

which have peering set to each other

aks subnet
10.3.0.0/16
10.3.0.0 - 10.3.255.255 (65536 addresses)

az aks create \
    --resource-group AKS_Workshop \
    --name workshop-aks-cluster \
    --network-plugin azure \
    --vnet-subnet-id "/subscriptions/../resourceGroups/AKS_Workshop/providers/Microsoft.Network/virtualNetworks/aksvnet/subnets/default" \
    --docker-bridge-address 172.17.0.1/16 \
    --dns-service-ip 10.4.0.2 \
    --service-cidr 10.4.0.0/16 \
    --generate-ssh-keys \
    --max-pods 96 \
    --node-vm-size Standard_DS2_v2

controller:
  service:
    loadBalancerIP: 10.3.0.4
    annotations:
      service.beta.kubernetes.io/azure-load-balancer-internal: "true"

helm install stable/nginx-ingress /
  --name backend-ingress /
  --namespace ingress -f ingress-basic.yaml
  --set controller.nodeSelector."beta\.kubernetes\.io/os"=linux
  --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux

NAME                                            TYPE           CLUSTER-IP    EXTERNAL-IP   PORT(S)                      AGE
aks-helloworld                                  ClusterIP      10.4.121.75   <none>        80/TCP                       25h
backend-ingress-nginx-ingress-controller        LoadBalancer   10.4.233.18   10.3.0.4      80:30904/TCP,443:32023/TCP   23h
backend-ingress-nginx-ingress-default-backend   ClusterIP      10.4.198.93   <none>        80/TCP                       23h
ingress-demo                                    ClusterIP      10.4.53.2     <none>        80/TCP                       25h

Name:              ingress-demo
Namespace:         ingress
Labels:            <none>
Annotations:       <none>
Selector:          app=acs-helloworld-saucy-antelope
Type:              ClusterIP
IP:                10.4.53.2
Port:              <unset>  80/TCP
TargetPort:        80/TCP
Endpoints:         10.3.3.134:80
Session Affinity:  None
Events:            <none>


问:
How to pass a variable from my controller, to the HTML, then to a JS function?
My controller ultimately renders this:

```<code>res.render('my-html', { title: `${title}`, myVar1, myVar2 });
</code>```

In the HTML, I can access the variables in order to display data directly into the HTML. But what I'm trying to do is then pass those variables into a client-side JS function:

```<code>function myClientSideFunction(myVar1) {
   console.log(myVar1)
};
</code>```

My webpack entry point file says:

'Uncaught ReferenceError: myVar1 is not defined'

I'm using Pug/Jade if that info helps.

答:
You would need to define those variables on the rendered HTML page in a script tag via Pug:

```<code>script.
  var myVar1 = #{myVar1};
</code>```

Then you could access them like any other javascript variable client-side.

Body:
My controller ultimately renders this:

res.render('my-html', { title: `${title}`, myVar1, myVar2 });

In the HTML, I can access the variables in order to display data directly into the HTML. But what I'm trying to do is then pass those variables into a client-side JS function:

function myClientSideFunction(myVar1) {
   console.log(myVar1)
};

My webpack entry point file says:

'Uncaught ReferenceError: myVar1 is not defined'

I'm using Pug/Jade if that info helps.

Body:
You would need to define those variables on the rendered HTML page in a script tag via Pug:

script.
  var myVar1 = #{myVar1};

Then you could access them like any other javascript variable client-side.


问:
how can i add the sendgrid webhook event Json response in a firebase cloud firestore using node.js
I have no idea how to implement this thing but before that, I have done a part of SendGrid where any document is created then it will send the email to the user. but this part what I am asking I has no idea how to proceed.this is my first part of this implementation wherein any collection if a new record is created then it will send email to the particular email and there is a response called event Object I want to write a cloud function to store the data. and I don't know how to start this function or proceed with this problem.

```<code>"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");

var serviceAccount1 = require("./key.json");

const newProject = admin.initializeApp({
  credential: admin.credential.cert(serviceAccount1),
  databaseURL: "xyz"
});
const sgMail = require("@sendgrid/mail");
const sgMailKey = "key";
sgMail.setApiKey(sgMailKey);

 exports.sentMail = functions.firestore
  .document("/Offices/{officeId}")
  .onCreate((documentSnapshot,event) => {
    const documentData = documentSnapshot.data()
    const officeID = event.params.officeId;
    console.log(JSON.stringify(event))
    const db = newProject.firestore();
    return db.collection("Offices").doc(officeID).get()
      .then(doc => {
        const data = doc.data();
        const msg = {
          to: "amarjeetkumars34@gmail.com",
          from: "singhamarjeet045@gmail.com",
          text: "hello from this side",
          templateId: "d-8ecfa59aa9d2434eb8b7d47d58b4f2cf",
          substitutionWrappers: ["{{", "}}"],
          substitutions: {
            name: data.name
          }
        };
        return sgMail.send(msg);
      })
      .then(() => console.log("payment mail sent success"))
      .catch(err => console.log(err));
  });
</code>```

and the expected output of my question be like a collection name XYZ wherein an object there are three fields like

```<code>{email:"xyz@gmail.com",
event:"processed",
timestamp:123555558855},
{email:"xyz@gmail.com",
event:"recieved",
timestamp:123555558855},
{email:"xyz@gmail.com",
event:"open",
timestamp:123555558855}
</code>```

答:
As you will read in the Sendgrid documentation:

SendGrid's Event Webhook will notify a URL of your choice via HTTP
POST with information about events that occur as SendGrid processes
your email

To implement the HTTP endpoint in your Firebase Project, you will implement an HTTPS Cloud Function that will be called by the Sendgrid webhook through an HTTPS POST request.

Each call from the Sendgrid webhook will concern a specific event and you will be able, in your Cloud Function, to get the value of the event (processed, delivered, etc...).

Now, you need in your Cloud Function to be able to link a specific event with a specific email that was previously sent through your Cloud Function. For that you should use custom arguments.

More precisely, you would add to your msg object (that you pass to the send() method)  a unique identifier. A classical value is a Firestore document ID, like event.params.officeId but could be any other unique ID that you generate in you Cloud Function.

Example of implementation

In your Cloud Function that sends the email, pass the officeId in a custom_args object, as shown below:

```<code> exports.sentMail = functions.firestore
  .document("/Offices/{officeId}")
  .onCreate((documentSnapshot,event) => {

    const documentData = documentSnapshot.data();

    const officeId = event.params.officeId;

    const msg = {
          to: "amarjeetkumars34@gmail.com",
          from: "singhamarjeet045@gmail.com",
          text: "hello from this side",
          templateId: "d-8ecfa59aa9d2434eb8b7d47d58b4f2cf",
          substitutionWrappers: ["{{", "}}"],
          substitutions: {
            name: documentData.name
          },
          custom_args: {
             "officeId": officeId
          }
    };

    return sgMail.send(msg)
      .then(() => {
         console.log("payment mail sent success"));
         return null;
      })
      .catch(err => {
         console.log(err)
         return null;
      });
  });
</code>```

Note that you get the data of the newly created document (the one which triggers the Cloud Function) through documentSnapshot.data(): you don't need to query for the same document in your Cloud Function.

Then, create a simple HTTPS Cloud Function, as follows:

```<code>exports.sendgridWebhook = functions.https.onRequest((req, res) => {
    const body = req.body; //body is an array of JavaScript objects

    const promises = [];

    body.forEach(elem => {

        const event = elem.event;
        const eventTimestamp = elem.timestamp;
        const officeId = elem.officeId;

        const updateObj = {};
        updateObj[event] = true;
        updateObj[event + 'Timestamp'] = eventTimestamp;

        promises.push(admin.firestore().collection('Offices').doc(officeId).update(updateObj));

    });

    return Promise.all(promises)
        .then(() => {
            return res.status(200).end();
        })

})
</code>```

Deploy it and grab its URL as shown in the terminal: it should be like https://us-central1-<your-project-id>.cloudfunctions.net/sendgridWebhook.

Note that here I use admin.firestore().collection('Offices').... You may use const db = newProject.firestore(); ... db.collection('Offices')...

Also note that the body of the HTTPS POST request sent by the Sendgrid webhook contains an array of JavaScript objects, therefore we will use Promise.all() to treat these different objects, i.e. write to the Firestore document with officeId the different events.

Then you need to set-up the Webhook in the Sendgrid platform, in the "Mail Settings/Event Notification" section, as explained in the doc and as shown below.

Body:
I have no idea how to implement this thing but before that, I have done a part of SendGrid where any document is created then it will send the email to the user. but this part what I am asking I has no idea how to proceed.this is my first part of this implementation wherein any collection if a new record is created then it will send email to the particular email and there is a response called event Object I want to write a cloud function to store the data. and I don't know how to start this function or proceed with this problem.

"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");

var serviceAccount1 = require("./key.json");

const newProject = admin.initializeApp({
  credential: admin.credential.cert(serviceAccount1),
  databaseURL: "xyz"
});
const sgMail = require("@sendgrid/mail");
const sgMailKey = "key";
sgMail.setApiKey(sgMailKey);

 exports.sentMail = functions.firestore
  .document("/Offices/{officeId}")
  .onCreate((documentSnapshot,event) => {
    const documentData = documentSnapshot.data()
    const officeID = event.params.officeId;
    console.log(JSON.stringify(event))
    const db = newProject.firestore();
    return db.collection("Offices").doc(officeID).get()
      .then(doc => {
        const data = doc.data();
        const msg = {
          to: "amarjeetkumars34@gmail.com",
          from: "singhamarjeet045@gmail.com",
          text: "hello from this side",
          templateId: "d-8ecfa59aa9d2434eb8b7d47d58b4f2cf",
          substitutionWrappers: ["{{", "}}"],
          substitutions: {
            name: data.name
          }
        };
        return sgMail.send(msg);
      })
      .then(() => console.log("payment mail sent success"))
      .catch(err => console.log(err));
  });

and the expected output of my question be like a collection name XYZ wherein an object there are three fields like

{email:"xyz@gmail.com",
event:"processed",
timestamp:123555558855},
{email:"xyz@gmail.com",
event:"recieved",
timestamp:123555558855},
{email:"xyz@gmail.com",
event:"open",
timestamp:123555558855}

Body:
As you will read in the Sendgrid documentation:

SendGrid's Event Webhook will notify a URL of your choice via HTTP
POST with information about events that occur as SendGrid processes
your email

To implement the HTTP endpoint in your Firebase Project, you will implement an HTTPS Cloud Function that will be called by the Sendgrid webhook through an HTTPS POST request.

Each call from the Sendgrid webhook will concern a specific event and you will be able, in your Cloud Function, to get the value of the event (processed, delivered, etc...).

Now, you need in your Cloud Function to be able to link a specific event with a specific email that was previously sent through your Cloud Function. For that you should use custom arguments.

More precisely, you would add to your msg object (that you pass to the send() method)  a unique identifier. A classical value is a Firestore document ID, like event.params.officeId but could be any other unique ID that you generate in you Cloud Function.

Example of implementation

In your Cloud Function that sends the email, pass the officeId in a custom_args object, as shown below:

 exports.sentMail = functions.firestore
  .document("/Offices/{officeId}")
  .onCreate((documentSnapshot,event) => {

    const documentData = documentSnapshot.data();

    const officeId = event.params.officeId;

    const msg = {
          to: "amarjeetkumars34@gmail.com",
          from: "singhamarjeet045@gmail.com",
          text: "hello from this side",
          templateId: "d-8ecfa59aa9d2434eb8b7d47d58b4f2cf",
          substitutionWrappers: ["{{", "}}"],
          substitutions: {
            name: documentData.name
          },
          custom_args: {
             "officeId": officeId
          }
    };

    return sgMail.send(msg)
      .then(() => {
         console.log("payment mail sent success"));
         return null;
      })
      .catch(err => {
         console.log(err)
         return null;
      });
  });

Note that you get the data of the newly created document (the one which triggers the Cloud Function) through documentSnapshot.data(): you don't need to query for the same document in your Cloud Function.

Then, create a simple HTTPS Cloud Function, as follows:

exports.sendgridWebhook = functions.https.onRequest((req, res) => {
    const body = req.body; //body is an array of JavaScript objects

    const promises = [];

    body.forEach(elem => {

        const event = elem.event;
        const eventTimestamp = elem.timestamp;
        const officeId = elem.officeId;

        const updateObj = {};
        updateObj[event] = true;
        updateObj[event + 'Timestamp'] = eventTimestamp;

        promises.push(admin.firestore().collection('Offices').doc(officeId).update(updateObj));

    });

    return Promise.all(promises)
        .then(() => {
            return res.status(200).end();
        })

})

Deploy it and grab its URL as shown in the terminal: it should be like https://us-central1-<your-project-id>.cloudfunctions.net/sendgridWebhook.

Note that here I use admin.firestore().collection('Offices').... You may use const db = newProject.firestore(); ... db.collection('Offices')...

Also note that the body of the HTTPS POST request sent by the Sendgrid webhook contains an array of JavaScript objects, therefore we will use Promise.all() to treat these different objects, i.e. write to the Firestore document with officeId the different events.

Then you need to set-up the Webhook in the Sendgrid platform, in the "Mail Settings/Event Notification" section, as explained in the doc and as shown below.


问:
Loading page fragments using $.post in jQuery
I am fetching 2 div's from a page using $.post jQuery AJAX request.  Now the data that comes after the execution is from a POST request and is something like this...

```<code>//data.php
<div id="alpha">alpha</div><div id="beta">beta</div>
</code>```

Now if i want to load the data of just the div with id 'alpha' into a div with id 'container' in the present page and if the data came by a GET request my life would be easier...

```<code>$("#container").load('data.php #alpha');
</code>```

would solve the problem.

I want to do similar filtering on success function using $.post function in jQuery so i can load the appropriate div's at the appropriate page in the current page.  How can i achieve this?

```<code>$.post('data.php',null,function(data){
//what to do here?
});
</code>```

Thanks

答:
```<code>$.post('data.php',
       function(data){
    $("#container").html($(data).find('#alpha'));

});
</code>```

<p>assuming you are replacing the entirety of container. if you're appending it then... </p>

```<code>$.post('data.php',
       function(data){
    $("#container").append($(data).find('#alpha'));

});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am fetching 2 div's from a page using $.post jQuery AJAX request.  Now the data that comes after the execution is from a POST request and is something like this...

//data.php

alpha

beta

Now if i want to load the data of just the div with id 'alpha' into a div with id 'container' in the present page and if the data came by a GET request my life would be easier...

$("#container").load('data.php #alpha');

would solve the problem.

I want to do similar filtering on success function using $.post function in jQuery so i can load the appropriate div's at the appropriate page in the current page.  How can i achieve this?

$.post('data.php',null,function(data){
//what to do here?
});

Thanks

Body:
$.post('data.php',
       function(data){
    $("#container").html($(data).find('#alpha'));

});

assuming you are replacing the entirety of container. if you're appending it then...

$.post('data.php',
       function(data){
    $("#container").append($(data).find('#alpha'));

});


问:
date index on R hourly data
I have a data frame with hourly data and I am trying to plot but I want date on x axis not just index as numbers, I want the dates to be shown on x axis

```<code>df = read.csv('~/Desktop/data.csv', header = TRUE , stringsAsFactors = FALSE)
df$Date <- as.POSIXct(strptime(df$Date,format= "%Y-%m-%d %H:%M:%OS"))
plot(df$column1)
</code>```

答:
The problem with your code seems to be that you feed a single variable into the plot command whereas what you want is a plot of column1 grouped by dates, right? If that's the case then you could use this:

DATA:

```<code>set-seed(123)
df <- data.frame(
  dates = rep(c("2009-01-01", "2009-01-02", "2009-01-03", "2009-01-04", "2009-01-05", "2009-01-06", "2009-01-07"), 1000),
  column1 = rnorm(7000, 100)
)
</code>```

SOLUTION:

Then you could use ggplot2and geom_jitterto plot column1 against dates:

```<code>library(ggplot2)
ggplot(data=df, aes(x=dates, y=column1)) + geom_jitter()
</code>```

RESULT:

The resulting plot would roughly look like this:

Title: date index on R hourly data

Body:
I have a data frame with hourly data and I am trying to plot but I want date on x axis not just index as numbers, I want the dates to be shown on x axis

df = read.csv('~/Desktop/data.csv', header = TRUE , stringsAsFactors = FALSE)
df$Date <- as.POSIXct(strptime(df$Date,format= "%Y-%m-%d %H:%M:%OS"))
plot(df$column1)

Body:
The problem with your code seems to be that you feed a single variable into the plot command whereas what you want is a plot of column1 grouped by dates, right? If that's the case then you could use this:

DATA:

set-seed(123)
df <- data.frame(
  dates = rep(c("2009-01-01", "2009-01-02", "2009-01-03", "2009-01-04", "2009-01-05", "2009-01-06", "2009-01-07"), 1000),
  column1 = rnorm(7000, 100)
)

SOLUTION:

Then you could use ggplot2and geom_jitterto plot column1 against dates:

library(ggplot2)
ggplot(data=df, aes(x=dates, y=column1)) + geom_jitter()

RESULT:

The resulting plot would roughly look like this:


问:
Is there a way to remove italic style from  tag without effecting document.execCommand("italic")
I'd like to make text in  tag not appear italic in a contenteditable div.

However, as you can see in the code snippet below, if I add font-style:normal to italic style, document.execCommand('italic') to unitalicize no longer works, as the browser correctly detects that the text is not italic.

Would there be any way to have both unitalic-looking  and a way to unitalicize?

function italicize(){
  document.execCommand("italic");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>i{
  font-style:normal;
  color:red;
}</code>```

abc

<button onclick=italicize()>italic</button>```

答:
More Solutions for this problem.

Change Node with innerText

function unitalicize(){
   var element = document.getElementsByTagName("i")[0];
   var span = document.createElement("span");
   while(element.firstChild){
           span.appendChild(element.firstChild);
   }
   element.parentElement.replaceChild(span,element)
}
function italicize(){
  var element = document.getElementsByTagName("span")[0];
  var i = document.createElement("i");
  while(element.firstChild){
     i.appendChild(element.firstChild);
  }
  element.parentElement.replaceChild(i,element)
}
  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>i{
  color:red;
}</code>```

abc

<button onclick=unitalicize()>unitalicize()</button>
<button onclick=italicize()>italicize()</button>```

Title: Is there a way to remove italic style from <i> tag without effecting document.execCommand("italic")

Body:
I'd like to make text in  tag not appear italic in a contenteditable div.

However, as you can see in the code snippet below, if I add font-style:normal to italic style, document.execCommand('italic') to unitalicize no longer works, as the browser correctly detects that the text is not italic.

Would there be any way to have both unitalic-looking  and a way to unitalicize?

function italicize(){
  document.execCommand("italic");
}

i{
  font-style:normal;
  color:red;
}

abc

<button onclick=italicize()>italic</button>

Body:
More Solutions for this problem.

Change Node with innerText

function unitalicize(){
   var element = document.getElementsByTagName("i")[0];
   var span = document.createElement("span");
   while(element.firstChild){
           span.appendChild(element.firstChild);
   }
   element.parentElement.replaceChild(span,element)
}
function italicize(){
  var element = document.getElementsByTagName("span")[0];
  var i = document.createElement("i");
  while(element.firstChild){
     i.appendChild(element.firstChild);
  }
  element.parentElement.replaceChild(i,element)
}

i{
  color:red;
}

<div contenteditable=true>a<i>b</i>c</div>

<button onclick=unitalicize()>unitalicize()</button>
<button onclick=italicize()>italicize()</button>


问:
How can I call a custom function in tryton after record creation?
I need to perform a notification on a non tryton database after the creation of the record.

I see that it's possible to overwrite the create function.. but there is any better solutions to be sure to be after the commit of the database ?

I do in this way

```<code>@classmethod
def create(cls, values):
    newObject = super(Inventory, cls).create(values)
    newObject.notifieToMainServer()
</code>```

regards

答:
Yes, you can call a function when the Transcation is commited by using the atexit function of the tryton Transaction.

So your code will be something like:

```<code>from trytond.transaction import Transaction

@classmethod
def create(cls, values):
   records = super().create(values)
   Transaction.atexit(notifyToMainServer)
   return records
</code>```

If you need to prevent the commit of the transaction when the notification can not be sent, you can use the Two-Phase commit protocol by joining some datamangers on the Transaction. Tryton by default implements an sendmail_transactional function which may be used as reference for implementing a DataManager to send your custom notifications.

Hope it helps!

Body:
I need to perform a notification on a non tryton database after the creation of the record.

I see that it's possible to overwrite the create function.. but there is any better solutions to be sure to be after the commit of the database ?

I do in this way

@classmethod
def create(cls, values):
    newObject = super(Inventory, cls).create(values)
    newObject.notifieToMainServer()

regards

Body:
Yes, you can call a function when the Transcation is commited by using the atexit function of the tryton Transaction.

So your code will be something like:

from trytond.transaction import Transaction

@classmethod
def create(cls, values):
   records = super().create(values)
   Transaction.atexit(notifyToMainServer)
   return records

If you need to prevent the commit of the transaction when the notification can not be sent, you can use the Two-Phase commit protocol by joining some datamangers on the Transaction. Tryton by default implements an sendmail_transactional function which may be used as reference for implementing a DataManager to send your custom notifications.

Hope it helps!


问:
Google Apps Script Not Loading Functions for Everyone, only me
My onSheetOpen / showSidebar is not working for anyone but me when opening my events Google sheet. I have set up triggers to launch both the onSheetOpen and showSidebar for myself, but this is not working for anyone else who opens the spreadsheet. Can anyone help figure out why this might be the case? Below is the code I'm using.</p>

```<code> /**
 * Set up custom sidebar.
 * TRIGGER: spreadsheet event 'on open'
 */
function onSheetOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Actions')
    .addItem("Register interest in current opportunity", 'registerInterest')
    .addItem("Show sidebar", 'showSidebar')
    .addToUi();

  showSidebar();
}

/**
 * Renders the sidebar
 * TRIGGER: spreadsheet event 'on open' & custom menu option
 */
function showSidebar() {
  try {
    var htmlOutput = HtmlService.createHtmlOutputFromFile('sidebar');
    SpreadsheetApp.getUi().showSidebar(htmlOutput);
  } catch(e) {
    // Just ignore - means user doesn't have edit access to sheet
  }
}

/**
 * Main function. Grabs the required data from the currently-selected row, registers interest
 * in that data in a separate sheet, and sends a confirmation email to the user.
 */
function registerInterest() {
  //var spreadsheet = SpreadsheetApp.getActive();
  // These are the attributes we capture and store in the 'interest' sheet
  var who = Session.getActiveUser().getEmail();
  var when = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm:ss');
  var data = getRowOfInterest(SpreadsheetApp.getActiveSheet());
  var id = Utilities.getUuid();
  Logger.log(id)
  if(data.what && data.what.length > 0) {
    // Get the Google Sheets ID of the target 'interest' sheet
    var id = getConfigValue("InterestSheet");
    if(id) {
      // Now try and open that sheet for updating
      var ss = SpreadsheetApp.openById(id);
      if(ss) {
        var sheet = ss.getSheetByName('Interest');
        if(sheet) {
          // All good; log interest. First, create the new row of data for the target sheet
          sheet.appendRow([ when, who, data.what, data.subject,  data.location, data.industry, data.capabilities ]);
          // Second, grab our 'template' email from config & use that to send a confirmation
          // email to the person registering their interest
          var body = getConfigValue('InterestEmail');
          MailApp.sendEmail(who, getConfigValue('InterestSubject'), null, { noReply: true, htmlBody: body });
        } else {
          throw Error('can\'t open the \'Interest expressed\' sheet (or it doesn\'t exist)');
        }
      } else {
        throw Error('can\'t open the \'Interest expressed\' sheet');
      }
    } else {
      throw Error('\'Interest expressed\' sheet not specified');
    }
  }
}

/**
 * Utility to derive the required data for registering interest.
 * Called from the registerInterest() function
 */
function getRowOfInterest(sheet) {
  var result = {};
  var row = sheet.getActiveRange().getRow(); // Get the currently-selected row index
  var fullRange = sheet.getRange(row, 1, 1, sheet.getLastColumn()); // Get the entire row of data
  //var fullRange = sheet.getRange(row, 1, 1, 9);
  Logger.log(fullRange.getValues())
  var data = fullRange.getValues();
  if(data[0] && data[0].length > 0) {
    for(var n = 0; n < data[0].length; n++) {
      // Populate specific attributes in the 'result' object - tailor this as you see fit
      if(n==0) result.subject = data[0][n];
      if(n==6) result.what = data[0][n] + ' ';
      //if(n==5 || n==7) result.what += data[0][n] + ' ';
      if(n==7) result.location = data[0][n];
      if(n==11) result.industry = data[0][n];
      if(n==12) result.capabilities = data[0][n];
    }

    result.what += '(' + sheet.getName() + ')';
    result.industry;
    result.capabilities;
    return result;
  }
}

function getSomeRange(){

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var row = sheet.getActiveRange().getRow(); // Get the currently-selected row index

  var myRange = sheet.getRange(row, 1, 1, sheet.getLastColumn());

  //Logger.log("Number of rows in range is "+myRange.getNumRows()+ " Number of columns in range is "+ myRange.getNumColumns());

}
/**
 * Utility to pull specified data from a config sheet. This assumes that a sheet called 'Config'
 * is populated thus:
 *    Column contains a load of 'key' and column 2 contains the corresponding 'values'
 * Called from registerInterest() function
 */
function getConfigValue(key) {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Config');
  var result;

  if(sheet) {
    // Scan column 1 for key and return value in column 2
    var data = sheet.getDataRange().getValues();
    for(var n = 0; n < data.length; ++n) {
      if(data[n][0].toString().match(key)) result = data[n][1];
    }
  }

  return result;
}

function hideExpiredEvents() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Events');
  var exsh=ss.getSheetByName('Expired Events');
  var sr=2;
  var rg=sh.getRange(sr,1,sh.getLastRow()-sr+1,sh.getLastColumn());
  var vA=rg.getValues();
  Logger.log(vA);
  var dt=new Date();
  var  d=0;//deleted row counter
  var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate(0)).valueOf();
  for(var i=0;i<vA.length;i++) {
    if(new Date(vA[i][3]).valueOf()<today) {
      exsh.appendRow(vA[i]);//move to bottom of expired events
      sh.deleteRow(i+sr-d++);//increment deleted row counter
    }
  }
}
</code>```

答:
Unfortunately, it seems that the issue you are encountering might be a bug.

What you can do in this case is to star the issue on Issue Tracker here by clicking the ★ next to the issue number and post a comment as well saying that you are affected by the issue.

Body:
My onSheetOpen / showSidebar is not working for anyone but me when opening my events Google sheet. I have set up triggers to launch both the onSheetOpen and showSidebar for myself, but this is not working for anyone else who opens the spreadsheet. Can anyone help figure out why this might be the case? Below is the code I'm using.

 /**
 * Set up custom sidebar.
 * TRIGGER: spreadsheet event 'on open'
 */
function onSheetOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Actions')
    .addItem("Register interest in current opportunity", 'registerInterest')
    .addItem("Show sidebar", 'showSidebar')
    .addToUi();

  showSidebar();
}

/**
 * Renders the sidebar
 * TRIGGER: spreadsheet event 'on open' & custom menu option
 */
function showSidebar() {
  try {
    var htmlOutput = HtmlService.createHtmlOutputFromFile('sidebar');
    SpreadsheetApp.getUi().showSidebar(htmlOutput);
  } catch(e) {
    // Just ignore - means user doesn't have edit access to sheet
  }
}

/**
 * Main function. Grabs the required data from the currently-selected row, registers interest
 * in that data in a separate sheet, and sends a confirmation email to the user.
 */
function registerInterest() {
  //var spreadsheet = SpreadsheetApp.getActive();
  // These are the attributes we capture and store in the 'interest' sheet
  var who = Session.getActiveUser().getEmail();
  var when = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm:ss');
  var data = getRowOfInterest(SpreadsheetApp.getActiveSheet());
  var id = Utilities.getUuid();
  Logger.log(id)
  if(data.what && data.what.length > 0) {
    // Get the Google Sheets ID of the target 'interest' sheet
    var id = getConfigValue("InterestSheet");
    if(id) {
      // Now try and open that sheet for updating
      var ss = SpreadsheetApp.openById(id);
      if(ss) {
        var sheet = ss.getSheetByName('Interest');
        if(sheet) {
          // All good; log interest. First, create the new row of data for the target sheet
          sheet.appendRow([ when, who, data.what, data.subject,  data.location, data.industry, data.capabilities ]);
          // Second, grab our 'template' email from config & use that to send a confirmation
          // email to the person registering their interest
          var body = getConfigValue('InterestEmail');
          MailApp.sendEmail(who, getConfigValue('InterestSubject'), null, { noReply: true, htmlBody: body });
        } else {
          throw Error('can\'t open the \'Interest expressed\' sheet (or it doesn\'t exist)');
        }
      } else {
        throw Error('can\'t open the \'Interest expressed\' sheet');
      }
    } else {
      throw Error('\'Interest expressed\' sheet not specified');
    }
  }
}

/**
 * Utility to derive the required data for registering interest.
 * Called from the registerInterest() function
 */
function getRowOfInterest(sheet) {
  var result = {};
  var row = sheet.getActiveRange().getRow(); // Get the currently-selected row index
  var fullRange = sheet.getRange(row, 1, 1, sheet.getLastColumn()); // Get the entire row of data
  //var fullRange = sheet.getRange(row, 1, 1, 9);
  Logger.log(fullRange.getValues())
  var data = fullRange.getValues();
  if(data[0] && data[0].length > 0) {
    for(var n = 0; n < data[0].length; n++) {
      // Populate specific attributes in the 'result' object - tailor this as you see fit
      if(n==0) result.subject = data[0][n];
      if(n==6) result.what = data[0][n] + ' ';
      //if(n==5 || n==7) result.what += data[0][n] + ' ';
      if(n==7) result.location = data[0][n];
      if(n==11) result.industry = data[0][n];
      if(n==12) result.capabilities = data[0][n];
    }

    result.what += '(' + sheet.getName() + ')';
    result.industry;
    result.capabilities;
    return result;
  }
}

function getSomeRange(){

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var row = sheet.getActiveRange().getRow(); // Get the currently-selected row index

  var myRange = sheet.getRange(row, 1, 1, sheet.getLastColumn());

  //Logger.log("Number of rows in range is "+myRange.getNumRows()+ " Number of columns in range is "+ myRange.getNumColumns());

}
/**
 * Utility to pull specified data from a config sheet. This assumes that a sheet called 'Config'
 * is populated thus:
 *    Column contains a load of 'key' and column 2 contains the corresponding 'values'
 * Called from registerInterest() function
 */
function getConfigValue(key) {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Config');
  var result;

  if(sheet) {
    // Scan column 1 for key and return value in column 2
    var data = sheet.getDataRange().getValues();
    for(var n = 0; n < data.length; ++n) {
      if(data[n][0].toString().match(key)) result = data[n][1];
    }
  }

  return result;
}

function hideExpiredEvents() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Events');
  var exsh=ss.getSheetByName('Expired Events');
  var sr=2;
  var rg=sh.getRange(sr,1,sh.getLastRow()-sr+1,sh.getLastColumn());
  var vA=rg.getValues();
  Logger.log(vA);
  var dt=new Date();
  var  d=0;//deleted row counter
  var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate(0)).valueOf();
  for(var i=0;i<vA.length;i++) {
    if(new Date(vA[i][3]).valueOf()<today) {
      exsh.appendRow(vA[i]);//move to bottom of expired events
      sh.deleteRow(i+sr-d++);//increment deleted row counter
    }
  }
}


问:
Load local files into iframe in Electron app
I'm building an app with Electron that lets you preview HTML5 banner ads stored locally on your machine.

So far, I have made it possible to select a directory containing all the files.

Once selected, the iframe's src is updated to that directory.

```<code>ipcRenderer.on('selected-directory', (event, data) => {
   // update preview
   const previewer = document.getElementById('preview-section-iframe')
   previewer.src = data.filePaths + '\\html\\'
}
</code>```

However, the banner doesn't load in and the html looks like this:

```<code><iframe id="preview-section-iframe" title="Banner preview" width="300" height="600" src="G:\BANNERS\300x600\html\">
</iframe>
</code>```

However, when hovering over the src in the dev tools, the src reads:

file:///G:/_projects/_dev/_electron_apps/test/electron-quick-start/G:\BANNERS\300x600\html\
```

It seems to be looking in the app files for the source. Is there a way to stop this?

Body:
I'm building an app with Electron that lets you preview HTML5 banner ads stored locally on your machine.

So far, I have made it possible to select a directory containing all the files.

Once selected, the iframe's src is updated to that directory.

ipcRenderer.on('selected-directory', (event, data) => {
   // update preview
   const previewer = document.getElementById('preview-section-iframe')
   previewer.src = data.filePaths + '\\html\\'
}

However, the banner doesn't load in and the html looks like this:

However, when hovering over the src in the dev tools, the src reads:

file:///G:/_projects/_dev/_electron_apps/test/electron-quick-start/G:\BANNERS\300x600\html\

It seems to be looking in the app files for the source. Is there a way to stop this?

Body:
Your iframe is expecting one path to a file, you're giving him reference to one folder.

Try something more like this
<iframe id="preview-section-iframe" title="Banner preview" width="300" height="600" src="G:\BANNERS\300x600\html\yourfile.extention">

</iframe>


问:
In what order are ON DELETE CASCADE constraints processed?
Here is an example of what I've got going on:

```<code>CREATE TABLE Parent (id BIGINT NOT NULL,
  PRIMARY KEY (id)) ENGINE=InnoDB;

CREATE TABLE Child (id BIGINT NOT NULL,
  parentid BIGINT NOT NULL,
  PRIMARY KEY (id),
  KEY (parentid),
  CONSTRAINT fk_parent FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE) ENGINE=InnoDB;

CREATE TABLE Uncle (id BIGINT NOT NULL,
  parentid BIGINT NOT NULL,
  childid BIGINT NOT NULL,
  PRIMARY KEY (id),
  KEY (parentid),
  KEY (childid),
  CONSTRAINT fk_parent_u FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE,
  CONSTRAINT fk_child FOREIGN KEY (childid) REFERENCES Child (id)) ENGINE=InnoDB;
</code>```

Notice there is no ON DELETE CASCADE for the Uncle-Child relationship; i.e. deleting a Child does not delete its Uncle(s) and vice-versa.

When I have a Parent and an Uncle with the same Child, and I delete the Parent, it seems like InnoDB should be able to just "figure it out" and let the cascade ripple through the whole family (i.e. deleting the Parent deletes the Uncle and the Child as well).  However, instead, I get the following:

```<code>  ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cascade_test/uncle`, CONSTRAINT `fk_child` FOREIGN KEY (`childid`) REFERENCES `child` (`id`))
</code>```

InnoDB is trying to cascade-delete the Child before the Uncle(s) that refer to it.

Am I missing something?  Is this supposed to fail for some reason I don't understand?  Or is there some trick to making it work (or is it a bug in MySQL)?

答:
the design is all wrong. You should have single table, with parent child relationship (literrally).
Then you can figure out uncles (and aunts) with a query

select id from persons where -find all children of the grandparents

parent id in (

    select parentid from persons   --find the grandparents

    where id in (

        select parentid from persons     --find the parents

        where id=THECHILD)
    )

minus --and take out the child's parents

select parentid from persons

where id=THECHILD

OwnerDisplayName: Matt

ContentLicense: CC BY-SA 2.5

Body:
Here is an example of what I've got going on:

CREATE TABLE Parent (id BIGINT NOT NULL,
  PRIMARY KEY (id)) ENGINE=InnoDB;

CREATE TABLE Child (id BIGINT NOT NULL,
  parentid BIGINT NOT NULL,
  PRIMARY KEY (id),
  KEY (parentid),
  CONSTRAINT fk_parent FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE) ENGINE=InnoDB;

CREATE TABLE Uncle (id BIGINT NOT NULL,
  parentid BIGINT NOT NULL,
  childid BIGINT NOT NULL,
  PRIMARY KEY (id),
  KEY (parentid),
  KEY (childid),
  CONSTRAINT fk_parent_u FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE,
  CONSTRAINT fk_child FOREIGN KEY (childid) REFERENCES Child (id)) ENGINE=InnoDB;

Notice there is no ON DELETE CASCADE for the Uncle-Child relationship; i.e. deleting a Child does not delete its Uncle(s) and vice-versa.

When I have a Parent and an Uncle with the same Child, and I delete the Parent, it seems like InnoDB should be able to just "figure it out" and let the cascade ripple through the whole family (i.e. deleting the Parent deletes the Uncle and the Child as well).  However, instead, I get the following:

  ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cascade_test/uncle`, CONSTRAINT `fk_child` FOREIGN KEY (`childid`) REFERENCES `child` (`id`))

InnoDB is trying to cascade-delete the Child before the Uncle(s) that refer to it.

Am I missing something?  Is this supposed to fail for some reason I don't understand?  Or is there some trick to making it work (or is it a bug in MySQL)?

LastEditorDisplayName: Matt Solnit

OwnerDisplayName: Tony BenBrahim


问:
Error in xml layout, Can't convert to dimension: 15
Within my application I have an error in the graphical layout which shows up as:

```<code>error!
UnsupportedOperationException: Can't convert to dimension: 15
Exception details are logged in Window > Show View > Error LogThe following classes could not be found:
- TextView
</code>```

When I run the application this works, but it shows the error in the graphical layout, does anyone know the cause of this.

It occurs when I put android:layout_marginTop="-3dip" , if I dont use - then this doesn't show.

Thanks

答:
I doubt you still need help with this problem; however, I ran into a similar message and thought I would share to hopefully help anyone else that might run into this error message.

I found that the error was only occurring in the "2.7in QVGA slider" device configuration.  I also found that if I changed the negative value to a different number I no longer got the error message.

So, I ended up using -2 instead.

I am going to guess the error is caused by some of the scaling calculations in the graphical renderer.  But it's not worth researching to find out at this point.

Body:
Within my application I have an error in the graphical layout which shows up as:

error!
UnsupportedOperationException: Can't convert to dimension: 15
Exception details are logged in Window > Show View > Error LogThe following classes could not be found:
- TextView

When I run the application this works, but it shows the error in the graphical layout, does anyone know the cause of this.

It occurs when I put android:layout_marginTop="-3dip" , if I dont use - then this doesn't show.

Thanks


问:
Parent to child communication without event
I have string parameter in child component that I need to show in my parent component.
It should be done when the page is loading. So, not on click or any other event.

How do you manage to do this?

So far I didn't find any answer that would fit my solution.

答:
You can use ViewChild to access children data in the parent component.

Demo : Stackblitz

```<code>import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
  secretString: string = "Hi there!";
}

</code>```

Child component :

Place your child component in the parent and tag it:

```<code><hello #cmp></hello>
</code>```

Use ViewChild to access the data inside you component

```<code>@ViewChild('cmp', {static: true}) hi;
</code>```

```<code><p>
  This is comming from your child: {{hi.secretString}}
</p>
</code>```

Body:
You can use ViewChild to access children data in the parent component.

Demo : Stackblitz

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
  secretString: string = "Hi there!";
}

Child component :

Place your child component in the parent and tag it:

<hello #cmp></hello>

Use ViewChild to access the data inside you component

@ViewChild('cmp', {static: true}) hi;

<p>
  This is comming from your child: {{hi.secretString}}
</p>


问:
Meaning of a linq statement
I saw this code and trying to understand the ling. feater.groupId = 30

```<code>    var myData = await _source.GetDataByIdNumber(staffId);

    if(!myData.select(x=>x.Id).contains(feater.groupId))
    {
      status.IsValid = false;
    }
</code>```

How do I interprete this line in sql or english?

```<code>    if(!myData.select(x=>x.Id).contains(feater.groupId))
</code>```

答:
"If" check is satisfied if none of the myData entities have an Id value of 30

Assuming standard C# Linq operators as per comments!

```<code> if(!myData.Select(x=>x.Id).Contains(feater.groupEntityId));
</code>```

Selects the Id property of all entities. Determines if value 30 is contained within the selected sequence.

Direct T-SQL translation is:

```<code> SELECT CASE
    WHEN 30 IN (
        SELECT Id
        FROM <YourTable>
    )
    THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
    END
</code>```

So, if the supplied value is equal to any of the Ids returned by the select sub-query, return true, else return false.

Title: Meaning of a linq statement

Body:
I saw this code and trying to understand the ling. feater.groupId = 30

    var myData = await _source.GetDataByIdNumber(staffId);

    if(!myData.select(x=>x.Id).contains(feater.groupId))
    {
      status.IsValid = false;
    }

How do I interprete this line in sql or english?

    if(!myData.select(x=>x.Id).contains(feater.groupId))

Body:
"If" check is satisfied if none of the myData entities have an Id value of 30

Assuming standard C# Linq operators as per comments!

 if(!myData.Select(x=>x.Id).Contains(feater.groupEntityId));

Selects the Id property of all entities. Determines if value 30 is contained within the selected sequence.

Direct T-SQL translation is:

 SELECT CASE
    WHEN 30 IN (
        SELECT Id
        FROM <YourTable>
    )
    THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
    END

So, if the supplied value is equal to any of the Ids returned by the select sub-query, return true, else return false.


问:
How to lock my firefox extension on mobile devices?
How can I lock my firefox extension on mobile devices?
I don't want to support them. How can I lock this? Somewhere in manifest.json?</p>

答: Okay, you can do it on addons.mozilla.org when adding a plugin ;)</p>


问:
iterate array of object and save values
I have this objects in Javascript:

```<code>products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}
</code>```

I want to group the articles_ids in the same family.
I want get this result:

```<code>grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}
</code>```

I try with forEach and filter methods, but I dont know how to make this with perform mode.

答:
const products = [{family : 'mugs', name :'black mug' , article_id : 1728}, {family : 'tees', name :'red t-shirt' , article_id : 1332 }, {family : 'mugs', name :'tea white mug' , article_id : 2748}, {family : 'tees', name :'green woman t-shirt' , article_id : 1332}];

const grouped_products = products.reduce((acc, {family, article_id}) => {
    const i = acc.findIndex(p => p.family === family);
    if(i !== -1) {
      return [
        ...acc.slice(0, i),
        {...acc[i], article_id: (acc[i].article_id + ',' + article_id)},
        ...acc.slice(i + 1, acc.length)
      ];
    }
    return [...acc, {family, article_id}];
}, []);

console.log(grouped_products);```

Title: iterate array of object and save values

Body:
I have this objects in Javascript:

products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}

I want to group the articles_ids in the same family.
I want get this result:

grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}

I try with forEach and filter methods, but I dont know how to make this with perform mode.