问:
How to write a mutation resolver to change one or more specific values of an object?
It seems reasonable to expect one resolver to handle input for any combination of one or more of an object's values. I shouldn't have to write separate resolvers for 'title', 'published', 'author', etc., right?

Here's my example object:

```<code>let books = [
  {
    title: 'Clean Code',
    published: 2008,
    author: 'Robert Martin',
    id: 'afa5b6f4-344d-11e9-a414-719c6709cf8e',
    genres: ['refactoring'],
  },
  {
    title: 'Agile software development',
    published: 2002,
    author: 'Robert Martin',
    id: 'afa5b6f5-344d-11e9-a414-719c6709cf9e',
    genres: ['agile', 'patterns', 'design'],
  },
]
</code>```

typeDefs:

```<code>const typeDefs = gql`
  type Book {
    title: String
    published: Int
    author: String
    id: ID
    genres: [String]
  }

  type Query {
    bookCount: Int!
    allBooks(title: String, author: String, genre: String): [Book]
    findBooks(title: String!): Book
  }

  type Mutation {
    addBook(
      title: String!
      published: Int
      author: String!
      genres: [String]
    ): Book
    editBook(
      id: ID
      title: String
      published: Int
      author: String
      genres: [String]
    ): Book
  }
`
</code>```

Here's the resolver I currently have:

```<code> Mutation: {
     editBook: (_, args) => {
      const book = books.find(b => b.id === args.id)
      if (!book) {
        return null
      }
      const updatedBook = {
        ...book,
        title: args.title,
        author: args.author,
        published: args.published,
        genres: [args.genres],
      }
      books = books.map(b => (
        b.id === args.id ? updatedBook : b))
      return updatedBook
    },
    }
</code>```

Here's what is currently happening.

Original object:

```<code>"allBooks": [
      {
        "id": "afa5b6f4-344d-11e9-a414-719c6709cf8e",
        "title": "Clean Code",
        "author": "Robert Martin",
        "published": 2008,
        "genres": [
          "refactoring"
        ]
      },
{...}
]
</code>```

Mutation query:

```<code>mutation {
  editBook(id:"afa5b6f4-344d-11e9-a414-719c6709cf8e", title:"changed"){
    id
    title
    author
    published
    genres
  }
}
</code>```

Returns this:

```<code>{
  "data": {
    "editBook": {
      "id": "afa5b6f4-344d-11e9-a414-719c6709cf8e",
      "title": "changed",
      "author": null,
      "published": null,
      "genres": [
        null
      ]
    }
  }
}
</code>```

How do I write the resolver to change one or more of an object's values, without changing the unspecified values to 'null'?

My javascript skills are, I'll admit, rather shaky, and I'm guessing the answer lies with a more eloquent map function, but since the code runs inside a graphql schema module, it doesn't handle console.log so troubleshooting is problematic. Any recommendations to address that would be extremely helpful as well, so I can troubleshoot my own problems better.

答:
Couple of points

There's no need to use map or to reassign books. Because the book variable is a reference to the object in your books array, you can mutate it (but not reassign it) and you will mutate the object in the array. See this question for additional details.

```<code>const book = books.find(b => b.id === args.id)
if (book) {
  // you cannot reassign book and still have the original value change,
  // but you can mutate it
  book.title = args.title
  book.author = args.author
  book.published = args.published
  book.genres = args.genres
}
return book
</code>```

To change only the values present in args, you have some options:

You can use the logical OR operator (||) to provide another value to assign if the first value is falsey. Here, book.title will only be used if args.title is undefined, null, 0, NaN, "", or false.

```<code>book.title = args.title || book.title
</code>```

You can use Object.assign, which copies the properties from one object to another. Since args will be missing those properties that aren't provided, you can just do something like the below snippet. This is much more elegant and concise, but will only work if your argument names match your property names.

```<code>Object.assign(book, args)
</code>```

You can loop through the args object. This might be more desirable if you have one or more arguments that don't match the properties of book:

```<code>Object.keys(args).forEach(argName => {
  const argValue = args[argName]
  book[argName] = argValue
})
</code>```

Putting it all together, we might do:

```<code>const book = books.find(b => b.id === args.id)
if (book) {
  Object.assign(book, args)
}
return book
</code>```

Body:
It seems reasonable to expect one resolver to handle input for any combination of one or more of an object's values. I shouldn't have to write separate resolvers for 'title', 'published', 'author', etc., right?

Here's my example object:

let books = [
  {
    title: 'Clean Code',
    published: 2008,
    author: 'Robert Martin',
    id: 'afa5b6f4-344d-11e9-a414-719c6709cf8e',
    genres: ['refactoring'],
  },
  {
    title: 'Agile software development',
    published: 2002,
    author: 'Robert Martin',
    id: 'afa5b6f5-344d-11e9-a414-719c6709cf9e',
    genres: ['agile', 'patterns', 'design'],
  },
]

typeDefs:

const typeDefs = gql`
  type Book {
    title: String
    published: Int
    author: String
    id: ID
    genres: [String]
  }

  type Query {
    bookCount: Int!
    allBooks(title: String, author: String, genre: String): [Book]
    findBooks(title: String!): Book
  }

  type Mutation {
    addBook(
      title: String!
      published: Int
      author: String!
      genres: [String]
    ): Book
    editBook(
      id: ID
      title: String
      published: Int
      author: String
      genres: [String]
    ): Book
  }
`

Here's the resolver I currently have:

 Mutation: {
     editBook: (_, args) => {
      const book = books.find(b => b.id === args.id)
      if (!book) {
        return null
      }
      const updatedBook = {
        ...book,
        title: args.title,
        author: args.author,
        published: args.published,
        genres: [args.genres],
      }
      books = books.map(b => (
        b.id === args.id ? updatedBook : b))
      return updatedBook
    },
    }

Here's what is currently happening.

Original object:

"allBooks": [
      {
        "id": "afa5b6f4-344d-11e9-a414-719c6709cf8e",
        "title": "Clean Code",
        "author": "Robert Martin",
        "published": 2008,
        "genres": [
          "refactoring"
        ]
      },
{...}
]

Mutation query:

mutation {
  editBook(id:"afa5b6f4-344d-11e9-a414-719c6709cf8e", title:"changed"){
    id
    title
    author
    published
    genres
  }
}

Returns this:

{
  "data": {
    "editBook": {
      "id": "afa5b6f4-344d-11e9-a414-719c6709cf8e",
      "title": "changed",
      "author": null,
      "published": null,
      "genres": [
        null
      ]
    }
  }
}

How do I write the resolver to change one or more of an object's values, without changing the unspecified values to 'null'?

My javascript skills are, I'll admit, rather shaky, and I'm guessing the answer lies with a more eloquent map function, but since the code runs inside a graphql schema module, it doesn't handle console.log so troubleshooting is problematic. Any recommendations to address that would be extremely helpful as well, so I can troubleshoot my own problems better.

Body:
Couple of points

There's no need to use map or to reassign books. Because the book variable is a reference to the object in your books array, you can mutate it (but not reassign it) and you will mutate the object in the array. See this question for additional details.

const book = books.find(b => b.id === args.id)
if (book) {
  // you cannot reassign book and still have the original value change,
  // but you can mutate it
  book.title = args.title
  book.author = args.author
  book.published = args.published
  book.genres = args.genres
}
return book

To change only the values present in args, you have some options:

You can use the logical OR operator (||) to provide another value to assign if the first value is falsey. Here, book.title will only be used if args.title is undefined, null, 0, NaN, "", or false.

book.title = args.title || book.title

You can use Object.assign, which copies the properties from one object to another. Since args will be missing those properties that aren't provided, you can just do something like the below snippet. This is much more elegant and concise, but will only work if your argument names match your property names.

Object.assign(book, args)

You can loop through the args object. This might be more desirable if you have one or more arguments that don't match the properties of book:

Object.keys(args).forEach(argName => {
  const argValue = args[argName]
  book[argName] = argValue
})

Putting it all together, we might do:

const book = books.find(b => b.id === args.id)
if (book) {
  Object.assign(book, args)
}
return book


来源: stackexchange

问:
UITabBarController not showing all view controllers
My UITabBarcontroller has two view controllers
-Favorites
-Keypad

I add these two controllers in an array in the order Favorites,Keypad,nil.

When the app is launched only the Favorites tab appears in the tabbar, I have to click the second tab for the "Keypad" (Title of the viewController) text to appear on the tabbar.

How do I make the tabbar have the title of both the view controllers at startup itself?

答:
Try this in your ViewController where you load the tabController:

```<code>-(void)viewDidLoad
{
    [super viewDidLoad];
    // creating the tabController
    UITabBarController *tabBarController = [[UITabBarController alloc] init];

    NSArray* controllers = [NSArray arrayWithObjects: myViewController, nil];

    myViewController.title = @"Title";

    tabBarController.viewControllers = controllers;
    [controllers release];
    [self.view addSubview:tabBarController.view];
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try this in your ViewController where you load the tabController:

-(void)viewDidLoad
{
    [super viewDidLoad];
    // creating the tabController
    UITabBarController *tabBarController = [[UITabBarController alloc] init];

    NSArray* controllers = [NSArray arrayWithObjects: myViewController, nil];

    myViewController.title = @"Title";

    tabBarController.viewControllers = controllers;
    [controllers release];
    [self.view addSubview:tabBarController.view];
}

ContentLicense: CC BY-SA 3.0


问:
How to build a chart at runtime
In a winforms project, if I add a chart control at design time, the following code builds and displays a chart perfectly.

However, without a chart1 on my form (at design time), if I create the same chart1 at run-time:

```<code>Chart chart1 = new Chart();
</code>```

add the series,

and then add it to my form:

```<code>this.Controls.Add(chart1);
</code>```

an empty chart displays as if the series was not added.

I need to build my chart completely at run-time.  Can anyone help me please?

```<code>using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Test
{
    public partial class Charts : Form
    {
        public Charts()
        {
            InitializeComponent();
            //Chart chart1 = new Chart();
            chart1.Series.Clear();
            chart1.Titles.Add("My Chart");

            chart1.Series.Add("Load");
            chart1.Series["Load"].ChartType = SeriesChartType.Column;

            chart1.Series["Load"].Points.AddXY(1, 40);
            chart1.Series["Load"].Points.AddXY(2, 60);
            chart1.Series["Load"].Points.AddXY(3, 80);
            chart1.Series["Load"].Points.AddXY(4, 100);
            chart1.Series["Load"].Points.AddXY(5, 110);
            chart1.Series["Load"].Points.AddXY(6, 80);
            chart1.Series["Load"].Points.AddXY(7, 70);

            //this.Controls.Add(chart1);

        }
    }
}
</code>```

答:
I just don't think you have managed to get all of the code out of the designer properly. Here's a minimal example that works for me:</p>

```<code>using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace WindowsFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var chart = new Chart();

            chart.ChartAreas.Add(new ChartArea());

            var series = new Series();
            series.Points.AddXY(1.0, 42.0);
            series.Points.AddXY(2.0, 47.0);
            series.Points.AddXY(3.0, 53.0);
            chart.Series.Add(series);

            chart.Location = new System.Drawing.Point(10, 10);
            chart.Size = new System.Drawing.Size(500, 400);

            this.Controls.Add(chart);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to build a chart at runtime

