问:
Generate multiple similar functions with C preprocessor
I want to generate multiple similar functions replacing just one word across the function.

As an example, for each of the below:

```<code>OBJECT = customer
OBJECT = account
</code>```

use the function template:

```<code>void add_OBJECT_to_array(void* item_ptr, int pos)
{
    mtx_lock(&OBJECT_array_mtx);
    OBJECT_array[pos] = *(OBJECT_t*)item_ptr;
    mtx_unlock(&OBJECT_array_mtx);
    return;
}
</code>```

So that I can call

```<code>add_order_to_array(ord, 1);
add_customer_to_array(cust, 1);
</code>```

Is this possible?

答:
Totally possible. You just need to know about the preprocessor concatenation operator ##. The following code will generate two functions add_order_to_array and add_customer_to_array.

```<code>#define GENERATE_FUNC(OBJECT) \
    void add_ ## OBJECT ## _to_array(void* item_ptr, int pos)\
    {                                                        \
        mtx_lock(&OBJECT ## _array_mtx);                     \
        OBJECT ## _array[pos] = *(OBJECT ## _t*)item_ptr;    \
        mtx_unlock(&OBJECT ## _array_mtx);                   \
        return;                                              \
    }

GENERATE_FUNC(order)
GENERATE_FUNC(customer)
</code>```

The preprocessor output will be (unfortunately it does not respect formatting):

```<code>void add_order_to_array(void* item_ptr, int pos) { mtx_lock(&order_array_mtx); order_array[pos] = *(order_t*)item_ptr; mtx_unlock(&order_array_mtx); return; }
void add_customer_to_array(void* item_ptr, int pos) { mtx_lock(&customer_array_mtx); customer_array[pos] = *(customer_t*)item_ptr; mtx_unlock(&customer_array_mtx); return; }
</code>```

Body:
I want to generate multiple similar functions replacing just one word across the function.

As an example, for each of the below:

OBJECT = customer
OBJECT = account

use the function template:

void add_OBJECT_to_array(void* item_ptr, int pos)
{
    mtx_lock(&OBJECT_array_mtx);
    OBJECT_array[pos] = *(OBJECT_t*)item_ptr;
    mtx_unlock(&OBJECT_array_mtx);
    return;
}

So that I can call

add_order_to_array(ord, 1);
add_customer_to_array(cust, 1);

Is this possible?

Body:
Totally possible. You just need to know about the preprocessor concatenation operator ##. The following code will generate two functions add_order_to_array and add_customer_to_array.

#define GENERATE_FUNC(OBJECT) \
    void add_ ## OBJECT ## _to_array(void* item_ptr, int pos)\
    {                                                        \
        mtx_lock(&OBJECT ## _array_mtx);                     \
        OBJECT ## _array[pos] = *(OBJECT ## _t*)item_ptr;    \
        mtx_unlock(&OBJECT ## _array_mtx);                   \
        return;                                              \
    }

GENERATE_FUNC(order)
GENERATE_FUNC(customer)

The preprocessor output will be (unfortunately it does not respect formatting):

void add_order_to_array(void* item_ptr, int pos) { mtx_lock(&order_array_mtx); order_array[pos] = *(order_t*)item_ptr; mtx_unlock(&order_array_mtx); return; }
void add_customer_to_array(void* item_ptr, int pos) { mtx_lock(&customer_array_mtx); customer_array[pos] = *(customer_t*)item_ptr; mtx_unlock(&customer_array_mtx); return; }


来源: stackexchange

问:
Is there a way to add a set of 2D polygon features from GeoJSON into a 3D layer in a SceneView in ArcGIS JS API 4.11?
I need to load a set of 2D polygon features into a SceneView in ArgGIS JS API 4.11 from one of the following file types: GeoJSON, KML, or ShapeFile.

I currently can get the data as either geojson, KML, or ShapeFile.  I was able to use a GeoJSONLayer to get it into my SceneView, and the actual layer renders using a SimpleRenderer with simple-fill. However, I need to project these polygons into 3D, probably by using PolygonSymbol3D and ExtrudeSymbol3DLayer in the renderer.  The problem is that GeoJSONLayer does not support ExtrudeSymbol3DLayer as of ArcGIS API 4.11. So I guess I need to find a different way to load the features in that would support the use of ExtrudeSymbol3DLayer.

I wanted to be able to use KMLLayer, but KMLLayer support for SceneView is also not available for ArcGIS API 4.11.

Is there any way to get a set of 2D polygon features defined as GeoJSON to be a 3D polygon layer in ArcGIS JS API 4.11?

Here's my current layer implementation for a 2D layer in a SceneView:

```<code>
let layer = new GeoJSONLayer({
        title: "My Layer",
        url: "http://localhost/data/layer.geojson",
        renderer: {
            type: "simple",
            symbolLayers: [{
                type: "simple-fill",
                material: { color: "orange" }
            }]
        }
        minScale: 0,
        opacity: 0.40,
        geometryType: "polygon"
    });
</code>```

And here's an idea of what my GeoJSON looks like:

```<code>{
  "type": "FeatureCollection",
  "features": [
    {
      "type":"Feature",
      "properties":{
        "name":"Feature 1",
        ...
      },
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [[[...]]]
      }
    },
    ...
  ],
}
</code>```

答:
You can use the ExtrudeSymbol3DLayer with a GeoJSONLayer. Use a renderer that looks something like this:

```<code>var renderer = {
  type: "simple", // autocasts as new SimpleRenderer()
  symbol: {
    type: "polygon-3d", // autocasts as new PolygonSymbol3D()
    symbolLayers: [
      {
        type: "extrude", // autocasts as new ExtrudeSymbol3DLayer()
        material: { color: "red" },
        edges: {
          type: "solid", // autocasts as new SolidEdges3D()
          color: [50, 50, 50, 0.5]
        }
      }
    ]
  },
  label: "Population Density per County",

  // these visual variables are the key to "Extruding" the polygons
  visualVariables: [
    {
      type: "size",
      axis: "height",

      field: "pop_2000",
      normalizationField: "sq_miles",
    }
  ]
};
</code>```

Full demo here.

ContentLicense: CC BY-SA 4.0

Body:
I need to load a set of 2D polygon features into a SceneView in ArgGIS JS API 4.11 from one of the following file types: GeoJSON, KML, or ShapeFile.

I currently can get the data as either geojson, KML, or ShapeFile.  I was able to use a GeoJSONLayer to get it into my SceneView, and the actual layer renders using a SimpleRenderer with simple-fill. However, I need to project these polygons into 3D, probably by using PolygonSymbol3D and ExtrudeSymbol3DLayer in the renderer.  The problem is that GeoJSONLayer does not support ExtrudeSymbol3DLayer as of ArcGIS API 4.11. So I guess I need to find a different way to load the features in that would support the use of ExtrudeSymbol3DLayer.

I wanted to be able to use KMLLayer, but KMLLayer support for SceneView is also not available for ArcGIS API 4.11.

Is there any way to get a set of 2D polygon features defined as GeoJSON to be a 3D polygon layer in ArcGIS JS API 4.11?

Here's my current layer implementation for a 2D layer in a SceneView:

let layer = new GeoJSONLayer({
        title: "My Layer",
        url: "http://localhost/data/layer.geojson",
        renderer: {
            type: "simple",
            symbolLayers: [{
                type: "simple-fill",
                material: { color: "orange" }
            }]
        }
        minScale: 0,
        opacity: 0.40,
        geometryType: "polygon"
    });

And here's an idea of what my GeoJSON looks like:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type":"Feature",
      "properties":{
        "name":"Feature 1",
        ...
      },
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [[[...]]]
      }
    },
    ...
  ],
}

Body:
You can use the ExtrudeSymbol3DLayer with a GeoJSONLayer. Use a renderer that looks something like this:

var renderer = {
  type: "simple", // autocasts as new SimpleRenderer()
  symbol: {
    type: "polygon-3d", // autocasts as new PolygonSymbol3D()
    symbolLayers: [
      {
        type: "extrude", // autocasts as new ExtrudeSymbol3DLayer()
        material: { color: "red" },
        edges: {
          type: "solid", // autocasts as new SolidEdges3D()
          color: [50, 50, 50, 0.5]
        }
      }
    ]
  },
  label: "Population Density per County",

  // these visual variables are the key to "Extruding" the polygons
  visualVariables: [
    {
      type: "size",
      axis: "height",

      field: "pop_2000",
      normalizationField: "sq_miles",
    }
  ]
};

Full demo here.


问:
JS: delete first element from array by value
I have an array:

```<code>arr = [50, 40, 50, 50];
</code>```

I need to delete first element, that equal 50 and dont touch another.
This code return only [40].

```<code>arr = arr.filter(function(e) {return e !== 50}) // [40]
</code>```

But I need

```<code>arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]
</code>```

I would be grateful for any help.

答:
findIndex() returns the index of the first occurrence of the function provided.
After that, you can just delete the element using splice().   </p>

```<code>let arr = [50, 40, 50, 50];
arr.splice(arr.findIndex(function(e) {return e === 50}), 1);
console.log(arr);
</code>```

Body:
I have an array:

arr = [50, 40, 50, 50];

I need to delete first element, that equal 50 and dont touch another.
This code return only [40].

arr = arr.filter(function(e) {return e !== 50}) // [40]

But I need

arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]

I would be grateful for any help.

Body:
findIndex() returns the index of the first occurrence of the function provided.
After that, you can just delete the element using splice().

let arr = [50, 40, 50, 50];
arr.splice(arr.findIndex(function(e) {return e === 50}), 1);
console.log(arr);


问:
How can I prevent xamarin form ListView items overlapping?
I am currently working on a Xamarin project which displays some content requesting from an API. The requested content is a list of objects and they will be displayed in a list view. API call is working properly and provide responds as expected. When I display the respond in a list view it looks little messy.