Body:
In a winforms project, if I add a chart control at design time, the following code builds and displays a chart perfectly.

However, without a chart1 on my form (at design time), if I create the same chart1 at run-time:

Chart chart1 = new Chart();

add the series,

and then add it to my form:

this.Controls.Add(chart1);

an empty chart displays as if the series was not added.

I need to build my chart completely at run-time.  Can anyone help me please?

using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Test
{
    public partial class Charts : Form
    {
        public Charts()
        {
            InitializeComponent();
            //Chart chart1 = new Chart();
            chart1.Series.Clear();
            chart1.Titles.Add("My Chart");

            chart1.Series.Add("Load");
            chart1.Series["Load"].ChartType = SeriesChartType.Column;

            chart1.Series["Load"].Points.AddXY(1, 40);
            chart1.Series["Load"].Points.AddXY(2, 60);
            chart1.Series["Load"].Points.AddXY(3, 80);
            chart1.Series["Load"].Points.AddXY(4, 100);
            chart1.Series["Load"].Points.AddXY(5, 110);
            chart1.Series["Load"].Points.AddXY(6, 80);
            chart1.Series["Load"].Points.AddXY(7, 70);

            //this.Controls.Add(chart1);

        }
    }
}

Body:
I just don't think you have managed to get all of the code out of the designer properly. Here's a minimal example that works for me:

using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace WindowsFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var chart = new Chart();

            chart.ChartAreas.Add(new ChartArea());

            var series = new Series();
            series.Points.AddXY(1.0, 42.0);
            series.Points.AddXY(2.0, 47.0);
            series.Points.AddXY(3.0, 53.0);
            chart.Series.Add(series);

            chart.Location = new System.Drawing.Point(10, 10);
            chart.Size = new System.Drawing.Size(500, 400);

            this.Controls.Add(chart);
        }
    }
}


问:
Upgrade Gupta application from version 5.2 to 7.0
I'm trying to convert a gupta application from version 5.2 to the version 7.0, after that i see that there is an external functions whose name is mimg52.dll, i try to change it in mimg70.dll but there isn't any dll on my computer which this name. Then, i try to launch the application with the dll version 5.2 but the program shows me the following message:
"Gupta runtime environment could not be loaded (CDLLI52.dll)"

How can i fix it?

答:
Looks like you have 2 issues at the same time, but one could be causing the other....

Deal with the first one first and download the correct v7.0 mimg dlls from here: mImg and mTbl link , (mImg and mTbl is a 3rd party plug-in.) , or better still, from the official Gupta TeamDeveloper Community forum here: mImg download from TD forum   ( register and you get more options ) ...

and then copy them directly into your application path ( you don't need to register the dll's ). MAKE SURE YOU USE THE CORRECT VERSION AS THEY ARE ALL IN THIS DOWNLOAD.
Then change your code from *52.dll to *70.dll .

Then we'll deal with the next issue once you are loading the correct mimg dll's, if they are not already fixed by this.


问:
Replaces command for label in helm charts
I often see the following snippet in the helm charts:

```<code>  labels:
    app: {{ template "app.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
</code>```

Why is the replacement necessary? Are + signs bad?

答:
As per this (https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set) documentation, labels cannot have plus(+) character in its value. </p>

```<code>The name segment is required and must be 63 characters or less, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between.
</code>```

Body:
I often see the following snippet in the helm charts:

  labels:
    app: {{ template "app.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}

Why is the replacement necessary? Are + signs bad?

Body:
As per this (https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set) documentation, labels cannot have plus(+) character in its value.

The name segment is required and must be 63 characters or less, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between.


问:
Store session in MemCache instead of default session storage in Yii 1.x
This is the code, that I've added to config/main.php in my Yii 1.x application:

```<code>   'mCache' => array(
        'class' => 'system.caching.CMemCache',
        'useMemcached'=>true,
        'keyPrefix'=>'',
        'hashKey'=>false,
        'serializer'=>false,
        'servers' => array(
            array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 10000)
        ),
    ),

    'session' => array(
        'sessionName' => 'PHPSESSID',
        'class' => 'CCacheHttpSession',
        'autoStart' => true,
        'cacheID' => 'mCache',
        'cookieMode' => 'only',
        'timeout' => 1200
    ),
</code>```

What should I do next, to force Yii to use CMemCache, instead of default session storage?

答:
I know this answer is old, but this configuration works</p>

```<code>    'memcacheConn'=>array(
        'class'=>'CMemCache',
        'servers'=>array(
            array(
                'host'=>'172.17.0.1',
                'port'=>11211,
                //'weight'=>60,
            ),
        ),
    ),
    'session' => array(
        'class' => 'CCacheHttpSession',
        'autoStart' => true,
        'cacheID' => 'memcacheConn',
        'cookieMode' => 'allow',
        'sessionName' => 'MYSSIONNAME',

    ),
</code>```

Body:
This is the code, that I've added to config/main.php in my Yii 1.x application:

   'mCache' => array(
        'class' => 'system.caching.CMemCache',
        'useMemcached'=>true,
        'keyPrefix'=>'',
        'hashKey'=>false,
        'serializer'=>false,
        'servers' => array(
            array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 10000)
        ),
    ),

    'session' => array(
        'sessionName' => 'PHPSESSID',
        'class' => 'CCacheHttpSession',
        'autoStart' => true,
        'cacheID' => 'mCache',
        'cookieMode' => 'only',
        'timeout' => 1200
    ),

What should I do next, to force Yii to use CMemCache, instead of default session storage?

Body:
I know this answer is old, but this configuration works

    'memcacheConn'=>array(
        'class'=>'CMemCache',
        'servers'=>array(
            array(
                'host'=>'172.17.0.1',
                'port'=>11211,
                //'weight'=>60,
            ),
        ),
    ),
    'session' => array(
        'class' => 'CCacheHttpSession',
        'autoStart' => true,
        'cacheID' => 'memcacheConn',
        'cookieMode' => 'allow',
        'sessionName' => 'MYSSIONNAME',

    ),


问:
How to get the index of a max operation
I am not sure how to get the index of the following amax function:

```<code>a = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(2, 2, 2)
print(np.amax(a, axis = (1, 2)))
</code>```

np.amax(a, axis = (1, 2)) should be [4, 8], and I am looking for index as [(0,1,1), (1,1,1)], specifically, I want index as [(1, 1) (1, 1)] not considering the layer index.

答:
```<code>In [654]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(2, 2, 2)
In [655]: np.amax(a, axis=(1,2))
Out[655]: array([4, 8])
In [656]: a
Out[656]:
array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])
</code>```

argmax does not take the tuple indices.  We can get around that by reshaping:

```<code>In [662]: np.argmax(a.reshape(a.shape[0],-1),1)
Out[662]: array([3, 3])
</code>```

and then reconstruct the full index with:

```<code>In [669]: idx = np.argmax(a.reshape(a.shape[0],-1),1)
In [670]: idx = np.unravel_index(idx,a.shape[1:])
In [671]: idx
Out[671]: (array([1, 1]), array([1, 1]))
In [672]:
In [672]: idx = (np.arange(a.shape[0]),)+idx
In [673]: idx
Out[673]: (array([0, 1]), array([1, 1]), array([1, 1]))
In [674]: a[idx]
Out[674]: array([4, 8])
</code>```

Title: How to get the index of a max operation

Body:
I am not sure how to get the index of the following amax function:

a = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(2, 2, 2)
print(np.amax(a, axis = (1, 2)))

np.amax(a, axis = (1, 2)) should be [4, 8], and I am looking for index as [(0,1,1), (1,1,1)], specifically, I want index as [(1, 1) (1, 1)] not considering the layer index.

Body:
In [654]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8]).reshape(2, 2, 2)
In [655]: np.amax(a, axis=(1,2))
Out[655]: array([4, 8])
In [656]: a
Out[656]:
array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])

argmax does not take the tuple indices.  We can get around that by reshaping:

In [662]: np.argmax(a.reshape(a.shape[0],-1),1)
Out[662]: array([3, 3])

and then reconstruct the full index with:

In [669]: idx = np.argmax(a.reshape(a.shape[0],-1),1)
In [670]: idx = np.unravel_index(idx,a.shape[1:])
In [671]: idx
Out[671]: (array([1, 1]), array([1, 1]))
In [672]:
In [672]: idx = (np.arange(a.shape[0]),)+idx
In [673]: idx
Out[673]: (array([0, 1]), array([1, 1]), array([1, 1]))
In [674]: a[idx]
Out[674]: array([4, 8])


问:
Using reflection instead of a long switch statement
Hey so I have a pretty long switch statement that calls a method based on a string like so

```<code>private void callMethod(String name) {
    switch(name) {
        case "blah":
            blah();
            break;
        case "method":
            method()
            break;
    }
}
</code>```

etc.

So I used reflection to shorten the code

```<code>try {
    Method method = ClassName.class.getDeclaredMethod(name, args);
    method.invoke(args);
} catch (NoSuchMethodException e) {
    // switch default
}
</code>```

Just wondering if using reflection like this is bad on memory/performance. I only call this function every so often.

Edit: The reason I used this is because the user has the option to start a different part of the game based on the string they enter in. Each method that starts the event is named after what they need to type in.

答:
Using reflection like that is a bad idea. Have a look here for information about drawbacks.

About the performance:

"Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications."

Don't think of reflection as a normal tool like String or ArrayList and rather try to implement a better software design that fits your needs. Then you will have to think about reflection very rarely.

Edit:

The performance hit is of course debatable but be aware of the other downsides. As others already stated are there security issues, e.g. when a user "calls" a method that is not intended to be "callable" directly by the user. Another downside is that you potentially have problems in your code which are not findable at compile time because of the reflection. And many more downsides ...

In my opinion reflection should be used mostly to solve technical problems that are not directly related to production code, e.g. in testing of your software.

Body:
Hey so I have a pretty long switch statement that calls a method based on a string like so

private void callMethod(String name) {
    switch(name) {
        case "blah":
            blah();
            break;
        case "method":
            method()
            break;
    }
}

etc.

So I used reflection to shorten the code

try {
    Method method = ClassName.class.getDeclaredMethod(name, args);
    method.invoke(args);
} catch (NoSuchMethodException e) {
    // switch default
}

Just wondering if using reflection like this is bad on memory/performance. I only call this function every so often.

Edit: The reason I used this is because the user has the option to start a different part of the game based on the string they enter in. Each method that starts the event is named after what they need to type in.


问:
Easiest way to subclass a widget in Python for use with Qt Designer
I'm building an app using PyQt5, with (most of) the GUI being built using Qt Designer.  I have a few UI elements that do mostly the same thing and it seems sensible to move their code into classes that inherit from a base class (which in turn inherits from QTableWidget).

This seems really straightforward except that I'm not sure how to get Qt Designer to use these classes when generating its UI files.  I've found a guide for doing this in PyQt4 and another one that's for Qt 5 but with native C++ code and yet another one that's for PyQt5 but doesn't deal with the (most complicated) aspect of making the subclasses available in Qt Designer.