This is my Xamarin form page code (Some contents are hard coded in order to make the UI consistent before further development):

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:helper="clr-namespace:WinningQuotes.Helper;assembly=WinningQuotes"
             x:Class="WinningQuotes.Views.QuotesPage"
             Title="Quotes">
    <ContentPage.Content>
        <StackLayout BackgroundColor="LightGray" Padding="0, 0, 0, 10">
            <ListView x:Name="ListQuote" ItemTapped="ListQuote_OnItemTapped" SeparatorVisibility="None" HasUnevenRows="True">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout BackgroundColor="LightGray" Padding="10, 10, 10, 0">
                                <Grid RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.25}"
                                      RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.75}"
                                      BackgroundColor="#FFFFFF" ColumnSpacing="0" RowSpacing="0">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto" />
                                        <RowDefinition Height="Auto" />
                                    </Grid.RowDefinitions>

                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>

                                    <StackLayout Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" BackgroundColor="Brown" Padding="10">
                                        <Label Text="Author" TextColor="#FFFFFF" FontSize="18" />
                                    </StackLayout>

                                    <StackLayout Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="3" Padding="10, 5, 10, 5" Orientation="Horizontal">
                                        <Image Source="{helper:EmbededImage WinningQuotes.Resources.Images.Timeline.png}" Aspect="AspectFill" />

                                        <StackLayout Margin="10, 0, 0, 0" HorizontalOptions="StartAndExpand">
                                            <Label Text="{Binding quote_text}" TextColor="Brown" FontSize="18" />
                                        </StackLayout>
                                    </StackLayout>

                                    <StackLayout Grid.Row="1" Grid.Column="1" Padding="10, 5, 5, 5">
                                        <Label Text="AUTHOR HITS" FontSize="10" TextColor="DarkGray" VerticalOptions="End" />

                                        <Label Text="24" FontSize="18" TextColor="DarkGray" VerticalOptions="End" />
                                    </StackLayout>

                                    <StackLayout Grid.Row="1" Grid.Column="2" Padding="5">
                                        <Label Text="QUOTES HITS" FontSize="10" TextColor="DarkGray" VerticalOptions="End" />

                                        <Label Text="120" FontSize="18" TextColor="DarkGray" VerticalOptions="End" />
                                    </StackLayout>

                                    <StackLayout Grid.Row="1" Grid.Column="3" Padding="5, 5, 10, 5">
                                        <Button Text="Quotes" VerticalOptions="FillAndExpand" HorizontalOptions="EndAndExpand" FontSize="10" FontAttributes="None" />
                                    </StackLayout>
                                </Grid>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
</code>```

When I run this on android emulator or real android device, it looks like this:

ListView element contents are overlapping and some unnecessary space below the brown box etc. How can I make this page look consistent?

答:
This can somethings happen if you haven't defined a RowHeight or set HasUnevenRows

<ListView RowHeight="125">

<ListView HasUnevenRows="true">

Body:
I am currently working on a Xamarin project which displays some content requesting from an API. The requested content is a list of objects and they will be displayed in a list view. API call is working properly and provide responds as expected. When I display the respond in a list view it looks little messy.

This is my Xamarin form page code (Some contents are hard coded in order to make the UI consistent before further development):

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:helper="clr-namespace:WinningQuotes.Helper;assembly=WinningQuotes"
             x:Class="WinningQuotes.Views.QuotesPage"
             Title="Quotes">
    <ContentPage.Content>
        <StackLayout BackgroundColor="LightGray" Padding="0, 0, 0, 10">
            <ListView x:Name="ListQuote" ItemTapped="ListQuote_OnItemTapped" SeparatorVisibility="None" HasUnevenRows="True">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout BackgroundColor="LightGray" Padding="10, 10, 10, 0">
                                <Grid RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.25}"
                                      RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=0.75}"
                                      BackgroundColor="#FFFFFF" ColumnSpacing="0" RowSpacing="0">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto" />
                                        <RowDefinition Height="Auto" />
                                    </Grid.RowDefinitions>

                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>

                                    <StackLayout Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" BackgroundColor="Brown" Padding="10">

                                    </StackLayout>

                                    <StackLayout Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="3" Padding="10, 5, 10, 5" Orientation="Horizontal">
                                        <Image Source="{helper:EmbededImage WinningQuotes.Resources.Images.Timeline.png}" Aspect="AspectFill" />

                                        <StackLayout Margin="10, 0, 0, 0" HorizontalOptions="StartAndExpand">

                                        </StackLayout>
                                    </StackLayout>

                                    <StackLayout Grid.Row="1" Grid.Column="1" Padding="10, 5, 5, 5">

                                    </StackLayout>

                                    <StackLayout Grid.Row="1" Grid.Column="2" Padding="5">

                                    </StackLayout>

                                    <StackLayout Grid.Row="1" Grid.Column="3" Padding="5, 5, 10, 5">
                                        <Button Text="Quotes" VerticalOptions="FillAndExpand" HorizontalOptions="EndAndExpand" FontSize="10" FontAttributes="None" />
                                    </StackLayout>
                                </Grid>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

When I run this on android emulator or real android device, it looks like this:

ListView element contents are overlapping and some unnecessary space below the brown box etc. How can I make this page look consistent?


问:
Middleware to Vuex state not updating state?
I am trying to get my firestore data that I am getting to be stored in my state but it does not show up in my Vue dev tools in the state.

When I console.log() the data I am getting through the store action I can see I am getting the right data but it will not update the state.

I am using middle-ware on my home page and another page to dispatch my action in order to get the required data.

I have also used a conditional statement within the middle-ware below to try to only dispatch action when my other state variables are not null because the firestore query requires state.user

```<code>//this is check-auth middleware
 export default function(context) {
 // in initAuth we are forwarding it the req
  context.store.dispatch('initAuth', context.req)
  console.log('WE ARE GRABBING USER INFO')
  context.store.dispatch('grabUserInfo', context.req)
  console.log('There is already user info there')
  // context.store.dispatch('currentUser')
   }
</code>```

We are  dispatching grabUserInfo to run a action that has a firestore query in it.

```<code>  grabUserInfo(vuexContext, context) {
     let userInfo = []
     var userRef = db.collection('users')
      var query = userRef
        .where('user_id', '==', vuexContext.state.user)
        .get()
        .then(querySnapshot => {
          querySnapshot.forEach(doc => {
          console.log(doc.data())
          userInfo.push(doc.data())
          })
        })
      vuexContext.commit('setUserInfoSub', userInfo)
    }
</code>```

my

```<code>   console.log(doc.data()) is showing
</code>```

subscribers: ["noFace2"]
subscriptions: ["noFace3"]
user_id: "VbomJvANYDNe3Bek0suySs1L8oy1"
username: "noFace1"

my info should be going through a mutation and commiting to state, but it does not show up in my state vue dev tools.

```<code> setUserInfoSub(state, payload) {
    state.userInfoSub = payload
  }