How do I make a subclass of a widget created using PyQt5 available for use in Qt Designer?

Alternatively, is there an easier way to do this?  I don't need to change the appearance or functionality of the widgets—I'm mostly just looking for an organized place to store some code that makes their data easier to set and access.

答:
To use a custom widget in Qt Designer there are the following options:

Qt Designer Plugin:

You must create a class that inherits from QPyDesignerCustomWidgetPlugin that indicates the characteristics of how it will be displayed in Qt Designer. The advantage of this method is that you can modify the qproperties besides being able to create dialogs and menus that allow you to make the modification in a friendly way. There is an example in the PyQt5 source code in the "examples/designer/plugins" folder.

Promote widgets

The advantage is that it is not necessary to create anything and the disadvantage is that it does not allow customization beyond what the base class plugin provides. In SO there are several examples: 1, 2, 3.

If you only want to position the widgets then just promote the widget, if instead you want to use Qt Designer to modify properties then a plugin is necessary.


问:
Nested Array in React Object
How do I structure this to stop getting the cant read property map of undefined? The note Object itself looks like this.  I will need to repeat this for a secondary array tasks as well. The problem I'm running into with a lot of other examples is they are either class-based or mapping an array with an array. This should be easier I feel like, but I've tried 1000 things and none of them work.

const notes = [
  {
    id: noteId,
    note: noteText,
    notePostedBy: ''
  }
];
```

<pre class="lang-js prettyprint-override"><code>import React, { useContext, useEffect  } from 'react';
import NoteItem from './NoteItem';
import LeadContext from '../../context/Lead/leadContext';

const Notes = () => {
  const leadContext = useContext(LeadContext);
  const { lead } = leadContext;

  return (
    <div className='leadul'>
     {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}
    </div>
  );
}

export default Notes;
</code>```

```<code>{notes: Array(1), tasks: Array(0), createdate: "2020-02-19T23:25:11.033Z", claimedBy: "unclaimed", isClaimed: false, …}
notes: [{…}]
tasks: []
createdate: "2020-02-19T23:25:11.033Z"
claimedBy: "unclaimed"
isClaimed: false
isClosed: false
isPaid: false
isApproved: false
name2: ""
address2: ""
city2: ""
state2: ""
zip2: ""
employerTime: ""
ssn2: ""
lexId2: ""
relation: ""
phone2: ""
phone3: ""
email2: ""
email3: ""
prac: ""
problem1: ""
problem2: ""
problem3: ""
resSold: ""
resSold2: ""
home: ""
homePay: ""
wages: ""
income1Type: ""
income1Value: ""
income2Type: ""
income2Value: ""
income3Type: ""
income3Value: ""
otherIncomeType: ""
otherIncomeValue: ""
availableCredit: ""
totalCredit: ""
employerName: ""
employerPhone: ""
_id: "5e4dc4354b3bcd36ec86fd53"
notePostedBy: "5e3b346d572df30017a39ef7"
name: "xxxxx"
address: "xxxxx"
city: "xxxxxx"
state: "xxxxx"
zip: "xxxxx"
plaintiff: "STATE OF WEST VIRGINIA"
amount: "10144"
lexId: ""
compliant: "filed"
filingStatus: "m"
cpa: "cpa"
ssn: ""
createdBy: "5e3b346d572df30017a39ef7"
__v: 0
__proto__: Object
</code>```

```<code>×
TypeError: Cannot read property 'map' of undefined
Notes
C:/Webdev/ntenet/client/src/components/popkis/Notes.js:13
  10 |
  11 |
  12 | return (
> 13 |   <div className='leadul'>
  14 |    {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}
  15 |   </div>
  16 |   );
</code>```

答:
When you are fetching data from an API, you have to make sure that the components that rely on the data do not render before the API data has been successfully loaded into the context. There are several ways to do so.

The easiest would be something like this:

```<code>import React, { useContext, useEffect  } from 'react';
import NoteItem from './NoteItem';
import LeadContext from '../../context/Lead/leadContext';

const Notes = () => {
  const leadContext = useContext(LeadContext);
  const { lead } = leadContext;

  return (
    <>
    { lead.notes
      ?
        <div className='leadul'>
         {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}
        </div>
      :
        <p>Data is still loading! Show a nice loading icon here</p>
    }
    </>
  );
}

export default Notes;
</code>```

Title: Nested Array in React Object

Body:
How do I structure this to stop getting the cant read property map of undefined? The note Object itself looks like this.  I will need to repeat this for a secondary array tasks as well. The problem I'm running into with a lot of other examples is they are either class-based or mapping an array with an array. This should be easier I feel like, but I've tried 1000 things and none of them work.

const notes = [
  {
    id: noteId,
    note: noteText,
    notePostedBy: ''
  }
];

import React, { useContext, useEffect  } from 'react';
import NoteItem from './NoteItem';
import LeadContext from '../../context/Lead/leadContext';

const Notes = () => {
  const leadContext = useContext(LeadContext);
  const { lead } = leadContext;

  return (

     {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}

  );
}

export default Notes;

{notes: Array(1), tasks: Array(0), createdate: "2020-02-19T23:25:11.033Z", claimedBy: "unclaimed", isClaimed: false, …}
notes: [{…}]
tasks: []
createdate: "2020-02-19T23:25:11.033Z"
claimedBy: "unclaimed"
isClaimed: false
isClosed: false
isPaid: false
isApproved: false
name2: ""
address2: ""
city2: ""
state2: ""
zip2: ""
employerTime: ""
ssn2: ""
lexId2: ""
relation: ""
phone2: ""
phone3: ""
email2: ""
email3: ""
prac: ""
problem1: ""
problem2: ""
problem3: ""
resSold: ""
resSold2: ""
home: ""
homePay: ""
wages: ""
income1Type: ""
income1Value: ""
income2Type: ""
income2Value: ""
income3Type: ""
income3Value: ""
otherIncomeType: ""
otherIncomeValue: ""
availableCredit: ""
totalCredit: ""
employerName: ""
employerPhone: ""
_id: "5e4dc4354b3bcd36ec86fd53"
notePostedBy: "5e3b346d572df30017a39ef7"
name: "xxxxx"
address: "xxxxx"
city: "xxxxxx"
state: "xxxxx"
zip: "xxxxx"
plaintiff: "STATE OF WEST VIRGINIA"
amount: "10144"
lexId: ""
compliant: "filed"
filingStatus: "m"
cpa: "cpa"
ssn: ""
createdBy: "5e3b346d572df30017a39ef7"
__v: 0
__proto__: Object

×
TypeError: Cannot read property 'map' of undefined
Notes
C:/Webdev/ntenet/client/src/components/popkis/Notes.js:13
  10 |
  11 |
  12 | return (
> 13 |

  14 |    {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}
  15 |

  16 |   );

Body:
When you are fetching data from an API, you have to make sure that the components that rely on the data do not render before the API data has been successfully loaded into the context. There are several ways to do so.

The easiest would be something like this:

import React, { useContext, useEffect  } from 'react';
import NoteItem from './NoteItem';
import LeadContext from '../../context/Lead/leadContext';

const Notes = () => {
  const leadContext = useContext(LeadContext);
  const { lead } = leadContext;

  return (
    <>
    { lead.notes
      ?
        <div className='leadul'>
         {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}
        </div>
      :
        <p>Data is still loading! Show a nice loading icon here</p>
    }
    </>
  );
}

export default Notes;


问:
Create a string method in Java to input a question
So I have this code:

```<code>import javax.swing.JOptionPane;

public class Quiz {
    public static void main(String[] args) {
    String question = "What is cardano?\n";
    question += "A. a place in Italy\n";
    question += "B. a dish using fish\n";
    question += "C. a blockchain protocol\n";
    question += "D. a monastery in Florence\n";
    question += "E. a type of food\n";

    while (true) {
        String answer = JOptionPane.showInputDialog(question);
        answer = answer.toUpperCase();
        if (answer.equals("C")) {
            JOptionPane.showMessageDialog(null, "Correct!");
            break;
        } else if (answer.equals("A") || answer.equals("B") || answer.equals("D") || answer.equals("E")) {
            JOptionPane.showMessageDialog(null, "Wrong. Please try again.");
        } else {
            JOptionPane.showMessageDialog(null, "Invalid answer. Please enter A, B, C, D, or E.");
        }
    }
}
</code>```

}

I need to Add a static method that asks a question until the user provides valid input.•Call the method "ask". It should take a String parameter and should return a String.
static String ask(String question).
How do I get the input to move to the method ask?

答:
You can create ask() method and return the input string you received from user.

Run your loop based on the answer. i.e. until answer is not equals to "C" in this case.

Finally invoke the ask() method at the end again to get the new input from the user

Repeat the same process until user inputs "C".

Below is the code:

```<code>answer = ask();

while (!answer.equalsIgnoreCase("C")) {

     if (answer.equals("A") || answer.equals("B") ||
         answer.equals("D") || answer.equals("E"))
             JOptionPane.showMessageDialog(null, "Wrong. Please try again.");
     else
         JOptionPane.showMessageDialog(null,
             "Invalid answer. Please enter A, B, C, D, or E.");

     answer = ask();
}

if (answer.equals("C"))
     JOptionPane.showMessageDialog(null, "Correct!");
</code>```

Body:
So I have this code:

import javax.swing.JOptionPane;

public class Quiz {
    public static void main(String[] args) {
    String question = "What is cardano?\n";
    question += "A. a place in Italy\n";
    question += "B. a dish using fish\n";
    question += "C. a blockchain protocol\n";
    question += "D. a monastery in Florence\n";
    question += "E. a type of food\n";

    while (true) {
        String answer = JOptionPane.showInputDialog(question);
        answer = answer.toUpperCase();
        if (answer.equals("C")) {
            JOptionPane.showMessageDialog(null, "Correct!");
            break;
        } else if (answer.equals("A") || answer.equals("B") || answer.equals("D") || answer.equals("E")) {
            JOptionPane.showMessageDialog(null, "Wrong. Please try again.");
        } else {
            JOptionPane.showMessageDialog(null, "Invalid answer. Please enter A, B, C, D, or E.");
        }
    }
}

}

I need to Add a static method that asks a question until the user provides valid input.•Call the method "ask". It should take a String parameter and should return a String.
static String ask(String question).
How do I get the input to move to the method ask?

Body:
You can create ask() method and return the input string you received from user.

Run your loop based on the answer. i.e. until answer is not equals to "C" in this case.

Finally invoke the ask() method at the end again to get the new input from the user

Repeat the same process until user inputs "C".

Below is the code:

answer = ask();

while (!answer.equalsIgnoreCase("C")) {

     if (answer.equals("A") || answer.equals("B") ||
         answer.equals("D") || answer.equals("E"))
             JOptionPane.showMessageDialog(null, "Wrong. Please try again.");
     else
         JOptionPane.showMessageDialog(null,
             "Invalid answer. Please enter A, B, C, D, or E.");

     answer = ask();
}

if (answer.equals("C"))
     JOptionPane.showMessageDialog(null, "Correct!");


问:
How to update input from dynamic select element
At the moment, I have a ng-repeat tied to a collection called vm.stations. When a button is pressed, it adds an item into the collection.

UI

```<code><div class="row" data-ng-repeat="station in vm.stations">
    <select ng-options="s.stationName for s in vm.nearbyStations"
            ng-model="vm.stations[$index].stationUID"
            class="form-control"
            ui-jq="selectpicker">
        <option value="">@L("NotSelected")</option>
    </select>
    <input field class="form-control text-right" type="number" step="1"
           min="0" ng-model="vm.stations[$index].distance">
    <input field class="form-control text-right" type="number" step="1"
           min="0" ng-model="vm.stations[$index].walkDuration">
</div>
</code>```

each station has distance and walk duration tied to it.

```<code>StationName: 'Test Station',

Distance: 15,

WalkDuration: 5
</code>```

My question is, when a station has been selected, how do i populate vm.stations[$index].distance and vm.stations[$index].walkDuration?

答:
Use the ng-change directive to update the station info:

```<code><div class="row" data-ng-repeat="station in vm.stations">
    <select ng-options="s.stationName for s in vm.nearbyStations"
            ng-model="vm.stations[$index].stationUID"
            ng-change=vm.updateStationInfo($index)"
            class="form-control"
            ui-jq="selectpicker">
        <option value="">@L("NotSelected")</option>
    </select>
    <input field class="form-control text-right" type="number" step="1"
           min="0" ng-model="vm.stations[$index].distance">
    <input field class="form-control text-right" type="number" step="1"
           min="0" ng-model="vm.stations[$index].walkDuration">
</div>
</code>```

vm.updateStationInfo = function(idx) {
    var station = vm.stations[idx];
    //...
    station.distance =     /* ... */;
    station.walkDuration = /* ... */;
};
```

For more information, see

AngularJS ng-change Directive API Reference

Body:
At the moment, I have a ng-repeat tied to a collection called vm.stations. When a button is pressed, it adds an item into the collection.

UI

    <select ng-options="s.stationName for s in vm.nearbyStations"
            ng-model="vm.stations[$index].stationUID"
            class="form-control"
            ui-jq="selectpicker">
        <option value="">@L("NotSelected")</option>
    </select>
    <input field class="form-control text-right" type="number" step="1"
           min="0" ng-model="vm.stations[$index].distance">
    <input field class="form-control text-right" type="number" step="1"
           min="0" ng-model="vm.stations[$index].walkDuration">

each station has distance and walk duration tied to it.

StationName: 'Test Station',

Distance: 15,

WalkDuration: 5

My question is, when a station has been selected, how do i populate vm.stations[$index].distance and vm.stations[$index].walkDuration?

Body:
Use the ng-change directive to update the station info:

<div class="row" data-ng-repeat="station in vm.stations">
    <select ng-options="s.stationName for s in vm.nearbyStations"
            ng-model="vm.stations[$index].stationUID"
            ng-change=vm.updateStationInfo($index)"
            class="form-control"
            ui-jq="selectpicker">
        <option value="">@L("NotSelected")</option>
    </select>
    <input field class="form-control text-right" type="number" step="1"
           min="0" ng-model="vm.stations[$index].distance">
    <input field class="form-control text-right" type="number" step="1"
           min="0" ng-model="vm.stations[$index].walkDuration">
</div>

vm.updateStationInfo = function(idx) {
    var station = vm.stations[idx];
    //...
    station.distance =     /* ... */;
    station.walkDuration = /* ... */;
};

For more information, see

AngularJS ng-change Directive API Reference


问:
When running the DAML sandbox an error occurs
The following error occurs when running the sandbox:

```<code>io.grpc.netty.NettyServerHandler onStreamError
WARNING: Stream Error
io.netty.handler.codec.http2.Http2Exception$HeaderListSizeException: Header size exceeded max allowed size (8192)
</code>```

What could the cause of this be?

答:
I have seen this error numerous times, and it is a consequence of having a transaction failure in a complex DAML model/transaction when running on the Sandbox. When you experience a transaction failure (fetch/exercise an inactive contract, lookupByKey returned a stale cid, head [], divide-by-zero, etc) the sandbox helpfully tries to provide transaction trace information in the error result.

This is normally fine for relatively simple models. With more complex models this trace can exceed the maximum header size producing the error you see. When this happens I have found the trace in the sandbox.log file, sometimes along with other errors that help explain what is going on.

The trace is an unformatted dump, so it can take a bit of effort to decode manually, but I have done it many times myself and the information I needed to identify the issue has always been there —— and to be honest, generally just knowing the choice I was exercising + the specific class of error is normally enough to point me in the right direction.

I believe there is some tooling being built to help with this sort of diagnosis; however, I don't know how advanced the work on that is.

Body:
The following error occurs when running the sandbox:

io.grpc.netty.NettyServerHandler onStreamError
WARNING: Stream Error
io.netty.handler.codec.http2.Http2Exception$HeaderListSizeException: Header size exceeded max allowed size (8192)

What could the cause of this be?


问:
React Hooks and localStorage dont set correct value
Hello I had an idea to make a hook to increase the font size and save preferences in localStorage
basically I have a state that goes from 1 to 4, and then when I click the button add I add +1 to the state until I reach number 4
and on the remove button I remove 1 from the state until 1

But I have doubts on how to save this to my location
basically if i don't use my useState just with getInitialValue It works normally.

like this gif, If I add the value manually it works:

but if I try to use my setFont I have problems (as it is saved in localStorage):

and i got this on localStorage :

code:

```<code>export default function App() {
  const { fontSize, setSize } = useFontSize();
  console.log(fontSize);
  return (
    <div className="App">
      <button
        onClick={() => {
          setSize(fontSize + 1);
        }}
      >
        add
      </button>
      <button
        onClick={() => {
          setSize(fontSize + 1);
        }}
      >
        remove
      </button>
    </div>
  );
}
</code>```

hook:

```<code>export default function useFontSize(defaultSize = { size: 1 }) {
  const [fontSize, _setSize] = useState(getInitialSize);
  function getInitialSize() {
    const savedSize = localStorage.getItem('_size_acessibility_font');
    const parsedSize = JSON.parse(savedSize);
    if (parsedSize) {
      const { size } = parsedSize;
      if (size >= 1 && size <= 4) {
        return size;
      }
    } else {
      return defaultSize.size;
    }
  }

  useEffect(() => {
    console.log(fontSize, 'on useEffect to set on localStorage');
    localStorage.setItem(
      '_size_acessibility_font',
      JSON.stringify({ size: fontSize }),
    );
  }, [fontSize]);

  return {
    fontSize,
    setSize: ({ setSize, ...size }) => {
      console.log(size, 'on function set size');
      if (size > 4) {
        return _setSize(4);
      }
      if (size < 1) {
        return _setSize(1);
      }
      return _setSize(size);
    },
  };
}
</code>```

example:

https://codesandbox.io/s/focused-newton-x0mqd

I don't know if this is the best logic for this context, if someone can help me.

答:
This seems a tad overengineered and upsets a few hooks idioms. For example, returning a named object pair for a hook is less typical than an array pair. The set function itself is complex and returns the result of the _setSize calls. Naming could be clearer if fontSize matched setSize by using setFontSize.

({ setSize, ...size }) is problematic since the caller is (correctly) providing an integer.

Here's a minimal, complete version that fixes these issues (local storage is mocked since Stack Snippets is sandboxed):

const localStorageMock = (() => {
  const storage = {};
  return {
    getItem: k => storage[k],
    setItem: (k, v) => {storage[k] = v.toString();}
  };
})();

const {useState, useEffect} = React;

const useFontSize = (defaultSize=1) => {
  const clamp = (n, lo=1, hi=4) => Math.min(hi, Math.max(n, lo));
  const clean = n => isNaN(n) ? defaultSize : clamp(+n);
  const storageName = "_size_acessibility_font";
  const fromStorage = clean(localStorageMock.getItem(storageName));
  const [fontSize, setFontSize] = useState(fromStorage);

  useEffect(() => {
    localStorageMock.setItem(storageName, fontSize);
  }, [fontSize]);

  return [fontSize, size => setFontSize(clean(size))];
};

const App = () => {
  const [fontSize, setFontSize] = useFontSize();
  return (

Font size: {fontSize}

      <button onClick={() => setFontSize(fontSize + 1)}>
        +
      </button>
      <button onClick={() => setFontSize(fontSize - 1)}>
        -
      </button>

  );
};

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<App />);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

Body:
Hello I had an idea to make a hook to increase the font size and save preferences in localStorage
basically I have a state that goes from 1 to 4, and then when I click the button add I add +1 to the state until I reach number 4
and on the remove button I remove 1 from the state until 1

But I have doubts on how to save this to my location
basically if i don't use my useState just with getInitialValue It works normally.

like this gif, If I add the value manually it works:

but if I try to use my setFont I have problems (as it is saved in localStorage):

and i got this on localStorage :

code:

export default function App() {
  const { fontSize, setSize } = useFontSize();
  console.log(fontSize);
  return (

      <button
        onClick={() => {
          setSize(fontSize + 1);
        }}
      >
        add
      </button>
      <button
        onClick={() => {
          setSize(fontSize + 1);
        }}
      >
        remove
      </button>

  );
}

hook:

export default function useFontSize(defaultSize = { size: 1 }) {
  const [fontSize, _setSize] = useState(getInitialSize);
  function getInitialSize() {
    const savedSize = localStorage.getItem('_size_acessibility_font');
    const parsedSize = JSON.parse(savedSize);
    if (parsedSize) {
      const { size } = parsedSize;
      if (size >= 1 && size <= 4) {
        return size;
      }
    } else {
      return defaultSize.size;
    }
  }

  useEffect(() => {
    console.log(fontSize, 'on useEffect to set on localStorage');
    localStorage.setItem(
      '_size_acessibility_font',
      JSON.stringify({ size: fontSize }),
    );
  }, [fontSize]);

  return {
    fontSize,
    setSize: ({ setSize, ...size }) => {
      console.log(size, 'on function set size');
      if (size > 4) {
        return _setSize(4);
      }
      if (size < 1) {
        return _setSize(1);
      }
      return _setSize(size);
    },
  };
}

example:

https://codesandbox.io/s/focused-newton-x0mqd

I don't know if this is the best logic for this context, if someone can help me.

Body:
This seems a tad overengineered and upsets a few hooks idioms. For example, returning a named object pair for a hook is less typical than an array pair. The set function itself is complex and returns the result of the _setSize calls. Naming could be clearer if fontSize matched setSize by using setFontSize.

({ setSize, ...size }) is problematic since the caller is (correctly) providing an integer.

Here's a minimal, complete version that fixes these issues (local storage is mocked since Stack Snippets is sandboxed):

const localStorageMock = (() => {
  const storage = {};
  return {
    getItem: k => storage[k],
    setItem: (k, v) => {storage[k] = v.toString();}
  };
})();

const {useState, useEffect} = React;

const useFontSize = (defaultSize=1) => {
  const clamp = (n, lo=1, hi=4) => Math.min(hi, Math.max(n, lo));
  const clean = n => isNaN(n) ? defaultSize : clamp(+n);
  const storageName = "_size_acessibility_font";
  const fromStorage = clean(localStorageMock.getItem(storageName));
  const [fontSize, setFontSize] = useState(fromStorage);

  useEffect(() => {
    localStorageMock.setItem(storageName, fontSize);
  }, [fontSize]);

  return [fontSize, size => setFontSize(clean(size))];
};

const App = () => {
  const [fontSize, setFontSize] = useFontSize();
  return (
    <div>
      <div>Font size: {fontSize}</div>
      <button onClick={() => setFontSize(fontSize + 1)}>
        +
      </button>
      <button onClick={() => setFontSize(fontSize - 1)}>
        -
      </button>
    </div>
  );
};

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<App />);

<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div>


问:
How do I inherit private member variables and public functions from another file?
I'm trying to call a function insertBack(newVal) from container.cpp inside the Stack.cpp file, but the compiler throws an error: identifier "insertBack" is undefined. Also, trying to do the same thing for a variable n which is found in the same file but under the private area--the error is the same: identifier "n" is undefined.

This is my first time doing multiple file compilation and inheritance.

Stack.cpp

#include "pch.h"
#include "Stack.h"
#include "container.h"

Stack::Stack()
{
    container();
}

bool Stack::push(int newVal)
{
    return insertBack(newVal);
}

void Stack::pop()
{
    --n;
}
```