</code>```

I don't understand how the data is not ending up in my state. Here is my State and mutations.

```<code>  const createStore = () => {
   return new Vuex.Store({
    state: {
     loadedCards: [],
     user: null,
     username: null,
     userInfoSub: [],
     token: null
   },
    mutations: {
    setCards(state, cards) {
    state.loadedCards = cards
    },
    setUser(state, payload) {
    state.user = payload
    },
     setUsername(state, payload) {
     state.username = payload
    },
    setUserInfoSub(state, payload) {
    state.userInfoSub = payload
    },
    setToken(state, token) {
    state.token = token
  }
</code>```

答:
Change your mutation to this:

```<code> setUserInfoSub(state, payload) {
    Vue.set(state, 'userInfoSub', payload);
    }
</code>```

This will allow Vue's reactivity system to kick back in for the state variable reassignment.

Per @Alexander's comment, you should also move the commit() inside then() given the async nature of the Firebase query.

Body:
I am trying to get my firestore data that I am getting to be stored in my state but it does not show up in my Vue dev tools in the state.

When I console.log() the data I am getting through the store action I can see I am getting the right data but it will not update the state.

I am using middle-ware on my home page and another page to dispatch my action in order to get the required data.

I have also used a conditional statement within the middle-ware below to try to only dispatch action when my other state variables are not null because the firestore query requires state.user

//this is check-auth middleware
 export default function(context) {
 // in initAuth we are forwarding it the req
  context.store.dispatch('initAuth', context.req)
  console.log('WE ARE GRABBING USER INFO')
  context.store.dispatch('grabUserInfo', context.req)
  console.log('There is already user info there')
  // context.store.dispatch('currentUser')
   }

We are  dispatching grabUserInfo to run a action that has a firestore query in it.

  grabUserInfo(vuexContext, context) {
     let userInfo = []
     var userRef = db.collection('users')
      var query = userRef
        .where('user_id', '==', vuexContext.state.user)
        .get()
        .then(querySnapshot => {
          querySnapshot.forEach(doc => {
          console.log(doc.data())
          userInfo.push(doc.data())
          })
        })
      vuexContext.commit('setUserInfoSub', userInfo)
    }

my

   console.log(doc.data()) is showing

subscribers: ["noFace2"]
subscriptions: ["noFace3"]
user_id: "VbomJvANYDNe3Bek0suySs1L8oy1"
username: "noFace1"

my info should be going through a mutation and commiting to state, but it does not show up in my state vue dev tools.

 setUserInfoSub(state, payload) {
    state.userInfoSub = payload
  }

I don't understand how the data is not ending up in my state. Here is my State and mutations.

  const createStore = () => {
   return new Vuex.Store({
    state: {
     loadedCards: [],
     user: null,
     username: null,
     userInfoSub: [],
     token: null
   },
    mutations: {
    setCards(state, cards) {
    state.loadedCards = cards
    },
    setUser(state, payload) {
    state.user = payload
    },
     setUsername(state, payload) {
     state.username = payload
    },
    setUserInfoSub(state, payload) {
    state.userInfoSub = payload
    },
    setToken(state, token) {
    state.token = token
  }

Body:
Change your mutation to this:

 setUserInfoSub(state, payload) {
    Vue.set(state, 'userInfoSub', payload);
    }

This will allow Vue's reactivity system to kick back in for the state variable reassignment.

Per @Alexander's comment, you should also move the commit() inside then() given the async nature of the Firebase query.


问:
How to use a foreach loop correctly with $_COOKIE with PHP?
If have 2 errors:

Invalid argument supplied for foreach()...

Use of undefined constant c - assumed 'c' in...

I first am trying to find if the cookie exists.  Then if a duplicate cookie exists in  the array.

I was looking at other examples on here, but they seems to show the same foreach loops.  Is there something I am missing?

```<code>$seo = "perma-link"
$count = 0;
$duplicate = 0;
if (isset($_COOKIE['c'])) {
    foreach($_COOKIE['c'] as $key => $value) {
        if($value === $seo){
            $duplicate = 1;
        }
    }
} else {
    setcookie(c[$count], $seo, time()+3600);
    $duplicate = 1;
}
if($duplicate == 0){
    $count = count($_COOKIE['c']);
    setcookie(c[$count], $seo, time()+3600);
}
</code>```

答:
Invalid argument supplied for foreach()

Your $_COOKIE['c'] is not an array.

Use of undefined constant c

setcookie(c[$count], $seo, time()+3600);
```

What is "c"? The interpreter says about this error.
The first argument of setcookie() is a cookie name. You shold provide a correct string.
The second argument of setcookie() is a value. If you want to iterate this using foreach it should be an array. Check you $seo variable.

Body:
If have 2 errors:

Invalid argument supplied for foreach()...

Use of undefined constant c - assumed 'c' in...

I first am trying to find if the cookie exists.  Then if a duplicate cookie exists in  the array.

I was looking at other examples on here, but they seems to show the same foreach loops.  Is there something I am missing?

$seo = "perma-link"
$count = 0;
$duplicate = 0;
if (isset($_COOKIE['c'])) {
    foreach($_COOKIE['c'] as $key => $value) {
        if($value === $seo){
            $duplicate = 1;
        }
    }
} else {
    setcookie(c[$count], $seo, time()+3600);
    $duplicate = 1;
}
if($duplicate == 0){
    $count = count($_COOKIE['c']);
    setcookie(c[$count], $seo, time()+3600);
}

Body:
Invalid argument supplied for foreach()

Your $_COOKIE['c'] is not an array.

Use of undefined constant c

setcookie(c[$count], $seo, time()+3600);

What is "c"? The interpreter says about this error.
The first argument of setcookie() is a cookie name. You shold provide a correct string.
The second argument of setcookie() is a value. If you want to iterate this using foreach it should be an array. Check you $seo variable.


问:
Specifying an attribute in a generic React component
I am trying to build a generic React select component to show a list of options labeled as whatever is passed to the component. My issue is that I want to be able to specify which attribute to use when printing the records which will not always be the same. For instance, if I pass an array of authors, I would use the full_name attribute to populate the list; however, if I wanted to print a list of books, I would want to use title.

I have an options function that I call to populate the select which looks like this:

```<code>options = () => {
  return this.props.collection.map(o => {
    return (
      <option key={o.id} value={o.id}>/*DISPLAY METHOD HERE*/</option>
    )
  })
}
</code>```

Basically I want to be able to pass in a prop to the component specifying the attribute I want to use (full_name, title, etc) and call that on o (o.full_name, o.title, ...) in the return call. Is this possible?

答:
Im not sure if I fully understood your question but if you try to access an arbitrary method of an object it is the same in JS as accessing an arbitrary attribute.

So you could like with attributes just access the method by string.
For example for your title:

    const Foo = (o, title) => {
      return o[title]();
    }

    Foo({ Fantastic: () => console.log('Four'), }, 'Fantastic');```

"o[title]" would get you the method and "()" invoke it

Body:
I am trying to build a generic React select component to show a list of options labeled as whatever is passed to the component. My issue is that I want to be able to specify which attribute to use when printing the records which will not always be the same. For instance, if I pass an array of authors, I would use the full_name attribute to populate the list; however, if I wanted to print a list of books, I would want to use title.

I have an options function that I call to populate the select which looks like this:

options = () => {
  return this.props.collection.map(o => {
    return (
      <option key={o.id} value={o.id}>/*DISPLAY METHOD HERE*/</option>
    )
  })
}

Basically I want to be able to pass in a prop to the component specifying the attribute I want to use (full_name, title, etc) and call that on o (o.full_name, o.title, ...) in the return call. Is this possible?

Body:
Im not sure if I fully understood your question but if you try to access an arbitrary method of an object it is the same in JS as accessing an arbitrary attribute.

So you could like with attributes just access the method by string.
For example for your title:

    const Foo = (o, title) => {
      return o[title]();
    }

    Foo({ Fantastic: () => console.log('Four'), }, 'Fantastic');

"o[title]" would get you the method and "()" invoke it


问:
How to extract data from json and inject it into chart?
I am making a bar chart component which I import in my app.js. My JSON data contains cricket match information i.e season and runs (i.e runs scored in that season). On Y-axis the height of bar will be sum of all the runs in particular season and on X-axis the labels would be the season.

For below JSON example:

```<code>season 2008 -> runs = 100+200=300
season 2009 -> runs = 300
season 2010 -> runs = 1100
season 2011 -> runs = 100
</code>```

JSON data:

```<code>[
    {
      "season":2008,
      "runs":100
    },
    {
      "season":2008,
      "runs":200
    },
    {
      "season":2009,
      "runs":300
    },
    {
      "season":2010,
      "runs":600
    },
    {
      "season":2010,
      "runs":500
    },
    {
      "season":2011,
      "runs":100
    }
]
</code>```

Chart component:

```<code>import React, { Component } from 'react';
import ChartistGraph from 'react-chartist';

const ChartData = {

  //labels are the season

  labels: [ ],

  series: [
    // runs will be injected here
  ],
   distributeSeries: true
}

const options = {
    width: 720,
    height: 400
}

class Chart extends Component {

  render(){
    return(
      <div>
         <ChartistGraph data={ChartData} type={'Bar'} options={options}/>
      </div>
    )}

}

export default Chart;
</code>```

Instead of hardcoding the data from JSON data how can I inject season as labels and runs as series. I tried using for loop but I was not able to get sum of runs for a particular season. eg: for season 2008 it should be 100+200=300 i.e label=2008 and series element corresponding to it will be 300.

Note: For given JSON data series will be :

series:[300, 300, 1100, 100]

答:
Sharing my take on the task</p>

```<code> <script>
            // in the url variable I use a link to my JSON, so might try you by
            // firstly uploading your JSON at myjson.com
            let url = 'https://api.myjson.com/bins/8x9l7';

            fetch(url).then(res => res.json()).then((out) => {
                // here you might try console.log(out); to check the correctness of
                // displaying your JSON imported via URL
                convertJsonToData(out);
            }).catch(err => { throw err });

            let data = {
                    labels: [],
                    series: [[]]
                };

            function convertJsonToData(jsonData) {
                for (let x in jsonData) {
                    data.labels.push(jsonData[x].transactTime); //transactTime and walletBalance are keys in my JSON, you will have yours
                    data.series[0].push(jsonData[x].walletBalance);
                };
                // here you might try console.log(data); to check the correctness of
                // data display taken from JSON and modified to use in chart
                return data;
            };

             let options = {
                 showPoint: false,
                 lineSmooth: true,
                 fullWidth: true,
                 height: 700,
                 showArea:true,
            };

             new Chartist.Line('.ct-chart', data, options);

          </script>
</code>```

Body:
I am making a bar chart component which I import in my app.js. My JSON data contains cricket match information i.e season and runs (i.e runs scored in that season). On Y-axis the height of bar will be sum of all the runs in particular season and on X-axis the labels would be the season.

For below JSON example:

season 2008 -> runs = 100+200=300
season 2009 -> runs = 300
season 2010 -> runs = 1100
season 2011 -> runs = 100

JSON data:

[
    {
      "season":2008,
      "runs":100
    },
    {
      "season":2008,
      "runs":200
    },
    {
      "season":2009,
      "runs":300
    },
    {
      "season":2010,
      "runs":600
    },
    {
      "season":2010,
      "runs":500
    },
    {
      "season":2011,
      "runs":100
    }
]

Chart component:

import React, { Component } from 'react';
import ChartistGraph from 'react-chartist';

const ChartData = {

  //labels are the season

  labels: [ ],

  series: [
    // runs will be injected here
  ],
   distributeSeries: true
}

const options = {
    width: 720,
    height: 400
}

class Chart extends Component {

  render(){
    return(

         <ChartistGraph data={ChartData} type={'Bar'} options={options}/>

    )}

}

export default Chart;

Instead of hardcoding the data from JSON data how can I inject season as labels and runs as series. I tried using for loop but I was not able to get sum of runs for a particular season. eg: for season 2008 it should be 100+200=300 i.e label=2008 and series element corresponding to it will be 300.

Note: For given JSON data series will be :

series:[300, 300, 1100, 100]

Body:
Sharing my take on the task

 <script>
            // in the url variable I use a link to my JSON, so might try you by
            // firstly uploading your JSON at myjson.com
            let url = 'https://api.myjson.com/bins/8x9l7';

            fetch(url).then(res => res.json()).then((out) => {
                // here you might try console.log(out); to check the correctness of
                // displaying your JSON imported via URL
                convertJsonToData(out);
            }).catch(err => { throw err });

            let data = {
                    labels: [],
                    series: [[]]
                };

            function convertJsonToData(jsonData) {
                for (let x in jsonData) {
                    data.labels.push(jsonData[x].transactTime); //transactTime and walletBalance are keys in my JSON, you will have yours
                    data.series[0].push(jsonData[x].walletBalance);
                };
                // here you might try console.log(data); to check the correctness of
                // data display taken from JSON and modified to use in chart
                return data;
            };

             let options = {
                 showPoint: false,
                 lineSmooth: true,
                 fullWidth: true,
                 height: 700,
                 showArea:true,
            };

             new Chartist.Line('.ct-chart', data, options);

          </script>


问:
php setcookie not working with ajax call
I have a page, test.php, with the following code:

```<code><html>
    <body>
        <form>
            <script type="text/javascript">

                function SendCookies(){

                    if (window.XMLHttpRequest)/* code for IE7+, Firefox, Chrome, Opera, Safari */
                    { xmlhttp=new XMLHttpRequest(); }
                    else /* code for IE6, IE5 */
                    { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }

                    xmlhttp.onreadystatechange=function()
                    {
                        if (xmlhttp.readyState==4 && xmlhttp.status == 200)
                        {
                            alert('done');
                        }
                    }

                    xmlhttp.open("GET", "/web/DEV/Classes/SetCookie.php?time=" + new Date());
                    xmlhttp.send();

                }

            </script>

            <input type="text" id="txtInput" name="txtInput"/>
            <input type="button" id="btnSubmit" name="btnSubmit" value="Submit"  onclick="SendCookies()"/>
            <div id="divTest">
                <?php
                    if (isset($_COOKIE["TestCookie"])) {
                        echo $_COOKIE["TestCookie"];
                    } else {
                        echo "__Results__";
                    }
                ?>
            </div>
        </form>
    </body>
</html>
</code>```

I have a page, SetCookie.php, with the following code:

```<code><?php
    $var = "THIS IS  A  TEST";
    setcookie("TestCookie", $var, time()+60*60*24*30);
?>
</code>```

When test.php's button is clicked, i use XMLHttpRequest to call my SetCookie.php page.  The page executes, becuase if i add an echo to it, i get that in the xmlhttp response.  However, TestCookie does not seem to be getting set.

If in text.php, i do the same command found in SetCookie.php, the cookie is then set accordingly for all browser sessions.

Even after i close / open the browser, the cookie remains unchanged from when i once set it in my test.php page manually.

----EDIT-----

I added:

```<code>if(!setcookie("TestCookie", "A", time()+60*60*24*30, "/")) {
    echo "FAIL";
}
</code>```

to the very top of test.php, however when i reload the page, it never shows the updated cookie... because that cookie was already set without the ,"/" parameter, and cannot be modified later, with the ,"/" parameter.

After clearing the cache and working with the suggested code, i cleared my cookies from the browser and used the added parameter for the set method, i was able to manipulate the cookies from all pages!!! thank you so much!!

答: I think you should look into the path parameter of the setcookie. Set it to "/" , so that it is accessible from across all directories/pages of the site.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a page, test.php, with the following code:

        <form>

            <input type="text" id="txtInput" name="txtInput"/>
            <input type="button" id="btnSubmit" name="btnSubmit" value="Submit"  onclick="SendCookies()"/>

                <?php
                    if (isset($_COOKIE["TestCookie"])) {
                        echo $_COOKIE["TestCookie"];
                    } else {
                        echo "__Results__";
                    }
                ?>

        </form>

I have a page, SetCookie.php, with the following code:

<?php
    $var = "THIS IS  A  TEST";
    setcookie("TestCookie", $var, time()+60*60*24*30);
?>

When test.php's button is clicked, i use XMLHttpRequest to call my SetCookie.php page.  The page executes, becuase if i add an echo to it, i get that in the xmlhttp response.  However, TestCookie does not seem to be getting set.

If in text.php, i do the same command found in SetCookie.php, the cookie is then set accordingly for all browser sessions.

Even after i close / open the browser, the cookie remains unchanged from when i once set it in my test.php page manually.

----EDIT-----

I added:

if(!setcookie("TestCookie", "A", time()+60*60*24*30, "/")) {
    echo "FAIL";
}

to the very top of test.php, however when i reload the page, it never shows the updated cookie... because that cookie was already set without the ,"/" parameter, and cannot be modified later, with the ,"/" parameter.

After clearing the cache and working with the suggested code, i cleared my cookies from the browser and used the added parameter for the set method, i was able to manipulate the cookies from all pages!!! thank you so much!!


问:
sending json web token using ajax to Node API
I'm trying to do an authorisation middleware using jsonwebtoken, cookie-parser to set cookies and jQuery in the client.

For that I'm using a middleware to check authorisations.

here is the middleware

```<code>const jwt = require('jsonwebtoken')

module.exports = (req,res,next)=> {
    try{
        const token = req.headers.authorization.split("=")[1];
        const decodedToken = jwt.verify(token, process.env.JWT_KEY)
        req.userData = decodedToken;
        next();

    } catch(error){
        return res.status(401).json({
            message: "Auth failed"
        })
    }
}
</code>```

In my API I'm creating and sending the token like this:

```<code>
                const token = jwt.sign({
                        email: user[0].email,
                        userId: user[0]._id
                    },

                    process.env.JWT_KEY, {
                        expiresIn: "1h"
                    }
                )

                res.cookie('userToken', token)
                res.render('index', {
                    movies: {}, token:token
                });

</code>```

In the client I'm sending back to the server like this:

```<code>var userToken = document.cookie;
        // console.log(userToken)

        $.ajax({
            url: "/movies/add",
            type: "GET",
            beforeSend: function (xhr, settings) {
                console.log(xhr)
                xhr.setRequestHeader('Authorization', 'Bearer ' + userToken);
            }
        });

</code>```

The movies/add route is receiving the request, because it's printing 'it entered', but it's not redirecting to movies/addMovies. What am I missing?

```<code>    router.get('/add', checkAuth, function (req, res, next) {

        console.log('it entered')

        res.render('movies/addMovies', {
            movies: {}
        })

    });
</code>```

答:
You're requesting the "page" via an AJAX call and returning the HTML (res.render) to the JavaScript.

If you're wanting to navigate to the other screen, you should either use a hyperlink or redirect using JavaScript (location.href).

Body:
I'm trying to do an authorisation middleware using jsonwebtoken, cookie-parser to set cookies and jQuery in the client.

For that I'm using a middleware to check authorisations.

here is the middleware

const jwt = require('jsonwebtoken')

module.exports = (req,res,next)=> {
    try{
        const token = req.headers.authorization.split("=")[1];
        const decodedToken = jwt.verify(token, process.env.JWT_KEY)
        req.userData = decodedToken;
        next();

    } catch(error){
        return res.status(401).json({
            message: "Auth failed"
        })
    }
}

In my API I'm creating and sending the token like this:

                const token = jwt.sign({
                        email: user[0].email,
                        userId: user[0]._id
                    },

                    process.env.JWT_KEY, {
                        expiresIn: "1h"
                    }
                )

                res.cookie('userToken', token)
                res.render('index', {
                    movies: {}, token:token
                });

In the client I'm sending back to the server like this:

var userToken = document.cookie;
        // console.log(userToken)

        $.ajax({
            url: "/movies/add",
            type: "GET",
            beforeSend: function (xhr, settings) {
                console.log(xhr)
                xhr.setRequestHeader('Authorization', 'Bearer ' + userToken);
            }
        });

The movies/add route is receiving the request, because it's printing 'it entered', but it's not redirecting to movies/addMovies. What am I missing?

    router.get('/add', checkAuth, function (req, res, next) {

        console.log('it entered')

        res.render('movies/addMovies', {
            movies: {}
        })

    });


问:
How to pass an account_id through a nested form in Rails
I'm trying to set up a nested form in rails and both the parent and child objects in the form need to have an "Account ID" so that they are both scoped to the current user's account, but I can't figure out how to pass the current user's Account ID for the child object through the nested form. I keep getting a validation error of "Account id must be present" for the nested object.

The parent form is "Product" and I'm trying to nest "Options" into the Product.new form.

I'm trying to do something like this:

```<code>@product.options.account_id = current_user.account.id
</code>```

But it's not working.

Here is the Product model:

```<code>class Product < ApplicationRecord
  belongs_to :account
  has_many :options, dependent: :destroy

  accepts_nested_attributes_for :options, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true, length: { maximum: 120 }
end
</code>```

And options model:

```<code>class Option < ApplicationRecord
  belongs_to :account
  belongs_to :product

  has_many :option_values, dependent: :destroy

  validates :account_id,  presence: true
  validates :name,        presence: true,
                          length: { maximum: 60 }
end
</code>```

Here's how I'm nesting "Options" into the Product form:

```<code><%= form.fields_for :options do |builder| %>
    <fieldset class='form-group'>
      <%= builder.label :name, 'Add option(s)' %>
      <%= builder.text_field :name %>
      <small id="optionHelp" class="form-text text-muted">
        (e.g. "Sizes" or "Color")
      </small>
    </fieldset>
  <% end %>
</code>```

And here is my ProductsController:

```<code>class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]
  before_action :restrict_access

  def index
    @products = Product.where(:account_id => current_user.account.id).all
  end

  def show
  end

  def new
    @product = Product.new
    @product.options.build
  end

  def edit
  end

  def create
    @account = current_user.account
    @product = @account.products.build(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @product.destroy
    respond_to do |format|
      format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
    end
  end

  private
    def set_product
      if Product.find(params[:id]).account_id == current_user.account.id
        @product = Product.find(params[:id])
      else
        redirect_to dashboard_path
      end
    end

    def restrict_access
      if index
        authorize @products
      else
        authorize @product
      end
    end

    def product_params
      params.require(:product).permit(:account_id, :name,
                                      options_attributes: [:id, :account_id, :name ])
    end
end
</code>```

What is the correct way to do this?

答:
The easiest option would be to add a hidden field into both forms:

https://apidock.com/rails/ActionView/Helpers/FormHelper/hidden_field

So in your case, for the options form, something like:

```<code>  <%= form.fields_for :options do |builder| %>
    <fieldset class='form-group'>
      <%= builder.label :name, 'Add option(s)' %>
      <%= builder.hidden_field :account_id, value: current_account.id %>
      <%= builder.text_field :name %>
      <small id="optionHelp" class="form-text text-muted">
        (e.g. "Sizes" or "Color")
      </small>
    </fieldset>
  <% end %>
</code>```

This will give you access to the [:option][:account_id] param, which will match the current user's.

Body:
I'm trying to set up a nested form in rails and both the parent and child objects in the form need to have an "Account ID" so that they are both scoped to the current user's account, but I can't figure out how to pass the current user's Account ID for the child object through the nested form. I keep getting a validation error of "Account id must be present" for the nested object.

The parent form is "Product" and I'm trying to nest "Options" into the Product.new form.

I'm trying to do something like this:

@product.options.account_id = current_user.account.id

But it's not working.

Here is the Product model:

class Product < ApplicationRecord
  belongs_to :account
  has_many :options, dependent: :destroy

  accepts_nested_attributes_for :options, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true, length: { maximum: 120 }
end

And options model:

class Option < ApplicationRecord
  belongs_to :account
  belongs_to :product

  has_many :option_values, dependent: :destroy

  validates :account_id,  presence: true
  validates :name,        presence: true,
                          length: { maximum: 60 }
end

Here's how I'm nesting "Options" into the Product form:

<%= form.fields_for :options do |builder| %>
    <fieldset class='form-group'>
      <%= builder.label :name, 'Add option(s)' %>
      <%= builder.text_field :name %>

        (e.g. "Sizes" or "Color")

    </fieldset>
  <% end %>

And here is my ProductsController:

class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]
  before_action :restrict_access

  def index
    @products = Product.where(:account_id => current_user.account.id).all
  end

  def show
  end

  def new
    @product = Product.new
    @product.options.build
  end

  def edit
  end

  def create
    @account = current_user.account
    @product = @account.products.build(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @product.destroy
    respond_to do |format|
      format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
    end
  end

  private
    def set_product
      if Product.find(params[:id]).account_id == current_user.account.id
        @product = Product.find(params[:id])
      else
        redirect_to dashboard_path
      end
    end

    def restrict_access
      if index
        authorize @products
      else
        authorize @product
      end
    end

    def product_params
      params.require(:product).permit(:account_id, :name,
                                      options_attributes: [:id, :account_id, :name ])
    end
end

What is the correct way to do this?

Body:
The easiest option would be to add a hidden field into both forms:

https://apidock.com/rails/ActionView/Helpers/FormHelper/hidden_field

So in your case, for the options form, something like:

  <%= form.fields_for :options do |builder| %>
    <fieldset class='form-group'>
      <%= builder.label :name, 'Add option(s)' %>
      <%= builder.hidden_field :account_id, value: current_account.id %>
      <%= builder.text_field :name %>
      <small id="optionHelp" class="form-text text-muted">
        (e.g. "Sizes" or "Color")
      </small>
    </fieldset>
  <% end %>

This will give you access to the [:option][:account_id] param, which will match the current user's.


问:
Condition based Foreign Key in Entity Framework Core
I have to create a condition based one to many relationship between classes. I have the following classes.

```<code>public enum Type
{
    Type1,
    Type2
}
public Class Base1
{
    public int Id {get; set;}
    public string Prop {get; set;}
    public List<NProp> NProps {get; set;}
}
public Class Base2
{
    public int Id {get; set;}
    public string Prop {get; set;}
    public List<NProp> NProps {get; set;}
}
public class NProp
{
    public Type Type {get; set;}
    public int BaseId {get; set;} //Foreign Key
    public string NProp {get; set;}
}
</code>```

Now, in class NProp, there is one foreign key baseId which should be a foreign key of Base1 if the Type is Type1 and to that of Base2 if the Type is Type2.
First of all, is this possible? If yes, then how?

答: No it's not possible. You should use two FKs. One for each Base. </p>

Body:
I have to create a condition based one to many relationship between classes. I have the following classes.

public enum Type
{
    Type1,
    Type2
}
public Class Base1
{
    public int Id {get; set;}
    public string Prop {get; set;}
    public List<NProp> NProps {get; set;}
}
public Class Base2
{
    public int Id {get; set;}
    public string Prop {get; set;}
    public List<NProp> NProps {get; set;}
}
public class NProp
{
    public Type Type {get; set;}
    public int BaseId {get; set;} //Foreign Key
    public string NProp {get; set;}
}

Now, in class NProp, there is one foreign key baseId which should be a foreign key of Base1 if the Type is Type1 and to that of Base2 if the Type is Type2.
First of all, is this possible? If yes, then how?


答:
The short answer is yes - d3 can load and draw geojson files. Geojson is a subset of json - d3 paths take geojson objects representing geographic features and convert them to SVG or canvas paths. As geojson is a subset of json, we can use d3.json to load our geojson files. The file extention, whether .json, .geojson, or .geo.json is immaterial.

Your code loads and draws the geojson as expected. The problem instead lies elsewhere.

The issue is that the default Mercator project parameters spread the world over 960 pixels (anticipating a 960x500 pixel map). But, the default svg size is 300 pixels wide by 150 pixels high. Essentially your SVG is clipping your map so that only the top left of the map is visible (essentially Alaska and Northern Canada). Your features are not in Alaska nor Northern Canada - they are in Australia, so they are not visible - you can see this if you inspect your SVG - you'll see that the features are drawn beyond the extent of the SVG bounds (example):

This explains why there are no errors: the file is loaded and the features drawn: just beyond the extent of the SVG.

One solution would be to set the SVG width and height to the extent expected by the default projection parameters: 960x500 (you have width and height variables but you do not use them). This would include your feature, but they would be very small - after all the map is still showing the world - even if your features only cover a small part of it.

Scaling and centering a map is the main challenge now. This part has been answered many times before: you need to set your projection parameters to show the area of interest. The simplest way is to use fitSize, but this only works on v4+:

```<code> projection.fitSize([svgWidth,svgHeight],geojsonObject])
</code>```

As seen here:

```<code>var width = 900;
var height = 500;

var svg = d3.select("body")
  .append("svg")
  .attr("width",width)  // apply width,height to svg
  .attr("height",height);

var projection = d3.geoMercator();
var path = d3.geoPath().projection(projection);

d3.json("geo.json", function(err, geojson) {

      projection.fitSize([width,height],geojson); // adjust the projection to the features
      svg.append("path").attr("d", path(geojson)); // draw the features

})
</code>```

If you wish to remain with v3, this question should have some answers - as well as having more info for v4+.

Title: Can D3 read "Geojson" files?

Body:
I've just downloaded a Geojson file from geojson.io to map the specific area I want in D3.

However, I cannot draw these features despite different approaches.

First, I thought maybe the file format - geojson - is not the correct one so I convert to json but I still cannot draw the features with D3.
Then I converted the file format from json to geo.json, but still cannot show the map on the screen.

Here is an example of my geojson:

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"stroke":"#8080ff","stroke-width":2,"stroke-opacity":1,"fill":"#0080c0","fill-opacity":0.5,"city name":"Melbourne","postcode":3004,"campus":"Southbank Campus","university":"Melbourne University"},"geometry":{"type":"Polygon","coordinates":[[[144.96743202209473,-37.817242738346984],[144.9671745300293,-37.817581756139454],[144.97138023376465,-37.83439508475046],[144.96726036071777,-37.83737769454491],[144.9712085723877,-37.83934343961261],[144.97035026550293,-37.846189246249814],[144.97678756713864,-37.84930692776673],[144.9785041809082,-37.85283110466397],[144.98296737670898,-37.85601627346177],[144.98399734497067,-37.85073017332982],[144.98459815979004,-37.845714804898066],[144.9799633026123,-37.84503702624343],[144.97756004333496,-37.837259070321736],[144.97620820999146,-37.83701758470656],[144.97631549835205,-37.836602397064034],[144.9765408039093,-37.83548392076778],[144.97558057308197,-37.83526361283155],[144.97554302215576,-37.83480181136876],[144.9785041809082,-37.83524242934148],[144.9787616729736,-37.833632466297274],[144.9833106994629,-37.83412393242583],[144.98502731323242,-37.82775156590534],[144.98811721801758,-37.828904055935546],[144.98923301696777,-37.82320922404997],[144.9752426147461,-37.815208598896234],[144.96743202209473,-37.817242738346984]]]}},{"type":"Feature","properties":{"stroke":"#8080ff","stroke-width":2,"stroke-opacity":1,"fill":"#0080c0","fill-opacity":0.5,"city name":"Melbourne","postcode":3000,"campus":"Southbank Campus","university":"Melbourne University"},"geometry":{"type":"Polygon","coordinates":[[[144.9558448791504,-37.82276853421615],[144.967303276062,-37.81910731693811],[144.9671745300293,-37.81737834565081],[144.97481346130368,-37.8151746960972],[144.97112274169922,-37.80768179558675],[144.95957851409912,-37.80608818475805],[144.9600076675415,-37.80496924596681],[144.9584197998047,-37.80154450977393],[144.95713233947754,-37.80168014591059],[144.9574327468872,-37.800595049843196],[144.95661735534668,-37.80079850657008],[144.95571613311765,-37.80608818475805],[144.95532989501953,-37.80849554104369],[144.95635986328122,-37.811886050589756],[144.9512529373169,-37.81324221081575],[144.9558448791504,-37.82276853421615]]]}},{"type":"Feature","properties":{"stroke":"#8080ff","stroke-width":2,"stroke-opacity":1,"fill":"#0080c0","fill-opacity":0.5,"city name":"Southbank","postcode":3006,"campus":"Southbank Campus","university":"Melbourne University"},"geometry":{"type":"Polygon","coordinates":[[[144.96726036071777,-37.81914121793108],[144.9558448791504,-37.82287023210366],[144.9532699584961,-37.82361601233024],[144.94837760925293,-37.82320922404997],[144.94773387908936,-37.82592110356655],[144.94691848754883,-37.827005827470494],[144.94919300079346,-37.83032769523887],[144.9528408050537,-37.828158329147854],[144.95404243469238,-37.83102255682819],[144.95453596115112,-37.83062428330308],[144.95479345321655,-37.83078528775296],[144.9553084373474,-37.8307768138433],[144.95657444000244,-37.83040396085496],[144.96288299560547,-37.82856509014813],[144.96575832366943,-37.831378459010416],[144.97035026550293,-37.830293799384194],[144.96726036071777,-37.81914121793108]]]}},{"type":"Feature","properties":{"stroke":"#8080ff","stroke-width":2,"stroke-opacity":1,"fill":"#0080c0","fill-opacity":0.5,"city name":"Docklands","postcode":3008,"campus":"Southbank Campus","university":"Melbourne University"},"geometry":{"type":"Polygon","coordinates":[[[144.95121002197266,-37.81310659591412],[144.94511604309082,-37.81500518186842],[144.94357109069824,-37.81297098076338],[144.93756294250488,-37.80971614241526],[144.93352890014648,-37.80958052103703],[144.93404388427732,-37.81283536536353],[144.93078231811523,-37.815412015363556],[144.92425918579102,-37.81690371899756],[144.91825103759763,-37.81873440498776],[144.920654296875,-37.82097184843051],[144.9319839477539,-37.822056645079854],[144.933443069458,-37.822192243539966],[144.93696212768555,-37.82585330779315],[144.94717597961423,-37.82605669492651],[144.9477767944336,-37.82287023210366],[144.9529266357422,-37.823412618470364],[144.95550155639648,-37.82273463488917],[144.95121002197266,-37.81310659591412]]]}},{"type":"Feature","properties":{"stroke":"#8080ff","stroke-width":2,"stroke-opacity":1,"fill":"#0080c0","fill-opacity":0.5,"city name":"Seddon","postcode":3011,"campus":"Southbank Campus","university":"Melbourne University"},"geometry":{"type":"Polygon","coordinates":[[[144.89966869354248,-37.81470005527579],[144.90559101104736,-37.81527640444762],[144.9093246459961,-37.80157841883145],[144.91232872009275,-37.799408207766895],[144.9148178100586,-37.800188134708165],[144.91627693176267,-37.79903519631872],[144.91636276245117,-37.797305754993076],[144.9143886566162,-37.79588147879352],[144.9098825454712,-37.79388066346596],[144.90554809570312,-37.79218501483793],[144.90365982055664,-37.79143891711323],[144.9023723602295,-37.790048442159254],[144.90262985229492,-37.78899709006653],[144.8938751220703,-37.78781006166096],[144.89035606384277,-37.78740307610388],[144.89031314849854,-37.78706391976077],[144.8833179473877,-37.78631777032694],[144.88142967224118,-37.79784832917946],[144.8798418045044,-37.7975770425844],[144.87941265106198,-37.80106978133416],[144.8869228363037,-37.801781872849624],[144.88529205322266,-37.8026635004523],[144.88409042358398,-37.809614426404934],[144.88687992095947,-37.8098517635444],[144.88962650299072,-37.81015691017421],[144.8899698257446,-37.80978395301097],[144.89447593688965,-37.81025862543725],[144.89816665649414,-37.81073329481208],[144.89820957183838,-37.81107234249728],[144.90112781524655,-37.81198776347078],[144.89966869354248,-37.81470005527579]]]}},

And here is my javascript:

var width = 900;
var height = 500;

var svg = d3.select("body").append("svg")
var projection = d3.geo.mercator();
var path = d3.geo.path().projection(projection);

d3.json("map.geo.json", function(err, geojson) {
      svg.append("path").attr("d", path(geojson));})

I am using d3v3

The map data should be drawn on the screen when I use D3 but now it cannot show anything and also doesn't have error message on it!

Body:
The short answer is yes - d3 can load and draw geojson files. Geojson is a subset of json - d3 paths take geojson objects representing geographic features and convert them to SVG or canvas paths. As geojson is a subset of json, we can use d3.json to load our geojson files. The file extention, whether .json, .geojson, or .geo.json is immaterial.

Your code loads and draws the geojson as expected. The problem instead lies elsewhere.

The issue is that the default Mercator project parameters spread the world over 960 pixels (anticipating a 960x500 pixel map). But, the default svg size is 300 pixels wide by 150 pixels high. Essentially your SVG is clipping your map so that only the top left of the map is visible (essentially Alaska and Northern Canada). Your features are not in Alaska nor Northern Canada - they are in Australia, so they are not visible - you can see this if you inspect your SVG - you'll see that the features are drawn beyond the extent of the SVG bounds (example):

This explains why there are no errors: the file is loaded and the features drawn: just beyond the extent of the SVG.

One solution would be to set the SVG width and height to the extent expected by the default projection parameters: 960x500 (you have width and height variables but you do not use them). This would include your feature, but they would be very small - after all the map is still showing the world - even if your features only cover a small part of it.

Scaling and centering a map is the main challenge now. This part has been answered many times before: you need to set your projection parameters to show the area of interest. The simplest way is to use fitSize, but this only works on v4+:

 projection.fitSize([svgWidth,svgHeight],geojsonObject])

As seen here:

var width = 900;
var height = 500;

var svg = d3.select("body")
  .append("svg")
  .attr("width",width)  // apply width,height to svg
  .attr("height",height);

var projection = d3.geoMercator();
var path = d3.geoPath().projection(projection);

d3.json("geo.json", function(err, geojson) {

      projection.fitSize([width,height],geojson); // adjust the projection to the features
      svg.append("path").attr("d", path(geojson)); // draw the features

})

If you wish to remain with v3, this question should have some answers - as well as having more info for v4+.


问:
problem while installing app on iphone
H everyone

i have up graded my xcode to xcode 4 & i am trying to install a app through this xcode on to a iphone but i am getting following error & i am unable to launch the app

```<code>warning: Unable to read symbols for /var/mobile/Applications/7A08B9EA-DD46-47B4-8E0C-BF081BDB1F4B/QIA All.app/QIA All (file not found).

dyld: Library not loaded: /System/Library/Frameworks/QuickLook.framework/QuickLook
  Referenced from: /var/mobile/Applications/7A08B9EA-DD46-47B4-8E0C-BF081BDB1F4B/QIA All.app/QIA All

Reason: image not found
</code>```

i have following warning in my app
ld: warning: directory not found for option '-F/Developer/new xcode/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.2.sdk/System/Library/PrivateFrameworks'

is from this warning

how can i fix this?,,,thanx in advance

答: Looks like your app is still trying to link to the 3.1.2 SDK.  You need to change the SDK in the project settings to Base SDK: Latest (iOS 4.3).  Also make sure to clear out any settings in the target for this value so that it inherits it properly.</p>

Title: problem while installing app on iphone

Body:
H everyone

i have up graded my xcode to xcode 4 & i am trying to install a app through this xcode on to a iphone but i am getting following error & i am unable to launch the app

warning: Unable to read symbols for /var/mobile/Applications/7A08B9EA-DD46-47B4-8E0C-BF081BDB1F4B/QIA All.app/QIA All (file not found).

dyld: Library not loaded: /System/Library/Frameworks/QuickLook.framework/QuickLook
  Referenced from: /var/mobile/Applications/7A08B9EA-DD46-47B4-8E0C-BF081BDB1F4B/QIA All.app/QIA All

Reason: image not found

i have following warning in my app
ld: warning: directory not found for option '-F/Developer/new xcode/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.2.sdk/System/Library/PrivateFrameworks'

is from this warning

how can i fix this?,,,thanx in advance


答:
Alternatively, you can pass a hidden_field with form and nested_form as given below: -

```<code><%= form_for @product do |form|%>
  <%= form.fields_for :options do |builder| %>
      <fieldset class='form-group'>
        <%= builder.label :name, 'Add option(s)' %>
        <%= builder.text_field :name %>
        <small id="optionHelp" class="form-text text-muted">
          (e.g. "Sizes" or "Color")
        </small>
        <%=builder.hidden_field :account_id, value: current_user.account.id%>
      </fieldset>
  <% end %>
  <%= form.hidden_field :account_id, value: current_user.account.id%>
<%end%>
</code>```

Other than this you can set account_id at the controller

```<code>  def new
    #@product = Product.new
    @product = current_user.account.products.new
    @product.options.build(account_id: current_user.account.id)
  end
</code>```

Title: How to pass an account_id through a nested form in Rails

Body:
Alternatively, you can pass a hidden_field with form and nested_form as given below: -

<%= form_for @product do |form|%>
  <%= form.fields_for :options do |builder| %>
      <fieldset class='form-group'>
        <%= builder.label :name, 'Add option(s)' %>
        <%= builder.text_field :name %>
        <small id="optionHelp" class="form-text text-muted">
          (e.g. "Sizes" or "Color")
        </small>
        <%=builder.hidden_field :account_id, value: current_user.account.id%>
      </fieldset>
  <% end %>
  <%= form.hidden_field :account_id, value: current_user.account.id%>
<%end%>

Other than this you can set account_id at the controller

  def new
    #@product = Product.new
    @product = current_user.account.products.new
    @product.options.build(account_id: current_user.account.id)
  end


问:
Javafx passwordfield echo displays garbled characters instead of bullet
The echo of passwordfield is displayed properly in the scene builder.

I also tried using netBeans, and the result is the same.

This is coding environment :

```<code>Jdk: 1.8.0.191
intelliJ:2019.1
netBeans: 8.0
</code>```

Main.java :

```<code>public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("test.fxml"));
        primaryStage.setTitle("test");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }

}
</code>```

test.fxml

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

<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <PasswordField layoutX="237.0" layoutY="179.0" promptText="password" />
   </children>
</AnchorPane>
</code>```