<p><strong>container.h</strong></p>

<pre class="lang-cpp prettyprint-override"><code>#ifndef CONTAINER_H
#define CONTAINER_H

#pragma once
#include <iostream>

class container
{
public:
    container();
    // Postcondition: data member n is initialized to -1 and all elements in the empty arr array are initialized to zero
    bool insertBack(int val);
    //  Precondition: the container object is not full
    // Postcondition: if arr array is not full, n is incremented by 1; returns true with val is inserted at the end of the arr array
    //                 Otherwise, returns false; the value is not inserted and program execution continues.

private:
    static const int CAPACITY = 10;     // physical size of the arr array or the storage capacity of a container object
    int arr[CAPACITY];          // arr array can store up to CAPACITY  (10 in our case) integers
    int n;                      // n is used as the subscript for the arr array. n is initialized to -1 for an empty array
                                // Each time a new value is inserted into the arr array, n must first be incremented
                                // by 1. Since n has been initialized to -1, the first inserted value is stored in arr[0],
                                // and the 2nd inserted value will be in arr[1], etc.  and the nth inserted value will be
                                // stored in arr[n – 1]. Obviously, n + 1 represents the actual number of elements
                                // stored in the array after n rounds of insertion.
};

#endif
</code>```

Stack.h

#ifndef STACK_H
#define STACK_H

#pragma once
#include <iostream>

class Stack
{
public:
    Stack();
    // Postcondition: an empty stack object is created (with n initialized to -1 as in P1)
    bool push(int newVal);
    // Postcondition: if the stack is full, returns false. Otherwise, returns true; also the newVal is pushed onto the stack
    //                 and the stack size is incremented by 1
    void pop();
    //  Precondition: the Stack must not be empty or this function will not be called
    // Postcondition: the object (an integer value) on top of the Stack is logically popped or deleted,  3) and Stack size is decremented by 1
};

#endif
```

答:
From the contents of the Stack constructor, I conclude that you want Stack to inherit from container. Stack.h already includes container.h, so the container class is visible anywhere where Stack is visible.

What you have to do is declare the actual inheritance:

```<code>class Stack : container
</code>```

You will get some compiler errors (for one thing, the container constructor is private), but that's a story for another day.

Body:
I'm trying to call a function insertBack(newVal) from container.cpp inside the Stack.cpp file, but the compiler throws an error: identifier "insertBack" is undefined. Also, trying to do the same thing for a variable n which is found in the same file but under the private area--the error is the same: identifier "n" is undefined.

This is my first time doing multiple file compilation and inheritance.

Stack.cpp

#include "pch.h"
#include "Stack.h"
#include "container.h"

Stack::Stack()
{
    container();
}

bool Stack::push(int newVal)
{
    return insertBack(newVal);
}

void Stack::pop()
{
    --n;
}

container.h

#ifndef CONTAINER_H
#define CONTAINER_H

#pragma once
#include <iostream>

class container
{
public:
    container();
    // Postcondition: data member n is initialized to -1 and all elements in the empty arr array are initialized to zero
    bool insertBack(int val);
    //  Precondition: the container object is not full
    // Postcondition: if arr array is not full, n is incremented by 1; returns true with val is inserted at the end of the arr array
    //                 Otherwise, returns false; the value is not inserted and program execution continues.

private:
    static const int CAPACITY = 10;     // physical size of the arr array or the storage capacity of a container object
    int arr[CAPACITY];          // arr array can store up to CAPACITY  (10 in our case) integers
    int n;                      // n is used as the subscript for the arr array. n is initialized to -1 for an empty array
                                // Each time a new value is inserted into the arr array, n must first be incremented
                                // by 1. Since n has been initialized to -1, the first inserted value is stored in arr[0],
                                // and the 2nd inserted value will be in arr[1], etc.  and the nth inserted value will be
                                // stored in arr[n – 1]. Obviously, n + 1 represents the actual number of elements
                                // stored in the array after n rounds of insertion.
};

#endif

Stack.h

#ifndef STACK_H
#define STACK_H

#pragma once
#include <iostream>

class Stack
{
public:
    Stack();
    // Postcondition: an empty stack object is created (with n initialized to -1 as in P1)
    bool push(int newVal);
    // Postcondition: if the stack is full, returns false. Otherwise, returns true; also the newVal is pushed onto the stack
    //                 and the stack size is incremented by 1
    void pop();
    //  Precondition: the Stack must not be empty or this function will not be called
    // Postcondition: the object (an integer value) on top of the Stack is logically popped or deleted,  3) and Stack size is decremented by 1
};

#endif

Body:
From the contents of the Stack constructor, I conclude that you want Stack to inherit from container. Stack.h already includes container.h, so the container class is visible anywhere where Stack is visible.

What you have to do is declare the actual inheritance:

class Stack : container

You will get some compiler errors (for one thing, the container constructor is private), but that's a story for another day.


问:
How do you build a C program that includes the entry point on Mac OS X?
How do you build a C program that includes the entry point on Mac OS X?

I want to build:

```<code>start() {
    /* exit system call */
    asm("movl $1,%eax;"
        "xorl %ebx,%ebx;"
        "int  $0x80"
    );
}
</code>```

but when I run:

```<code>gcc -nostdlib min.c
</code>```

I always get:

```<code>ld: could not find entry point "start" (perhaps missing crt1.o)
collect2: ld returned 1 exit status
</code>```

The one other attempt I made just to see what it was doing was run:

```<code>gcc -nostdlib -c min.c && otool -tV min.o
</code>```

And the output was:

```<code>(__TEXT,__text) section
_start:
0000000000000000    pushq   %rbp
0000000000000001    movq    %rsp,%rbp
0000000000000004    leave
0000000000000005    ret
</code>```

So where did that underscore come from before the "start" function? How do I prevent that from happening? Or more simply:

How do you build a C program that includes the entry point on Mac OS X?

Thanks,
CrazyChenz

答:
You can control the symbol that gcc gives to the function by declaring it separately with asm:

```<code>void start() asm ("start");
</code>```

Make sure this is a standalone declaration, separate from the function definition.

You can read more details about controlling the generated symbol here: https://stackoverflow.com/a/1035937/12928775

Also, as Peter Cordes points out, you should probably include __attribute__((naked)) on the function definition to prevent gcc from generating a stack frame on entry.

The full code would be:

```<code>void start() asm ("start");

__attribute__((naked)) void start() {
    /* exit system call */
    asm("movl $1,%eax;"
        "xorl %ebx,%ebx;"
        "int  $0x80"
    );
}
</code>```

Body:
How do you build a C program that includes the entry point on Mac OS X?

I want to build:

start() {
    /* exit system call */
    asm("movl $1,%eax;"
        "xorl %ebx,%ebx;"
        "int  $0x80"
    );
}

but when I run:

gcc -nostdlib min.c

I always get:

ld: could not find entry point "start" (perhaps missing crt1.o)
collect2: ld returned 1 exit status

The one other attempt I made just to see what it was doing was run:

gcc -nostdlib -c min.c && otool -tV min.o

And the output was:

(__TEXT,__text) section
_start:
0000000000000000    pushq   %rbp
0000000000000001    movq    %rsp,%rbp
0000000000000004    leave
0000000000000005    ret

So where did that underscore come from before the "start" function? How do I prevent that from happening? Or more simply:

How do you build a C program that includes the entry point on Mac OS X?

Thanks,
CrazyChenz

Body:
You can control the symbol that gcc gives to the function by declaring it separately with asm:

void start() asm ("start");

Make sure this is a standalone declaration, separate from the function definition.

You can read more details about controlling the generated symbol here: https://stackoverflow.com/a/1035937/12928775

Also, as Peter Cordes points out, you should probably include __attribute__((naked)) on the function definition to prevent gcc from generating a stack frame on entry.

The full code would be:

void start() asm ("start");

__attribute__((naked)) void start() {
    /* exit system call */
    asm("movl $1,%eax;"
        "xorl %ebx,%ebx;"
        "int  $0x80"
    );
}


问:
'urllib' on an infinite loop
For a while, i have been trying to use cloud9 to give me an extra hand on repetitive tasks on my job. However, the majority of those tasks have web scraping involved, and I am having a hard time using the urllib library.

It does not work even for simple codes. It keeps running forever, and I can't find the reasons for that. I will appreciate some tips...

```<code>from urllib.request import urlopen
import json
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = ('Enter - ')
html = urlopen(url, context=ctx).read()
str_data = open(html).read()
json_data = json.loads(str_data)

for entry in json_data:

name = entry[0];
    title = entry[1];
    print((name, title))
</code>```

答:
Do yourself a favor and replace that with Requests. Your example simplifies to:

import requests

url = "..."
json_data = requests.get(url).json()

for entry in json_data:
    name = entry[0]
    title = entry[1]
    print(name, title)
```

That also removes a whole awful lot of potential for mistakes from your code.

Title: 'urllib' on an infinite loop

Body:
For a while, i have been trying to use cloud9 to give me an extra hand on repetitive tasks on my job. However, the majority of those tasks have web scraping involved, and I am having a hard time using the urllib library.

It does not work even for simple codes. It keeps running forever, and I can't find the reasons for that. I will appreciate some tips...

from urllib.request import urlopen
import json
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = ('Enter - ')
html = urlopen(url, context=ctx).read()
str_data = open(html).read()
json_data = json.loads(str_data)

for entry in json_data:

name = entry[0];
    title = entry[1];
    print((name, title))

Body:
Do yourself a favor and replace that with Requests. Your example simplifies to:

import requests

url = "..."
json_data = requests.get(url).json()

for entry in json_data:
    name = entry[0]
    title = entry[1]
    print(name, title)

That also removes a whole awful lot of potential for mistakes from your code.


问:
Can't get Extra data via Intent
I'm trying to put extra data (string) in an intent. I use startActivity to get my extra string data on the other side.
But I can't get why it doesn't work! Here's my code :
This is the destination Activity from where I want to parse my extra data -- Recipe Activity :

```<code>class RecipeActivity : AppCompatActivity() {
    for (k in 0..name_arr.size-1) {
        if(temp_arr[position]==name_arr[k]){
            //to parse the id number of the selected recipe by the user to the next activity
            val i = Intent(baseContext, ResRecActivity::class.java)
            i.putExtra("ItemPosition",k)
            startActivity(i)
        }
    }
}
</code>```

This is the Target Activity for successful parsing of extra data -- ResRecActivity :

```<code>class ResRecActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_res_rec)
        setSupportActionBar(toolbar)

        var posit : String = intent.getStringExtra("ItemPosition") //wanting to get the extra data

        //BELOW LINE IS THE ERROR LINE
        *readJson(posit.toInt())* //Intending to parse the extra data in Integer datatype to readJson Function
    }
}
</code>```

Error that I am getting is :

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testarca/com.example.arca.ResRecActivity}: kotlin.KotlinNullPointerException
    Caused by: *kotlin.KotlinNullPointerException*
        at com.example.arca.ResRecActivity.onCreate(ResRecActivity.kt:37)
</code>```

Main Aim :
I just want to parse the Integer "position" (in my case "k") from "RecipeActivity" to "ResRecActivity", for using that integer position in another function named "readJson" as a parameter to the function.
And I am trying to achieve that using Intent property for Handling between the activities.

Note: Also give me a similar solution to parse an ArrayList data from one activity to another using intent.

答:
First

replace this line

```<code>val i = Intent(baseContext, ResRecActivity::class.java)
</code>```

with

```<code> val i = Intent(this, ResRecActivity::class.java)
</code>```

Second

You put Int in intent, so you should use intent.getIntExtra("ItemPosition", -1)

Hope this helps.

Title: Can't get Extra data via Intent

Body:
I'm trying to put extra data (string) in an intent. I use startActivity to get my extra string data on the other side.
But I can't get why it doesn't work! Here's my code :
This is the destination Activity from where I want to parse my extra data -- Recipe Activity :

class RecipeActivity : AppCompatActivity() {
    for (k in 0..name_arr.size-1) {
        if(temp_arr[position]==name_arr[k]){
            //to parse the id number of the selected recipe by the user to the next activity
            val i = Intent(baseContext, ResRecActivity::class.java)
            i.putExtra("ItemPosition",k)
            startActivity(i)
        }
    }
}

This is the Target Activity for successful parsing of extra data -- ResRecActivity :

class ResRecActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_res_rec)
        setSupportActionBar(toolbar)

        var posit : String = intent.getStringExtra("ItemPosition") //wanting to get the extra data

        //BELOW LINE IS THE ERROR LINE
        *readJson(posit.toInt())* //Intending to parse the extra data in Integer datatype to readJson Function
    }
}

Error that I am getting is :

E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testarca/com.example.arca.ResRecActivity}: kotlin.KotlinNullPointerException
    Caused by: *kotlin.KotlinNullPointerException*
        at com.example.arca.ResRecActivity.onCreate(ResRecActivity.kt:37)

Main Aim :
I just want to parse the Integer "position" (in my case "k") from "RecipeActivity" to "ResRecActivity", for using that integer position in another function named "readJson" as a parameter to the function.
And I am trying to achieve that using Intent property for Handling between the activities.

Note: Also give me a similar solution to parse an ArrayList data from one activity to another using intent.

Body:
First

replace this line

val i = Intent(baseContext, ResRecActivity::class.java)

with

 val i = Intent(this, ResRecActivity::class.java)

Second

You put Int in intent, so you should use intent.getIntExtra("ItemPosition", -1)

Hope this helps.


问:
GET or POST when reading request body
Should I use the GET or POST method when sending information to a server in the body of the HTTP request?  There are no query parameters appended to the URL, the server will inspect the body of the request for what it needs.</p>

答:
GET extracts parameters from the request URL. POST extracts parameters from the request body.

So you need POST.

Title: GET or POST when reading request body


问:
Powershell Script that recursively searches for specific file and containing directory and copy it to another location
I'm attempting to write a powershell script that will search recursively for a file and copy it to another location on a local drive with the date appended to it.

However that file could be in multiple different directories. (ex. c:\users\default\Bookmark.txt, c:\users\profile1\Bookmark.txt, c:\users\profile2\Bookmark.txt...etc.)

To distinguish between the different directories I was thinking of appending the directory name containing the file to the filename along with the date. (ex. filename-directoryName-date)

Here is what I have so far:

```<code>get-childitem -path "$env:userprofile\AppData\Local\Microsoft\Edge\User Data" -filter Bookmarks -Recurse -ErrorAction SilentlyContinue -Force | copy-item -Destination $env:userprofile\Bookmarks-$(get-date -UFormat %d-%m-%Y)
</code>```

This works if it only finds 1 copy of the Bookmarks file and it only appends the date.

To figure out the names of the containing folders I used this command.

```<code>(get-childitem -path "$env:userprofile\AppData\Local\Microsoft\Edge\User Data" -filter Bookmarks -Recurse -ErrorAction SilentlyContinue -Force).Directory.Name
</code>```

I need to somehow put this two together and so it outputs :

c:(whateverlocation)\Bookmark-DirectoryName-Date

I hope I'm making sense.

答:
Dan,

When you use the Get-ChildItem command (alias gci) it will return to you an array of DirectoryInfo and FileInfo objects, one for each item it finds.  If you are looking for files called "Bookmarks" (or bookmark.txt...can't tell from your examples which one you're looking for) then you can use the following command to get you a list of all of them:

```<code>[array]$FileList = gci -Recurse -File -Filter "Bookmarks"
</code>```

The [array] designation is necessary to be sure the object is an array regardless of how many items are returned. The filter can have wildcards if you don't know the exact filename.  What that leaves me with is an array object named $FileList containing all of the information about the files.  You can read all about the properties and methods available in these objects at this Microsoft help page.

For this task, we'll need the .FullName property, which tells you the full path & name of each item (which can be used as your source) and the .BaseName & .Extension properties, which give you the filename and extension respectively.  Using these properties, you can copy each of the files you find to a destination.  Putting it all together, you get something like this:

```<code>$SourceFolder = "$($env:userprofile)\AppData\Local\Microsoft\Edge\User Data"
$DestFolder = '' #Path to Destination Folder
[array]$FileList = gci -Path $SourceFolder -Recurse -File -Filter "Bookmarks"
ForEach ($F in $FileList) {
    Copy-Item $F.FullName (Join-Path $DestFolder ($F.Name + 'stuff to add to end of filename' + $F.Extension))
}
</code>```

In this case, since the files are named 'Bookmarks', the $F.Extension should be blank.  If using a more traditional filename, the pattern above will help you fit your changes in between the filename and the extension.

Hope this helps you out.  If it does, please accept the answer using the check mark on the left.

Body:
I'm attempting to write a powershell script that will search recursively for a file and copy it to another location on a local drive with the date appended to it.

However that file could be in multiple different directories. (ex. c:\users\default\Bookmark.txt, c:\users\profile1\Bookmark.txt, c:\users\profile2\Bookmark.txt...etc.)

To distinguish between the different directories I was thinking of appending the directory name containing the file to the filename along with the date. (ex. filename-directoryName-date)

Here is what I have so far:

get-childitem -path "$env:userprofile\AppData\Local\Microsoft\Edge\User Data" -filter Bookmarks -Recurse -ErrorAction SilentlyContinue -Force | copy-item -Destination $env:userprofile\Bookmarks-$(get-date -UFormat %d-%m-%Y)

This works if it only finds 1 copy of the Bookmarks file and it only appends the date.

To figure out the names of the containing folders I used this command.

(get-childitem -path "$env:userprofile\AppData\Local\Microsoft\Edge\User Data" -filter Bookmarks -Recurse -ErrorAction SilentlyContinue -Force).Directory.Name

I need to somehow put this two together and so it outputs :

c:(whateverlocation)\Bookmark-DirectoryName-Date

I hope I'm making sense.

Body:
Dan,

When you use the Get-ChildItem command (alias gci) it will return to you an array of DirectoryInfo and FileInfo objects, one for each item it finds.  If you are looking for files called "Bookmarks" (or bookmark.txt...can't tell from your examples which one you're looking for) then you can use the following command to get you a list of all of them:

[array]$FileList = gci -Recurse -File -Filter "Bookmarks"

The [array] designation is necessary to be sure the object is an array regardless of how many items are returned. The filter can have wildcards if you don't know the exact filename.  What that leaves me with is an array object named $FileList containing all of the information about the files.  You can read all about the properties and methods available in these objects at this Microsoft help page.

For this task, we'll need the .FullName property, which tells you the full path & name of each item (which can be used as your source) and the .BaseName & .Extension properties, which give you the filename and extension respectively.  Using these properties, you can copy each of the files you find to a destination.  Putting it all together, you get something like this:

$SourceFolder = "$($env:userprofile)\AppData\Local\Microsoft\Edge\User Data"
$DestFolder = '' #Path to Destination Folder
[array]$FileList = gci -Path $SourceFolder -Recurse -File -Filter "Bookmarks"
ForEach ($F in $FileList) {
    Copy-Item $F.FullName (Join-Path $DestFolder ($F.Name + 'stuff to add to end of filename' + $F.Extension))
}

In this case, since the files are named 'Bookmarks', the $F.Extension should be blank.  If using a more traditional filename, the pattern above will help you fit your changes in between the filename and the extension.

Hope this helps you out.  If it does, please accept the answer using the check mark on the left.


问:
SQL where last n records for each id meet a certain criteria
This question was the closest I have found to my problem but it still doesn't solve it.

I have a (simplified) table like:

```<code>ID  Value   Date
1   CCC     2013-09-06
1   CCC     2015-07-13
1   AAA     2015-10-15
1   AAA     2015-10-29
1   AAA     2015-11-17
1   AAA     2015-12-22
2   AAA     2019-11-01
3   BBB     2017-10-02
3   AAA     2017-12-21
3   AAA     2018-01-18
3   AAA     2018-02-20
3   AAA     2018-03-20
3   AAA     2018-05-16
3   AAA     2018-08-15
3   AAA     2018-11-14
</code>```

I'd like to have the IDs that have the value AAA on the last five entries by date.
In my example, the result would be

```<code>ID
--
3
</code>```

ID 1 does not meet the criteria because when ordered by date, one of the last four entries are not 'AAA'.

ID 2 does not meet the criteria because although it's last value is AAA, it does not even at least 5 entries (only 1)

I have tried dividing my problem in different steps, first identifiying all IDs that have at least 5 records, with a simple select TOP 5 ordered by date DESC.
I have also succeeded in finding all records that have at least five 'AAA' values, using COUNT, GROUP BY and HAVING.

But I have been unable to take into account if those records found are the last five by date.

I appreciate any help/tips.

答:
Based on the requirement of last 5 or more records check. If we have continuous rows for 'AAA' and then 'CCC' or anything other, we need to make sure that we are comparing the table to make sure that there is no other values.</p>