hope it show default echo.

答:
I finally get the solution！！！！！！
Just make sure to write the code under jdk11, and it has little to do with file encoding.
setup jdk11 and setup a JavaFX Project for JDK 11 Using Intellij.

bug

no bug

Body:
The echo of passwordfield is displayed properly in the scene builder.

I also tried using netBeans, and the result is the same.

This is coding environment :

Jdk: 1.8.0.191
intelliJ:2019.1
netBeans: 8.0

Main.java :

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("test.fxml"));
        primaryStage.setTitle("test");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }

}

test.fxml

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

<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <PasswordField layoutX="237.0" layoutY="179.0" promptText="password" />
   </children>
</AnchorPane>

hope it show default echo.


问:
How to import React(jsx) file in Rails app?
I have a problem when run ./bin/webpack-dev-server in my Rails app I'm getting an error:

```<code>Failed to compile.

./app/javascript/packs/blob.js
Module build failed: SyntaxError: Unexpected token (5:1)

  3 |
  4 |
> 5 | <!DOCTYPE html>
    |  ^
</code>```

I'm not sure what but I think something should be added to webpack.config.js

答:
Your webpack configuration might be incorrect, it is trying to compile JavaScript from an html file, you need to specify an entry jsx file in your webpack config. I usually put all my jsx files into a frontend folder at project root and use the following webpack.config.js file at root