```<code>     with cte as (
select 1 as ID, '2019-02' as Date, 'AAA' as Value union all
select 1 as ID, '2019-03' as Date, 'AAA' as Value union all
select 1 as ID, '2019-04' as Date, 'AAA' as Value union all
select 1 as ID, '2019-01' as Date, 'BBB' as Value union all
select 1 as ID, '2019-06' as Date, 'CCC' as Value union all
select 1 as ID, '2019-07' as Date, 'AAA' as Value union all
select 1 as ID, '2019-08' as Date, 'AAA' as Value union all
select 1 as ID, '2019-09' as Date, 'AAA' as Value union all
select 1 as ID, '2019-10' as Date, 'AAA' as Value union all
select 1 as ID, '2019-11' as Date, 'CCC' as Value union all
select 2 as ID, '2019-05' as Date, 'AAA' as Value union all
select 2 as ID, '2019-07' as Date, 'BBB' as Value union all
select 2 as ID, '2019-03' as Date, 'AAA' as Value union all
select 2 as ID, '2019-08' as Date, 'AAA' as Value union all
select 2 as ID, '2019-09' as Date, 'AAA' as Value union all
select 2 as ID, '2019-10' as Date, 'AAA' as Value union all
select 2 as ID, '2019-11' as Date, 'AAA' as Value union all
select 2 as ID, '2019-12' as Date, 'AAA' as Value union all
select 3 as ID, '2019-02' as Date, 'CCC' as Value union all
select 3 as ID, '2019-03' as Date, 'AAA' as Value union all
select 3 as ID, '2019-02' as Date, 'BBB' as Value union all
select 3 as ID, '2019-04' as Date, 'AAA' as Value union all
select 3 as ID, '2019-05' as Date, 'AAA' as Value union all
select 3 as ID, '2019-06' as Date, 'AAA' as Value union all
select 3 as ID, '2019-07' as Date, 'AAA' as Value union all
select 3 as ID, '2019-08' as Date, 'AAA' as Value
 )

    select ID
 from  cte  z
  where not exists (Select 1 from cte c where z.id = c.id and z.Date < c.Date and c.Value <> 'AAA')
 group by ID
 having count(case when Value = 'AAA' then 1 end  ) >=5

Output:
ID

3
</code>```

Body:
This question was the closest I have found to my problem but it still doesn't solve it.

I have a (simplified) table like:

ID  Value   Date
1   CCC     2013-09-06
1   CCC     2015-07-13
1   AAA     2015-10-15
1   AAA     2015-10-29
1   AAA     2015-11-17
1   AAA     2015-12-22
2   AAA     2019-11-01
3   BBB     2017-10-02
3   AAA     2017-12-21
3   AAA     2018-01-18
3   AAA     2018-02-20
3   AAA     2018-03-20
3   AAA     2018-05-16
3   AAA     2018-08-15
3   AAA     2018-11-14

I'd like to have the IDs that have the value AAA on the last five entries by date.
In my example, the result would be

ID
--
3

ID 1 does not meet the criteria because when ordered by date, one of the last four entries are not 'AAA'.

ID 2 does not meet the criteria because although it's last value is AAA, it does not even at least 5 entries (only 1)

I have tried dividing my problem in different steps, first identifiying all IDs that have at least 5 records, with a simple select TOP 5 ordered by date DESC.
I have also succeeded in finding all records that have at least five 'AAA' values, using COUNT, GROUP BY and HAVING.

But I have been unable to take into account if those records found are the last five by date.

I appreciate any help/tips.

Body:
Based on the requirement of last 5 or more records check. If we have continuous rows for 'AAA' and then 'CCC' or anything other, we need to make sure that we are comparing the table to make sure that there is no other values.

     with cte as (
select 1 as ID, '2019-02' as Date, 'AAA' as Value union all
select 1 as ID, '2019-03' as Date, 'AAA' as Value union all
select 1 as ID, '2019-04' as Date, 'AAA' as Value union all
select 1 as ID, '2019-01' as Date, 'BBB' as Value union all
select 1 as ID, '2019-06' as Date, 'CCC' as Value union all
select 1 as ID, '2019-07' as Date, 'AAA' as Value union all
select 1 as ID, '2019-08' as Date, 'AAA' as Value union all
select 1 as ID, '2019-09' as Date, 'AAA' as Value union all
select 1 as ID, '2019-10' as Date, 'AAA' as Value union all
select 1 as ID, '2019-11' as Date, 'CCC' as Value union all
select 2 as ID, '2019-05' as Date, 'AAA' as Value union all
select 2 as ID, '2019-07' as Date, 'BBB' as Value union all
select 2 as ID, '2019-03' as Date, 'AAA' as Value union all
select 2 as ID, '2019-08' as Date, 'AAA' as Value union all
select 2 as ID, '2019-09' as Date, 'AAA' as Value union all
select 2 as ID, '2019-10' as Date, 'AAA' as Value union all
select 2 as ID, '2019-11' as Date, 'AAA' as Value union all
select 2 as ID, '2019-12' as Date, 'AAA' as Value union all
select 3 as ID, '2019-02' as Date, 'CCC' as Value union all
select 3 as ID, '2019-03' as Date, 'AAA' as Value union all
select 3 as ID, '2019-02' as Date, 'BBB' as Value union all
select 3 as ID, '2019-04' as Date, 'AAA' as Value union all
select 3 as ID, '2019-05' as Date, 'AAA' as Value union all
select 3 as ID, '2019-06' as Date, 'AAA' as Value union all
select 3 as ID, '2019-07' as Date, 'AAA' as Value union all
select 3 as ID, '2019-08' as Date, 'AAA' as Value
 )

    select ID
 from  cte  z
  where not exists (Select 1 from cte c where z.id = c.id and z.Date < c.Date and c.Value <> 'AAA')
 group by ID
 having count(case when Value = 'AAA' then 1 end  ) >=5

Output:
ID

3


问:
Clang cindex can't find header in unsaved_files
I'm trying to use clang.cindex in Python, but when I try to pass in a dummy header, it doesn't work:

```<code>import sys
from clang import cindex
tu = cindex.Index.create().parse('t.cc', args=[], unsaved_files=[
    ('t.h', ''),
    ('t.cc', '#include "t.h"'),
])
for diag in tu.diagnostics:
    sys.stderr.write(diag.format() + "\n")
</code>```

The error I receive is:

```<code>t.cc:1:10: fatal error: 't.h' file not found
</code>```

What is going on? Why can it find t.cc but not t.h?

答:
It turns out this is due to the lack of a ./ prefix. Apparently paths aren't canonicalized.

This works fine:

```<code>import sys
from clang import cindex
tu = cindex.Index.create().parse('./t.cc', args=[], unsaved_files=[
    ('./t.h', ''),
    ('./t.cc', '#include "t.h"'),
])
for diag in tu.diagnostics:
    sys.stderr.write(diag.format() + "\n")
</code>```

Body:
I'm trying to use clang.cindex in Python, but when I try to pass in a dummy header, it doesn't work:

import sys
from clang import cindex
tu = cindex.Index.create().parse('t.cc', args=[], unsaved_files=[
    ('t.h', ''),
    ('t.cc', '#include "t.h"'),
])
for diag in tu.diagnostics:
    sys.stderr.write(diag.format() + "\n")

The error I receive is:

t.cc:1:10: fatal error: 't.h' file not found

What is going on? Why can it find t.cc but not t.h?

Body:
It turns out this is due to the lack of a ./ prefix. Apparently paths aren't canonicalized.

This works fine:

import sys
from clang import cindex
tu = cindex.Index.create().parse('./t.cc', args=[], unsaved_files=[
    ('./t.h', ''),
    ('./t.cc', '#include "t.h"'),
])
for diag in tu.diagnostics:
    sys.stderr.write(diag.format() + "\n")


问:
pairing one picture to multiple pictures in folder
I have some pictures in the folder I want to pair so I can add them to my slide with iterative fashion. I want to pair pictures ending with mp ones to bp ones. One caveat is that there are multiple pictures ending with bp and bp so that adding logical check would be feasible.

lets say we have a pictures in the folder

I want to pair 1_birds_bp.png to other pictures starting with 1 and ending with mp

so that the pair should look like #expected result

```<code>('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_hawk_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_owl_mp.png')
</code>```

and for reptile group

```<code>('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_crocodile_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_snake_mp.png')
</code>```

So by following this post
I tried

```<code>def image_pairs(folder):
    bp, mp = [], []

    for image_path in glob.glob(folder + '/*.png'):
        if "bp" in image_path:
            bp.append(image_path)

        elif "mp" in image_path:
            mp.append(image_path)
    for pair in zip(bp, mp):
        print(pair)
        #yield pair
</code>```

but I can pair the only

```<code>('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\1_hawk_mp.png')
</code>```

how can achieve this ?

答:
I like @xletmjm's approach, although pathlib is only available in Python >= 3.4.

Here's an alternate approach that works with what you've used so far.

```<code>import glob

class Path(object):
    def __init__(self, path):
        self._path = path

    @property
    def stem(self):
        """The "base" part of the filename, without the extension."""
        return ".".join(self.filename.split(".")[:-1])

    @property
    def filename(self):
        return self._path.split("/")[-1]

    @property
    def filename_prefix(self):
        return self.stem.split("_")[0]

    @property
    def filename_suffix(self):
        return self.stem.split("_")[-1]

    @property
    def path(self):
        return self._path

def iter_bp_paths(paths):
    """Generate each Path object in `paths` with filename having "_bp" suffix."""
    return (p for p in paths if p.filename_suffix == "bp")

def iter_mp_paths(paths, prefix):
    """Generate each Path object in `paths` with `prefix` and "mp" suffix."""
    return (
        p for p in paths if p.filename_prefix == prefix and p.filename_suffix == "mp"
    )

if __name__ == "__main__":
    paths = [Path(path) for path in glob.glob("/Users/you/tmp/*.png")]
    for bp_path in iter_bp_paths(paths):
        for mp_path in iter_mp_paths(paths, bp_path.filename_prefix):
            print(bp_path.path, mp_path.path)

</code>```

Body:
I have some pictures in the folder I want to pair so I can add them to my slide with iterative fashion. I want to pair pictures ending with mp ones to bp ones. One caveat is that there are multiple pictures ending with bp and bp so that adding logical check would be feasible.

lets say we have a pictures in the folder

I want to pair 1_birds_bp.png to other pictures starting with 1 and ending with mp

so that the pair should look like #expected result

('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_hawk_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_owl_mp.png')

and for reptile group

('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_crocodile_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_snake_mp.png')

So by following this post
I tried

def image_pairs(folder):
    bp, mp = [], []

    for image_path in glob.glob(folder + '/*.png'):
        if "bp" in image_path:
            bp.append(image_path)

        elif "mp" in image_path:
            mp.append(image_path)
    for pair in zip(bp, mp):
        print(pair)
        #yield pair

but I can pair the only

('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\1_hawk_mp.png')

how can achieve this ?

Body:
I like @xletmjm's approach, although pathlib is only available in Python >= 3.4.

Here's an alternate approach that works with what you've used so far.

import glob