```<code>const path = require('path');

module.exports = {
  context: __dirname,
  entry: './frontend/ROOT FILE NAME.jsx',
  output: {
    path: path.resolve(__dirname, 'app', 'assets', 'javascripts'),
    filename: 'bundle.      },
  module: {
    rules: [{
      test: /\.jsx?$/,
      exclude: /(node_modules)/,
      use: {
        loader: 'babel-loader',
        query: {
          presets: ['@babel/env', '@babel/react',],
          plugins: ['@babel/plugin-proposal-class-properties']
        }
      },
    }]
  },
  devtool: 'source-map',
  resolve: {
    extensions: [".js", ".jsx"]
  }
};
</code>```

Note that I have Babel with some extensions added, you may want to add more or remove some depending on JS syntax you’re using.

See here on how to set up root file

Body:
I have a problem when run ./bin/webpack-dev-server in my Rails app I'm getting an error:

Failed to compile.

./app/javascript/packs/blob.js
Module build failed: SyntaxError: Unexpected token (5:1)

  3 |
  4 |
> 5 | <!DOCTYPE html>
    |  ^

I'm not sure what but I think something should be added to webpack.config.js

Body:
Your webpack configuration might be incorrect, it is trying to compile JavaScript from an html file, you need to specify an entry jsx file in your webpack config. I usually put all my jsx files into a frontend folder at project root and use the following webpack.config.js file at root

const path = require('path');

module.exports = {
  context: __dirname,
  entry: './frontend/ROOT FILE NAME.jsx',
  output: {
    path: path.resolve(__dirname, 'app', 'assets', 'javascripts'),
    filename: 'bundle.      },
  module: {
    rules: [{
      test: /\.jsx?$/,
      exclude: /(node_modules)/,
      use: {
        loader: 'babel-loader',
        query: {
          presets: ['@babel/env', '@babel/react',],
          plugins: ['@babel/plugin-proposal-class-properties']
        }
      },
    }]
  },
  devtool: 'source-map',
  resolve: {
    extensions: [".js", ".jsx"]
  }
};

Note that I have Babel with some extensions added, you may want to add more or remove some depending on JS syntax you’re using.

See here on how to set up root file


问:
How does activeClassName work with Link component?
As in title - how does activeClassName param work with react-router-dom Link component? What does it mean that some class is active? In docs we can find only:

The className a <Link> receives when its route is active. No active class by default.

But without explanation what the active route actually is.

Edit: okay, now, having understood this, I can see that I could guess this meaning of this phrase. But I still think that was quite confusing.

答:
If the URL is same as the to of your Link, activeClassName will be assigned to your anchor tag. Suppose you have 3 tabs:

```<code><Link to='/tab-1' activeClassName="red-text">Tab 1</Link>
<Link to='/tab-2' activeClassName="red-text">Tab 2</Link>
<Link to='/tab-3' activeClassName="red-text">Tab 3</Link>
</code>```

If your current URL is site.com/tab-2, only tab 2 will have the red-text class name, other tabs will not have it.

The above code will render as below when the url is site.com/tab-2, so that Tab 2 will be highlighted.

```<code><a href='/tab-1'>Tab 1</Link>
<a href='/tab-2' class="red-text">Tab 2</Link>
<a href='/tab-3' >Tab 3</Link>
</code>```

Example here.

Body:
If the URL is same as the to of your Link, activeClassName will be assigned to your anchor tag. Suppose you have 3 tabs:

<Link to='/tab-1' activeClassName="red-text">Tab 1</Link>
<Link to='/tab-2' activeClassName="red-text">Tab 2</Link>
<Link to='/tab-3' activeClassName="red-text">Tab 3</Link>

If your current URL is site.com/tab-2, only tab 2 will have the red-text class name, other tabs will not have it.

The above code will render as below when the url is site.com/tab-2, so that Tab 2 will be highlighted.

<a href='/tab-1'>Tab 1</Link>
<a href='/tab-2' class="red-text">Tab 2</Link>
<a href='/tab-3' >Tab 3</Link>

Example here.


问:
tf.boolean_mask not accepting the axis argument
Here is my code:

```<code> 44     scores = tf.boolean_mask(box_class_scores,filtering_mask,axis=-1)
 45     boxes = tf.boolean_mask(boxes,filtering_mask,axis=-1)
 46     classes = tf.boolean_mask(box_classes,filtering_mask,axis=-1)
</code>```

Error, I'm getting:

TypeError: boolean_mask() got an unexpected keyword argument 'axis'

The tf.boolean_mask() is not accepting the axis argument but is a valid argument as can be seen in the documentation: https://www.tensorflow.org/api_docs/python/tf/boolean_mask

答:
As @syltruong has pointed out, check if the version of Keras you're using matches the documentation. Right now, the documentation uses version 2.2.4.

On a side note @Ganesh and @Sushant, you don't actually need to use the axis parameter for that particular piece of code in the Deep Learning Specialization.

Body:
Here is my code:

 44     scores = tf.boolean_mask(box_class_scores,filtering_mask,axis=-1)
 45     boxes = tf.boolean_mask(boxes,filtering_mask,axis=-1)
 46     classes = tf.boolean_mask(box_classes,filtering_mask,axis=-1)

Error, I'm getting:

TypeError: boolean_mask() got an unexpected keyword argument 'axis'

The tf.boolean_mask() is not accepting the axis argument but is a valid argument as can be seen in the documentation: https://www.tensorflow.org/api_docs/python/tf/boolean_mask


问:
svnsync: PROPFIND request failed
I'm desperately trying to backup my google code-repo but since
I'm not too familiar with SVN, I can't get svnsync to work.
I thought that backing up your repo to another repo or dumpfile was an easy
task, but I'm wrong? I would really appreciate tips on how to do this..

What I'm trying to do:

@shell:~$ svnsync init http://www..org/svn/
http://.googlecode.com/svn/trunk
svnsync: PROPFIND request failed on '/svn'
svnsync: PROPFIND of '/svn': 301 Moved Permanently (http://www..org)

What does that mean? And is it possible to fix it?

http://www.*.org/svn/ was created with svnadmin create, ofc.

Thanks in advance! =)

答: I would raise this in a comment, but I don't have the points to comment yet.  It looks like at least part of your problem is that your URLs may not be correct.  The 301 is telling you that the resource you expect to find there is not actually there, so I'd start by checking that URL by doing an svn ls on it.</p>

OwnerDisplayName: Stian S

ContentLicense: CC BY-SA 2.5

Title: svnsync: PROPFIND request failed

OwnerDisplayName: runako


问:
Find something(min/max/unique) for path between u and v node in a graph for every query
https://www.hackerearth.com/challenges/hiring/sap-labs-java-hiring-challenge/algorithm/micro-and-internship-10/description/

In query based questions, like above, where we have to find path between two nodes every time and perform some operation on the path, what should be the approach? I have tried DFS, but it's giving run time error as well as Time limit Exceeded.

DFS algorithm

答:
First let's solve the problem using normal dfs for each query. What we need is a boolean array V of length 100 (since the values on each node can't exceed 100) and as we traversing each node if V[a[u]] (where u is the current node) is 0 set it to 1 and increment the answer.