class Path(object):
    def __init__(self, path):
        self._path = path

    @property
    def stem(self):
        """The "base" part of the filename, without the extension."""
        return ".".join(self.filename.split(".")[:-1])

    @property
    def filename(self):
        return self._path.split("/")[-1]

    @property
    def filename_prefix(self):
        return self.stem.split("_")[0]

    @property
    def filename_suffix(self):
        return self.stem.split("_")[-1]

    @property
    def path(self):
        return self._path

def iter_bp_paths(paths):
    """Generate each Path object in `paths` with filename having "_bp" suffix."""
    return (p for p in paths if p.filename_suffix == "bp")

def iter_mp_paths(paths, prefix):
    """Generate each Path object in `paths` with `prefix` and "mp" suffix."""
    return (
        p for p in paths if p.filename_prefix == prefix and p.filename_suffix == "mp"
    )

if __name__ == "__main__":
    paths = [Path(path) for path in glob.glob("/Users/you/tmp/*.png")]
    for bp_path in iter_bp_paths(paths):
        for mp_path in iter_mp_paths(paths, bp_path.filename_prefix):
            print(bp_path.path, mp_path.path)


问:
Display textBox.Text in Windows Form with "idx" iterating through for loop
This is my first C# project. I have two .cs files, one which has all the GUI related stuff (Form1.cs) and one which has my processing (GMF.cs). When "Start" (a Button) on GUI is clicked by user, control passes to Form1.cs, which internally calls GMFMat() present in GMF.cs file.

In Form1.cs, I have:

```<code>private void button1_Click(object sender, EventArgs e) // Start Processing button clicked.
{
    GMF n = new GMF();
    func_out = n.GMFMat(inputs_GUI, this.progressBar1, this.textBox_imageNumber);
}

private void timer1_Tick(object sender, EventArgs e) // Increment Progress Bar
{
    progressBar1.Increment(1);
}

private void textBox_imageNumber_TextChanged(object sender, EventArgs e)
{
    this.Text = textBox_imageNumber.Text;
    Console.Write("Text = " + textBox_imageNumber.Text);
}
</code>```

In GMF.cs, I have:

```<code>class GMF
{
public Tuple<string, int> GMFMat(in_params input_from_GUI, System.Windows.Forms.ProgressBar bar, System.Windows.Forms.TextBox textBox_ImgNumber)
{
    double nth_file = 0;
    double num_files = 100
    foreach (string dir in dirs) // For our example, say 100 ierations
    {
        nth_file = nth_file + 1;
        textBox_ImgNumber.Text = nth_file.ToString();
        // Progress bar updates in each iteration, and I can see it as it progresses on the windows Form during execution.
        bar_value_percent = nth_file / num_files * 100;
        bar.Value = int.Parse(Math.Truncate(bar_value_percent).ToString());
    }
}
}
</code>```

Form1.cs[Design] has a TextBox (which I simlpy dragged and dropped from Toolbox). I renamed (Name) = textBox_imageNumber

The value increments by 1 every-time it enters the for loop.

The basic purpose of doing this is because I want the user to know (Display a message on Form Application) everytime the for loop finishes 1000 iterations.

When I run the code above, I notice the following:

On the Console window, the output is as expected: Text = 1, Text = 2, ... Text = 100 as the program proceeds. - this shows that the value of variable in textBox_ImgNumber.Text is being updated inside the for loop of GMF.cs, and reaches Form1.cs.

However, on the Form, the value in text box is blank while the program runs (inside the for loop). As soon as it comes out of func_out = n.GMFMat(inputs_GUI, this.progressBar1, this.textBox_imageNumber);, the textBox's value is displayed as 100.

I want the value of text box on the form to be updated as and when the for loop iterates (as I see on Console window).  How can I do this?

I use Visual Studio, C# on Visual Studio 2010, .NET Framework 4 Client Profile

I know my Form is working well with respect to processing, etc since other functions are communicated well between the two .cs files.

For example, I also have a progress bar whose progress I can see when the program is being executed.

答:
I found the solution.

I had to include the line: Application.DoEvents();

So in Form1.cs:

```<code>private void textBox_imageNumber_TextChanged(object sender, EventArgs e)
{
     this.Text = textBox_imageNumber.Text;
     Console.Write("Text = " + textBox_imageNumber.Text);
     Application.DoEvents();
}
</code>```

Body:
This is my first C# project. I have two .cs files, one which has all the GUI related stuff (Form1.cs) and one which has my processing (GMF.cs). When "Start" (a Button) on GUI is clicked by user, control passes to Form1.cs, which internally calls GMFMat() present in GMF.cs file.

In Form1.cs, I have:

private void button1_Click(object sender, EventArgs e) // Start Processing button clicked.
{
    GMF n = new GMF();
    func_out = n.GMFMat(inputs_GUI, this.progressBar1, this.textBox_imageNumber);
}

private void timer1_Tick(object sender, EventArgs e) // Increment Progress Bar
{
    progressBar1.Increment(1);
}

private void textBox_imageNumber_TextChanged(object sender, EventArgs e)
{
    this.Text = textBox_imageNumber.Text;
    Console.Write("Text = " + textBox_imageNumber.Text);
}

In GMF.cs, I have:

class GMF
{
public Tuple<string, int> GMFMat(in_params input_from_GUI, System.Windows.Forms.ProgressBar bar, System.Windows.Forms.TextBox textBox_ImgNumber)
{
    double nth_file = 0;
    double num_files = 100
    foreach (string dir in dirs) // For our example, say 100 ierations
    {
        nth_file = nth_file + 1;
        textBox_ImgNumber.Text = nth_file.ToString();
        // Progress bar updates in each iteration, and I can see it as it progresses on the windows Form during execution.
        bar_value_percent = nth_file / num_files * 100;
        bar.Value = int.Parse(Math.Truncate(bar_value_percent).ToString());
    }
}
}

Form1.cs[Design] has a TextBox (which I simlpy dragged and dropped from Toolbox). I renamed (Name) = textBox_imageNumber

The value increments by 1 every-time it enters the for loop.

The basic purpose of doing this is because I want the user to know (Display a message on Form Application) everytime the for loop finishes 1000 iterations.

When I run the code above, I notice the following:

On the Console window, the output is as expected: Text = 1, Text = 2, ... Text = 100 as the program proceeds. - this shows that the value of variable in textBox_ImgNumber.Text is being updated inside the for loop of GMF.cs, and reaches Form1.cs.

However, on the Form, the value in text box is blank while the program runs (inside the for loop). As soon as it comes out of func_out = n.GMFMat(inputs_GUI, this.progressBar1, this.textBox_imageNumber);, the textBox's value is displayed as 100.

I want the value of text box on the form to be updated as and when the for loop iterates (as I see on Console window).  How can I do this?

I use Visual Studio, C# on Visual Studio 2010, .NET Framework 4 Client Profile

I know my Form is working well with respect to processing, etc since other functions are communicated well between the two .cs files.

For example, I also have a progress bar whose progress I can see when the program is being executed.

Body:
I found the solution.

I had to include the line: Application.DoEvents();

So in Form1.cs:

private void textBox_imageNumber_TextChanged(object sender, EventArgs e)
{
     this.Text = textBox_imageNumber.Text;
     Console.Write("Text = " + textBox_imageNumber.Text);
     Application.DoEvents();
}


问:
The driver.findelement don't find the tab element:
i have this Problem with my test ..the

```<code>driver.findElement(By.xpath("//html/body/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div/div/div/div/div/ul/li[2]/a[2]/em/span/span/span")).click();
</code>```

don't find the element.

the eclipse show this message of error

Cannot locate a node using
  //html/body/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div/div/div/div/div/ul/li[2]/a[2]/em/span/span/span

答:
EDIT : Post edited to reflect answer to actual problem. Original answer follows.

Long XPath expressions are fragile, and tests are prone to fail when relying on them : a completely unrelated change somewhere else in the document can mess everything up, and even if you're aware of the problem, the tests' code is just harder to maintain.

In this particular case, since the site is generated by GWT, it's even worse - there is little control over the actual HTML changes. A good solution when using GWT is to use the ensureDebugId method (see link in comments).

Are you sure that this XPath expression is correct ? Does other tests work with this driver ?

I'd recommend avoiding the use of long XPath expressions like that - wouldn't it be safer in the long term to start the expression at an id-specified div somewhere in the page rather than at the root of the DOM ?

Body:
i have this Problem with my test ..the

driver.findElement(By.xpath("//html/body/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div/div/div/div/div/ul/li[2]/a[2]/em/span/span/span")).click();

don't find the element.

the eclipse show this message of error

Cannot locate a node using
  //html/body/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div/div/div/div/div/ul/li[2]/a[2]/em/span/span/span


问:
Date picker shows range years
When I select my picker I only want to show years from 1900 to 2150
What's wrong in my code or what's missing?</p>

```<code>@objc func dateChanged(datePicker: UIDatePicker,field: HoshiTextField){
    let dateFormatter =  DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    let min = dateFormatter.date(from: "01-01-1900")
    let max = dateFormatter.date(from: "01-01-2150")
    datePicker.minimumDate = min
    datePicker.maximumDate = max
    if  self.fechaTxt.isFirstResponder{
        self.fechaTxt.text = dateFormatter.string(from: datePicker.date)
    }
    self.view!.endEditing(true)
}
</code>```

答:
When setting the min and max date of a UIDatePicker, other dates will still be visible, they just can't be selected. So if you try to scroll to the year 1800, your picker will bounce up to your minimumValue of 1900.

If you want to prevent date us beyond your time range to be shown, I'm afraid you'll have to create it yourself, by using UIPickerView, and populate it with however many components you want.

Or, as this is likely a common problem, I guess several other people have created a pod or spm just for this case, so check the internet for alternatives if you don't want to re-invent this wheel.

Title: Date picker shows range years

Body:
When I select my picker I only want to show years from 1900 to 2150
What's wrong in my code or what's missing?

@objc func dateChanged(datePicker: UIDatePicker,field: HoshiTextField){
    let dateFormatter =  DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    let min = dateFormatter.date(from: "01-01-1900")
    let max = dateFormatter.date(from: "01-01-2150")
    datePicker.minimumDate = min
    datePicker.maximumDate = max
    if  self.fechaTxt.isFirstResponder{
        self.fechaTxt.text = dateFormatter.string(from: datePicker.date)
    }
    self.view!.endEditing(true)
}


问:
How do Cardinalities and Generalization work in UML?
I am trying to understand how Cardinalities and Relationships work with Generalization in simple UML class diagrams. I have this simple example here:

A Player owns exactly 9 Fields, but the distribution of them is irrelevant (i.e. 5 Endfields, 4 Startfields or 1 Endfield and 8 Startfields). The Field class is abstract. If i model this problem as seen above, would a Player have 9 Fields from each type? If so, how do i model this correctly?

答:
Your model does correctly express your intended meaning except that you need to add a disjointness constraint to your Endfield-Startfield segmentation (called "generalization set" in UML jargon) for making sure that a field cannot be both an end field and a start field.

As of UML 2.5, segmentations are overlapping (and incomplete) by default. See also the (always excellent) explanations on uml-diagrams.org, which shows how to draw the disjointness constraint.