Now to solve a similar problem like finding a min edge between two nodes we need to use sparse table which is also used to find LCA, if you dont know what a sparse table is I recommend you read about it here https://www.hackerrank.com/topics/lowest-common-ancestor (the third part). Briefly it's a way to find LCA in O(log n) with O(nlogn) pre-processing.

If we take 2 nodes u and v and we want to find the min weight in the path it's equivalent to finding the min of the min weight from u to LCA(u,v) and and the min weight from v to LCA(u,v).

How is that useful ? using sparse table, instead of just saving where a node go to if it makes a jump of height h we also save the min edge on the path then we can simply answer each query with O(log n) complexity.

The same implies to this problem but instead of storing the min value we've got a boolean array as I explained in the first approach, where the i-th value is 1 if there is an edge of weight i when we make a jump of height h and 0 otherwise. Using this array you should be able to answer each query.

this solution makes 100 * log n operations when answering a query since we're iterating through the boolean array.


问:
npm ERR! Error: EPERM: operation not permitted, rename
When I execute npm install I get this error

npm ERR! Error: EPERM: operation not permitted, rename C:\projects******\node_modules\react-async-script' -> 'C:\projects*******\node_modules.react-async-script.DELETE'

I am running the cmd as administrator

I ran npm cache clean before

I made sure all the other applications don't have anything related to node_modules open

答: As Martin Kearn pointed out in a comment, closing Visual Studio resolved these npm permission issues for me. Evidently VS sometimes locks files in node_modules.


问:
how to " sort csv file" python
I'm trying to create a new file that contains only the data for movies with a rank above 9.

The dataset that I'm analyzing contains rating on many movies obtained from IMDB.
The data fields are:

Votes: the number of people rating the movie

Rank: the averate rating of the movie

Title: the name of the movie

Year: the year in which the movie was released

The code I tried:

```<code>import csv

filename = "IMDB.txt"
with open(filename, 'rt', encoding='utf-8-sig') as imdb_file:
    imdb_reader = csv.DictReader(imdb_file, delimiter = '\t')
    with open('new file.csv', 'w', newline='') as high_rank:
        fieldnames = ['Votes', 'Rank', 'Title', 'Year']
        writer = csv.DictWriter(high_rank, fieldnames=fieldnames)
        writer.writeheader()
        for line_number, current_row in enumerate (imdb_reader):
            if(float(current_row['Rank']) > 9.0):
                csv_writer.writerow(dict(current_row))
</code>```

but unfortunately its not working, what should i do ?

答:
Let's considere you have the following excel sheet name temp.csv and you want to filter films with a rank above 9 (included):

One simple way to do is to use the pandas modules. It gives you the opportunity to :

read .csv files with pd.read_csv method (doc)

filter data as you want

export data to a new file : for .csv output, df.to_csv do the job (doc)

Assume you have the following dataframe:

The code bellow do the job:

# import modules
import pandas as pd

# Path - name of your file
filename = "temp.csv"

# Read the csv file
df = pd.read_csv(filename, sep=";")
print(df)
#    Votes  Rank                               Film  Year
# 0     15    16          The Shawshank Redemption   1994
# 1   2004     5                     The Godfather   1972
# 2    486    13            The Godfather: Part II   1974
# 3    529     9  Il buono, il brutto, il cattivo.   1966
# 4    289    12                      Pulp Fiction   1994
# 5     98    11                         Inception   2010
# 6     69    18                  Schindler's List   1993
# 7      3     7                         Angry Men   1957
# 8    584    14   One Flew Over the Cuckoo's Nest   1975

# Filter the csv file
df_filtered = df[df["Rank"] >= 9]
print(df_filtered)
#    Votes  Rank                               Film  Year
# 0     15    16          The Shawshank Redemption   1994
# 2    486    13            The Godfather: Part II   1974
# 3    529     9  Il buono, il brutto, il cattivo.   1966
# 4    289    12                      Pulp Fiction   1994
# 5     98    11                         Inception   2010
# 6     69    18                  Schindler's List   1993
# 8    584    14   One Flew Over the Cuckoo's Nest   1975

# name new csv file
new_filename = filename[:-3] + "_new" + filename[-3:]

# Export dataframe to csv file
df_filtered.to_csv(new_filename)
```

The new .csv looks like this:

Title: how to " sort csv file" python

Body:
I'm trying to create a new file that contains only the data for movies with a rank above 9.

The dataset that I'm analyzing contains rating on many movies obtained from IMDB.
The data fields are:

Votes: the number of people rating the movie

Rank: the averate rating of the movie

Title: the name of the movie

Year: the year in which the movie was released

The code I tried:

import csv

filename = "IMDB.txt"
with open(filename, 'rt', encoding='utf-8-sig') as imdb_file:
    imdb_reader = csv.DictReader(imdb_file, delimiter = '\t')
    with open('new file.csv', 'w', newline='') as high_rank:
        fieldnames = ['Votes', 'Rank', 'Title', 'Year']
        writer = csv.DictWriter(high_rank, fieldnames=fieldnames)
        writer.writeheader()
        for line_number, current_row in enumerate (imdb_reader):
            if(float(current_row['Rank']) > 9.0):
                csv_writer.writerow(dict(current_row))

but unfortunately its not working, what should i do ?

Body:
Let's considere you have the following excel sheet name temp.csv and you want to filter films with a rank above 9 (included):

One simple way to do is to use the pandas modules. It gives you the opportunity to :

read .csv files with pd.read_csv method (doc)

filter data as you want

export data to a new file : for .csv output, df.to_csv do the job (doc)

Assume you have the following dataframe:

The code bellow do the job:

# import modules
import pandas as pd

# Path - name of your file
filename = "temp.csv"

# Read the csv file
df = pd.read_csv(filename, sep=";")
print(df)
#    Votes  Rank                               Film  Year
# 0     15    16          The Shawshank Redemption   1994
# 1   2004     5                     The Godfather   1972
# 2    486    13            The Godfather: Part II   1974
# 3    529     9  Il buono, il brutto, il cattivo.   1966
# 4    289    12                      Pulp Fiction   1994
# 5     98    11                         Inception   2010
# 6     69    18                  Schindler's List   1993
# 7      3     7                         Angry Men   1957
# 8    584    14   One Flew Over the Cuckoo's Nest   1975

# Filter the csv file
df_filtered = df[df["Rank"] >= 9]
print(df_filtered)
#    Votes  Rank                               Film  Year
# 0     15    16          The Shawshank Redemption   1994
# 2    486    13            The Godfather: Part II   1974
# 3    529     9  Il buono, il brutto, il cattivo.   1966
# 4    289    12                      Pulp Fiction   1994
# 5     98    11                         Inception   2010
# 6     69    18                  Schindler's List   1993
# 8    584    14   One Flew Over the Cuckoo's Nest   1975

# name new csv file
new_filename = filename[:-3] + "_new" + filename[-3:]

# Export dataframe to csv file
df_filtered.to_csv(new_filename)

The new .csv looks like this:


问:
JavaScript C Style Type Cast From Signed To Unsigned
how to type cast a number in javascript?

```<code>a = (unsigned int)atoi(arg1);
b = (unsigned int)atoi(arg2);
</code>```

Assuming that a and b can be signed.

I want to convert a 4 byte signed integer into a 4 byte unsigned integer.

I know there is no such thing as type casting or signed/unsigned in javascript. I am looking for an easy to understand algorithm.

答:
convert signed byte to unsigned byte, javascript:

```<code>-5 & 0xff // = 251   , signed to unsigned byte
251 <<24 >>24 // = -5  , unsinged byte to signed
</code>```

the first makes all first bits 0 except the 1st byte

the second found on

https://blog.vjeux.com/2013/javascript/conversion-from-uint8-to-int8-x-24.html

basically, in a number, there are 4 bytes.
in a positive number, the 3 first bytes are 0 and all 0 bits are zero.
in a negative number, the 3 first bytes are 1 and all 0 bits are one and all 1 bits are zero. In bytes the most significant bit of 4th byte is used for sign;

shifting bits to left makes the 1st bit 1 of 1st byte to be as the 1st bit of 4th byte, then shifting again to the right, drags the most significant bit across. so if the sign bit is 1. it makes many 1 bits in front 3 bytes. so it is a side effect of shifting but it works.

```<code>for example: like you start from
?1111111 the first bit is a sign bit - ?,
but in a larger variable,  so it is:

00000000_00000000_00000000_?1111111
shift to left
?1111111_........_........_........
shift to right
????????_????????_????????_?1111111
this is the effect,
it drags the edge bit across the shift
</code>```

Body:
how to type cast a number in javascript?

a = (unsigned int)atoi(arg1);
b = (unsigned int)atoi(arg2);

Assuming that a and b can be signed.

I want to convert a 4 byte signed integer into a 4 byte unsigned integer.

I know there is no such thing as type casting or signed/unsigned in javascript. I am looking for an easy to understand algorithm.

Body:
convert signed byte to unsigned byte, javascript:

-5 & 0xff // = 251   , signed to unsigned byte
251 <<24 >>24 // = -5  , unsinged byte to signed

the first makes all first bits 0 except the 1st byte

the second found on

https://blog.vjeux.com/2013/javascript/conversion-from-uint8-to-int8-x-24.html

basically, in a number, there are 4 bytes.
in a positive number, the 3 first bytes are 0 and all 0 bits are zero.
in a negative number, the 3 first bytes are 1 and all 0 bits are one and all 1 bits are zero. In bytes the most significant bit of 4th byte is used for sign;

shifting bits to left makes the 1st bit 1 of 1st byte to be as the 1st bit of 4th byte, then shifting again to the right, drags the most significant bit across. so if the sign bit is 1. it makes many 1 bits in front 3 bytes. so it is a side effect of shifting but it works.

for example: like you start from
?1111111 the first bit is a sign bit - ?,
but in a larger variable,  so it is:

00000000_00000000_00000000_?1111111
shift to left
?1111111_........_........_........
shift to right
????????_????????_????????_?1111111
this is the effect,
it drags the edge bit across the shift


答:
If you don't add a $path value to setcookie(), it defaults to "the current directory". This means that if you set the cookie from /web/DEV/Classes/SetCookie.php, the cookie gets set to /web/DEV/Classes/, and anything above that path won't see that cookie.

To fix this, add a specific $path to setcookie. If your app runs on the domain root (example.com), use '/'. If it's in a subfolder (example.com/myapp/), use '/myapp/'

```<code>setcookie("TestCookie", $var, time()+60*60*24*30, '/');
</code>```

Title: php setcookie not working with ajax call

Body:
I have a page, test.php, with the following code:

        <form>

            <input type="text" id="txtInput" name="txtInput"/>
            <input type="button" id="btnSubmit" name="btnSubmit" value="Submit"  onclick="SendCookies()"/>

                <?php
                    if (isset($_COOKIE["TestCookie"])) {
                        echo $_COOKIE["TestCookie"];
                    } else {
                        echo "__Results__";
                    }
                ?>

        </form>

I have a page, SetCookie.php, with the following code:

<?php
    $var = "THIS IS  A  TEST";
    setcookie("TestCookie", $var, time()+60*60*24*30);
?>

When test.php's button is clicked, i use XMLHttpRequest to call my SetCookie.php page.  The page executes, becuase if i add an echo to it, i get that in the xmlhttp response.  However, TestCookie does not seem to be getting set.

If in text.php, i do the same command found in SetCookie.php, the cookie is then set accordingly for all browser sessions.

Even after i close / open the browser, the cookie remains unchanged from when i once set it in my test.php page manually.

----EDIT-----

I added:

if(!setcookie("TestCookie", "A", time()+60*60*24*30, "/")) {
    echo "FAIL";
}

to the very top of test.php, however when i reload the page, it never shows the updated cookie... because that cookie was already set without the ,"/" parameter, and cannot be modified later, with the ,"/" parameter.

After clearing the cache and working with the suggested code, i cleared my cookies from the browser and used the added parameter for the set method, i was able to manipulate the cookies from all pages!!! thank you so much!!

Body:
If you don't add a $path value to setcookie(), it defaults to "the current directory". This means that if you set the cookie from /web/DEV/Classes/SetCookie.php, the cookie gets set to /web/DEV/Classes/, and anything above that path won't see that cookie.

To fix this, add a specific $path to setcookie. If your app runs on the domain root (example.com), use '/'. If it's in a subfolder (example.com/myapp/), use '/myapp/'

setcookie("TestCookie", $var, time()+60*60*24*30, '/');


问:
Best methodology for evaluating a software architecture/ test software attributes like 'scalability' without specifics?
I want to evaluate software without doing a detailled system test. For example: I don't want to test wether my software can handle a maximum of 20ms latency. I want to prove that my software's performance is scalable (by it's design). What kind of methodology would be appropiate?</p>

答:
Scalability is the ability of the software to continue to perform in an acceptable manner when the system keeps getting bigger in terms of various factors. For example:

Data: The growth of data size that system persists or processes.

Traffic: The growth in volume of incoming/outgoing traffic increases

Users:  The growth in the number of active users and thus simultaneous connections

New Features / Operations: The increase in the number of features/operations supported by the system. Although this factor may fall into extensibility, it may affect scalability sometimes.

As per my understanding, you want to prove that the software is scalable but you do not care about proving the specific metrics that the system would be able to support. One approach could be to identify ALL the potential bottlenecks that would come into picture when the system gets bigger, document these bottlenecks and then document/demonstrate that the software would be able to overcome these bottlenecks. The metrics collection can be more work which is not required as you mentioned but performing a high level load test and giving a visual demonstration that the system is able to handle the load might be one of the ways. Not sure about the exact situation of yours but hope this helps.


问:
Generate multiple similar functions with C preprocessor
I want to generate multiple similar functions replacing just one word across the function.

As an example, for each of the below:

```<code>OBJECT = customer
OBJECT = account
</code>```

use the function template:

```<code>void add_OBJECT_to_array(void* item_ptr, int pos)
{
    mtx_lock(&OBJECT_array_mtx);
    OBJECT_array[pos] = *(OBJECT_t*)item_ptr;
    mtx_unlock(&OBJECT_array_mtx);
    return;
}
</code>```

So that I can call

```<code>add_order_to_array(ord, 1);
add_customer_to_array(cust, 1);
</code>```

Is this possible?

答:
Yes it's possible:

```<code>#define DECLARE_ADD_FUNCTION(__obj)                         \
    void add_##__obj##_to_array(void* item_ptr, int pos)    \
    {                                                       \
        mtx_lock(&__obj##_array_mtx);                       \
        __obj##_array[pos] = *(__obj##_t*)item_ptr;         \
        mtx_unlock(&__obj##_array_mtx);                     \
        return;                                             \
    }

DECLARE_ADD_FUNCTION(customer)
DECLARE_ADD_FUNCTION(account)
</code>```

When you look at the output of the preprocessor you get:

gcc -E foo.c

```<code>void add_customer_to_array(void* item_ptr, int pos) { mtx_lock(&customer_array_mtx); customer_array[pos] = *(customer_t*)item_ptr; mtx_unlock(&customer_array_mtx); return; }
void add_account_to_array(void* item_ptr, int pos) { mtx_lock(&account_array_mtx); account_array[pos] = *(account_t*)item_ptr; mtx_unlock(&account_array_mtx); return; }
</code>```

You can even ensure that the pointer type is the correct type by changing the function prototype to add_##__obj##_to_array(__obj##_t *, int pos)

Body:
I want to generate multiple similar functions replacing just one word across the function.

As an example, for each of the below:

OBJECT = customer
OBJECT = account

use the function template:

void add_OBJECT_to_array(void* item_ptr, int pos)
{
    mtx_lock(&OBJECT_array_mtx);
    OBJECT_array[pos] = *(OBJECT_t*)item_ptr;
    mtx_unlock(&OBJECT_array_mtx);
    return;
}

So that I can call

add_order_to_array(ord, 1);
add_customer_to_array(cust, 1);

Is this possible?

Body:
Yes it's possible:

#define DECLARE_ADD_FUNCTION(__obj)                         \
    void add_##__obj##_to_array(void* item_ptr, int pos)    \
    {                                                       \
        mtx_lock(&__obj##_array_mtx);                       \
        __obj##_array[pos] = *(__obj##_t*)item_ptr;         \
        mtx_unlock(&__obj##_array_mtx);                     \
        return;                                             \
    }

DECLARE_ADD_FUNCTION(customer)
DECLARE_ADD_FUNCTION(account)

When you look at the output of the preprocessor you get:

gcc -E foo.c

void add_customer_to_array(void* item_ptr, int pos) { mtx_lock(&customer_array_mtx); customer_array[pos] = *(customer_t*)item_ptr; mtx_unlock(&customer_array_mtx); return; }
void add_account_to_array(void* item_ptr, int pos) { mtx_lock(&account_array_mtx); account_array[pos] = *(account_t*)item_ptr; mtx_unlock(&account_array_mtx); return; }

You can even ensure that the pointer type is the correct type by changing the function prototype to add_##__obj##_to_array(__obj##_t *, int pos)


问:
How to use group by on 2 different columns and use SUM function in mysql
I have this table:

and I want records like this:

```<code>Leave_detail_id   emp_id  leave_count
-------------------------------------
  1                 22       3
  3                 22       2
  2                 30       4
</code>```

Please help me how to use multiple GROUP BY with SUM

答:
```<code>SELECT leave_detail_id, emp_id, SUM(leave_count) FROM table GROUP BY Leave_detail_id, emp_id;
</code>```

Body:
I have this table:

and I want records like this:

Leave_detail_id   emp_id  leave_count
-------------------------------------
  1                 22       3
  3                 22       2
  2                 30       4

Please help me how to use multiple GROUP BY with SUM