问:
Question about type classes in Scala
Let there are classes Fruit, Orange, and Apple.

```<code>abstract class Fruit
class Orange extends Fruit
class Apple extends Fruit</code>```

Now I want to add write functionality to both types Orange and Apple. Using the type class pattern I can do the following:

```<code>trait Writer[T] {def write(t:T)}

implicit object AppleWriter extends Writer[Apple] {
   def write(a:Apple) {println("I am an apple!")}
}

implicit object OrangeWriter extends Writer[Orange] {
   def write(o:Orange) {println("I am an orange!")}
}

def write[T](t:T)(implicit w:Writer[T]){w.write(t)}</code>```

So for, so good but what if I want to define writeFruits ?

```<code>def writeFruits(fruits:List[Fruit]) {for (fruit <- fruits) write(fruit)}</code>```

I would like writeFruits to call either write[Apple] or write[Orange] for each fruit. I see that it does not work (and I know why) but maybe I can implement the writeFruits anyway.

Can I implement writeFruits somehow ?

答:
Or maybe case-classes are for you? </p>

```<code>abstract class Fruit {}
case object Orange extends Fruit
case object Apple extends Fruit

trait Writer[T] {def write (t:T)}

implicit object FruitWriter extends Writer [Fruit] {
   def write (fruit: Fruit) = fruit match {
     case Apple => println ("I am an apple!")
     case Orange => println ("I am an orange!")
   }
}

def writeFruits (fruits: List[Fruit]) {
  for (fruit <- fruits) write(fruit)
}

val fl = List (Orange, Apple, Apple, Orange, Apple)

writeFruits (fl)
I am an orange!
I am an apple!
I am an apple!
I am an orange!
I am an apple!
</code>```

Title: Question about type classes in Scala

Body:
Let there are classes Fruit, Orange, and Apple.

abstract class Fruit
class Orange extends Fruit
class Apple extends Fruit

Now I want to add write functionality to both types Orange and Apple. Using the type class pattern I can do the following:

trait Writer[T] {def write(t:T)}

implicit object AppleWriter extends Writer[Apple] {
   def write(a:Apple) {println("I am an apple!")}
}

implicit object OrangeWriter extends Writer[Orange] {
   def write(o:Orange) {println("I am an orange!")}
}

def write[T](t:T)(implicit w:Writer[T]){w.write(t)}

So for, so good but what if I want to define writeFruits ?

def writeFruits(fruits:List[Fruit]) {for (fruit <- fruits) write(fruit)}

I would like writeFruits to call either write[Apple] or write[Orange] for each fruit. I see that it does not work (and I know why) but maybe I can implement the writeFruits anyway.

Can I implement writeFruits somehow ?

Body:
Or maybe case-classes are for you?

abstract class Fruit {}
case object Orange extends Fruit
case object Apple extends Fruit

trait Writer[T] {def write (t:T)}

implicit object FruitWriter extends Writer [Fruit] {
   def write (fruit: Fruit) = fruit match {
     case Apple => println ("I am an apple!")
     case Orange => println ("I am an orange!")
   }
}

def writeFruits (fruits: List[Fruit]) {
  for (fruit <- fruits) write(fruit)
}

val fl = List (Orange, Apple, Apple, Orange, Apple)

writeFruits (fl)
I am an orange!
I am an apple!
I am an apple!
I am an orange!
I am an apple!


来源: stackexchange

问:
Managing Python Packages using AWS S3 Bucket
I would like to use an Amazon S3 bucket to store python packages and use them in any pip installation in our project. As of now I am able to download these packages from web and store them in an Amazon S3 bucket using aws s3 cp <source> <destination>.

For example: pip download tornado==6.2.0. It has downloaded all the dependencies and copied into the S3 bucket. Real issue here is the dependencies are in either .whl or tar.gz or some other format.

How can I refer pip install tornado==6.2.0 from S3 bucket?

答:
What you're asking for is to implement the simple python packaging index, aka pyPI. If you configure a fileserver (which is what you're treating the bucket as) in the way decribed by the PEP, tools like pip will automatically know how to install packages from it.

But configuring a fileserver is hard and annoying, and other people have done it already anyway. So instead you can use pypiserver (which also publishes a docker container that you can run out of aws), and connect its package repository to the s3 bucket that you have set up (this part might actually be a bit tricky).

So, given that pypiserver runs on some port within your intranet, e.g. 3141, you can download packages from it with

```<code>pip install mypackage --extra-index-url 0.0.0.0:3141 --trusted-host 0.0.0.0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What you're asking for is to implement the simple python packaging index, aka pyPI. If you configure a fileserver (which is what you're treating the bucket as) in the way decribed by the PEP, tools like pip will automatically know how to install packages from it.

But configuring a fileserver is hard and annoying, and other people have done it already anyway. So instead you can use pypiserver (which also publishes a docker container that you can run out of aws), and connect its package repository to the s3 bucket that you have set up (this part might actually be a bit tricky).

So, given that pypiserver runs on some port within your intranet, e.g. 3141, you can download packages from it with

pip install mypackage --extra-index-url 0.0.0.0:3141 --trusted-host 0.0.0.0


问:
Is ADO.NET in .NET Core possible?
Most tutorials are Entity Framework with no mention of Ado.Net in .Net Core projects. I have a "legacy" database, so a EF/"Code-First" approach is not an option.

For ADO.NET connections, is the System.Data.SqlClient available to an ASP.NET Core project?

It is available when I use a .NET Framework project template but is it still available in a .NET Core project?

答:
In ADO.NET Core I do NOT use System.Data.SqlClient but I use Microsoft.Data.SqlClient.
Until now, I could use all my previous coding!.

Title: Is ADO.NET in .NET Core possible?


答:
Try this</p>

```<code>function getSkinType($id) {
     $grouping = [
         'type 1' => [1, 13, 20, 25, 35], // [ ids ]
         'type 2' => [20, 25],
         'type 3' => [35, 40],
     ];

     foreach($grouping as $type => $range) {
         if (in_array($id, $range))  {
              return $type;
         }
     }

     return 'Type not found'; // default text here
}

echo getSkinType(13); // "type 1"
</code>```

Title: One php array with some values for some indexs

Body:
I wanna create an array or a function n php with something like this:

for index between 1-20 returns "type 1"

for index between 20-25 returns "type 2"

for index between 25-35 returns "type 1"

for index between 35-40 returns "type 3"

for index between 40-60 retusn "type 2".

How can I do this?

For example id 1, id 22, id 50 can be type 1, but also id 2, id 23, id 51 are type 2.

I've tried this:

function getSkinType($id) {
    $skins = array(
        0,13,40,46,47,59,60,72,73,76,82,83,84,85,90,91,93,98,102,103,104,105,106,107,108,109,110,111,112, 113,114,115,116,120,121,123,124,125,126,127,128,141,147,150,163,164,165,166,169,170,173,174,175,177,181,185,186,187,189,191,193,194,192,195,203,204,216,219,221,223,228,233,240,258,259,263,269,270,271,272,290,292,293,294,295,296,297,298,299,3 => "premium",
        2,7,9,11,14,15,16,17,19,20,21,22,18,23,24,25,28,29,30,32,33,34,35,36,41,43,44,45,48,51,52,57,58,63,64,66,67,69,88,92,95,96,97,100,101,122,131,133,138,139,140,142,143,148,154,155,156,167,171,172, 176,179,180,182,183, 184,188,190,201,202,206,214,215,222,224,225,226,227,234,238,247,248,249,250,251,252 => "normal",
        1,12,27,31,37,50,56,78,79,129,134,135,136,137,152,153,157,158,159,160,161,162,196,200,212 => "default"
    );
    return $skins[$id];
}

Body:
Try this

function getSkinType($id) {
     $grouping = [
         'type 1' => [1, 13, 20, 25, 35], // [ ids ]
         'type 2' => [20, 25],
         'type 3' => [35, 40],
     ];

     foreach($grouping as $type => $range) {
         if (in_array($id, $range))  {
              return $type;
         }
     }

     return 'Type not found'; // default text here
}

echo getSkinType(13); // "type 1"


问:
How can I dynamically load an icon using its snake_case name (React, material-ui)
Normally I'd use material-ui icons by importing them directly per the material-ui instructions.

But I have a text tag, which is the actual icon name (like calendar_view_day) and need to get and render an icon component from it dynamically.

How can I something like:

```<code>render() {
  return (
    <Icon name="calendar_view_day" color="primary" />
  )
}
</code>```

Instead of:

```<code>render() {
  return (
    <CalendarViewDay color="primary" />  // Imported by name
  )
}
</code>```

答:
EDIT: This answer for MUI v4, MUI v5 answers below (but untested by me)

OK, so I massively overthought this.

Correct answer

Turns out material-ui includes an icon component that allows you to do this... and it converts names itself, so accepts snake, pascal and other variants. BEWARE this will massively increase bundle size, as pointed out in the comments. If you're bundle size constrained, you'll have to take a different approach of serving the icon SVGs from somewhere!

```<code>import Icon from '@material-ui/core/Icon'

...

render() {
  return (
    <Icon>{props.iconName}</Icon>
  )
}
</code>```

Previous answer (working but massive overkill)

Create function to:

convert snake_case to PascalCase

Handle special cases reported in the material-ui icons documentation

...Then use the material-ui Icon component.

Here's the code:

```<code>import Icon from '@material-ui/core/Icon'

function upperFirst(string) {
  return string.slice(0, 1).toUpperCase() + string.slice(1, string.length)
}

function fixIconNames(string) {
  const name = string.split('_').map(upperFirst).join('')
  if (name === '3dRotation') {
    return 'ThreeDRotation'
  } else if (name === '4k') {
    return 'FourK'
  } else if (name === '360') {
    return 'ThreeSixty'
  }
  return name
}

...

render() {
  const iconName = fixIconNames(props.iconName)
  return (
    <Icon>{props.iconName}</Icon>
  )
}
</code>```

Body:
Normally I'd use material-ui icons by importing them directly per the material-ui instructions.

But I have a text tag, which is the actual icon name (like calendar_view_day) and need to get and render an icon component from it dynamically.

How can I something like:

render() {
  return (
    <Icon name="calendar_view_day" color="primary" />
  )
}

Instead of:

render() {
  return (
    <CalendarViewDay color="primary" />  // Imported by name
  )
}

Body:
EDIT: This answer for MUI v4, MUI v5 answers below (but untested by me)

OK, so I massively overthought this.

Correct answer

Turns out material-ui includes an icon component that allows you to do this... and it converts names itself, so accepts snake, pascal and other variants. BEWARE this will massively increase bundle size, as pointed out in the comments. If you're bundle size constrained, you'll have to take a different approach of serving the icon SVGs from somewhere!

import Icon from '@material-ui/core/Icon'

...

render() {
  return (
    <Icon>{props.iconName}</Icon>
  )
}

Previous answer (working but massive overkill)

Create function to:

convert snake_case to PascalCase

Handle special cases reported in the material-ui icons documentation

...Then use the material-ui Icon component.

Here's the code:

import Icon from '@material-ui/core/Icon'

function upperFirst(string) {
  return string.slice(0, 1).toUpperCase() + string.slice(1, string.length)
}

function fixIconNames(string) {
  const name = string.split('_').map(upperFirst).join('')
  if (name === '3dRotation') {
    return 'ThreeDRotation'
  } else if (name === '4k') {
    return 'FourK'
  } else if (name === '360') {
    return 'ThreeSixty'
  }
  return name
}

...

render() {
  const iconName = fixIconNames(props.iconName)
  return (
    <Icon>{props.iconName}</Icon>
  )
}


问:
How do I search within an JSON array of hashes by hash values?
I am using Postgres' JSON data type to store some information.

For example I have model User with a field locations that holds a json document(array of objects containing pairs of keys and values) in the following format:

```<code>[{"name": "Location 1", kind: "house"},
 {"name": "Location 2", kind: "house"},
 {"name": "Location 3", kind: "office"},
 ...
 {"name": "Location X", kind: "house"}
]
</code>```

I want to query with .where on the JSON data type.

I want to query for users that have at least one location with kind = office.

Thanks!

答:
Filters based on the values of objects inside array JSONB

If you want to make filters based on the values of the objects (jsonb) inside the arrays in Rails with postgres you can use something like example below.

Assuming you have a Product model:

```<code>Product.select("*").from(
  Product.select("*, jsonb_array_elements(registers) as register")
).where("(register ->> 'price')::numeric >= 1.50")
</code>```

In above example we select all products with price greater than or equal 1.50.

For this we use:

jsonb_array_elements() from postgres;

an auxiliary column and alias;

and methods from ActiveRecord from Rails.

I applied ident in sub-query just for best readability.

After you can put this in a scope or use other best practice.

ContentLicense: CC BY-SA 3.0

Body:
I am using Postgres' JSON data type to store some information.

For example I have model User with a field locations that holds a json document(array of objects containing pairs of keys and values) in the following format:

[{"name": "Location 1", kind: "house"},
 {"name": "Location 2", kind: "house"},
 {"name": "Location 3", kind: "office"},
 ...
 {"name": "Location X", kind: "house"}
]

I want to query with .where on the JSON data type.

I want to query for users that have at least one location with kind = office.

Thanks!

Body:
Filters based on the values of objects inside array JSONB

If you want to make filters based on the values of the objects (jsonb) inside the arrays in Rails with postgres you can use something like example below.

Assuming you have a Product model:

Product.select("*").from(
  Product.select("*, jsonb_array_elements(registers) as register")
).where("(register ->> 'price')::numeric >= 1.50")

In above example we select all products with price greater than or equal 1.50.

For this we use:

jsonb_array_elements() from postgres;

an auxiliary column and alias;

and methods from ActiveRecord from Rails.

I applied ident in sub-query just for best readability.

After you can put this in a scope or use other best practice.


问:
controller function, next is not defined error
My code was working just fine, but out of no where I started getting this error.
ReferenceError: next is not defined.
No clue how I started getting it as I didn't change this function at all. </p>

```<code>const Accounts = require('../data/accounts.model')

exports.addAccount = (req, res) => {
    const newAccount = new Accounts({
        Username: req.body.Username,
        Password: req.body.Password,
        AccountType: req.body.AccountType,
        Email: req.body.Email,
        Age: req.body.Age,
        Question1A: req.body.Question1A,
        Question2A: req.body.Question2A,
        Question3A: req.body.Question3A,
    });

    newAccount.save((err) => {
        if (err){
             return next(err);
  //error happens here^
        }
        res.send('Account created Successfully');
    });
};
</code>```

答:
next is the 3rd parameter to any middleware. So the code should be:

```<code>exports.addAccount = (req, res, next) => {
</code>```

Body:
My code was working just fine, but out of no where I started getting this error.
ReferenceError: next is not defined.
No clue how I started getting it as I didn't change this function at all.

const Accounts = require('../data/accounts.model')

exports.addAccount = (req, res) => {
    const newAccount = new Accounts({
        Username: req.body.Username,
        Password: req.body.Password,
        AccountType: req.body.AccountType,
        Email: req.body.Email,
        Age: req.body.Age,
        Question1A: req.body.Question1A,
        Question2A: req.body.Question2A,
        Question3A: req.body.Question3A,
    });

    newAccount.save((err) => {
        if (err){
             return next(err);
  //error happens here^
        }
        res.send('Account created Successfully');
    });
};

Body:
next is the 3rd parameter to any middleware. So the code should be:

exports.addAccount = (req, res, next) => {


问:
Upsert parent and children with EntityFramework
I find myself frequently wanting "Upsert" functionality in EntityFramework - I've got a disconnected graph of parent + children entities and I want to "upsert" the parent (and its children). By that I mean

When the parent doesn't have an ID assigned (id = 0) I'd like to simply insert the parent and the children (auto assign IDs in both cases)

When the parent does have a ID assigned, I'd like to replace the existing parent entity in the database (having the same ID) with the new one. In addition, any children associated with that parent should be removed (parent 'owns' the children). The children on the new parent should be inserted in their place (keeping the assigned ids).

This "mostly" works in that it retains the ID of the parent, but does not retain the IDs of the children (the children are assigned new IDs on each "upsert").

public void Upsert(ParentEntity parentEntity) {
    ParentEntity existing = DB.Parents.Find(parentEntity.Id);

    if (existing == null) {
        DB.Parents.Add(parentEntity);
    } else {
        var existingChildren = DB.Children.Where(m => m.ParentId == parentEntity.Id).ToArray();

        foreach (var child in parentEntity.Children) {
            child.ParentId = parentEntity.Id;
        }

        DB.Children.RemoveRange(existingChildren);
        DB.Children.AddRange(parentEntity.Children);

        DB.Entry(existing).State = EntityState.Detached;
        DB.Parents.Attach(parentEntity);
        DB.Entry(parentEntity).State = EntityState.Modified;
    }

    SaveChanges();
}
```

答:
This works:

public void Upsert(ParentEntity parentEntity) {
    ParentEntity existing = DB.Parents.Find(parentEntity.Id);

    if (existing == null) {
        DB.Parents.Add(parentEntity);
    } else {
        var newChildKeys = new HashSet<int>(parentEntity.Children.Select(m => m.Id));

        var existingChildren = DB.Children.Where(m => m.ParentId == parentEntity.Id).ToArray();
        var existingChildrenKeys = new HashSet<int>(existingChildren.Select(m => m.Id));

        foreach (var existingChild in existingChildren) {
            if (newChildKeys.Contains(existingChild.Id)) {
                DB.Entry(existingChild).State = EntityState.Detached;
            } else {
                DB.Children.Remove(existingChild);
            }
        }

        foreach (var child in parentEntity.Children) {
            child.ParentId = parentEntity.Id;
            if (existingChildrenKeys.Contains((child.Id))) {
                DB.Children.Attach(child);
                DB.Entry(child).State = EntityState.Modified;
            } else {
                DB.Children.Add(child);
            }
        }

        DB.Entry(existing).State = EntityState.Detached;
        DB.Parents.Attach(parentEntity);
        DB.Entry(parentEntity).State = EntityState.Modified;
    }

    SaveChanges();
}
```

Perhaps it can be improved on from a stylistic perspective / made more generic. The basic idea is

Find the common keys across the entities (existing in database vs replacement entity)

For common keys, detach the old entity, attach the new entity & mark as modified

For keys that no-longer exist - remove the entity

For new keys - add the entity

Body:
This works:

public void Upsert(ParentEntity parentEntity) {
    ParentEntity existing = DB.Parents.Find(parentEntity.Id);

    if (existing == null) {
        DB.Parents.Add(parentEntity);
    } else {
        var newChildKeys = new HashSet<int>(parentEntity.Children.Select(m => m.Id));

        var existingChildren = DB.Children.Where(m => m.ParentId == parentEntity.Id).ToArray();
        var existingChildrenKeys = new HashSet<int>(existingChildren.Select(m => m.Id));

        foreach (var existingChild in existingChildren) {
            if (newChildKeys.Contains(existingChild.Id)) {
                DB.Entry(existingChild).State = EntityState.Detached;
            } else {
                DB.Children.Remove(existingChild);
            }
        }

        foreach (var child in parentEntity.Children) {
            child.ParentId = parentEntity.Id;
            if (existingChildrenKeys.Contains((child.Id))) {
                DB.Children.Attach(child);
                DB.Entry(child).State = EntityState.Modified;
            } else {
                DB.Children.Add(child);
            }
        }

        DB.Entry(existing).State = EntityState.Detached;
        DB.Parents.Attach(parentEntity);
        DB.Entry(parentEntity).State = EntityState.Modified;
    }

    SaveChanges();
}

Perhaps it can be improved on from a stylistic perspective / made more generic. The basic idea is

Find the common keys across the entities (existing in database vs replacement entity)

For common keys, detach the old entity, attach the new entity & mark as modified

For keys that no-longer exist - remove the entity

For new keys - add the entity


问:
Netsuite SuiteCloud IDE How to setup administrator user to not have two-factor authentication
I would like to use the NetSuite SuiteCloud IDE (Eclipse plugin), but I am also an Administrator. If you're an Administrator NetSuite requires you to have two factor authentication enabled, but if you want to use the SuiteCloud IDE you can't have two factor authentication enabled. How does one get out of this Catch-22?

I'm new to NetSuite so I don't know much about setting up roles. Do I just add another role with full permissions (or what permissions are needed?)? How would the SuiteCloud IDE know to use that role? Or do I have to create myself as an employee twice with different emails (this would be bad since we don't have many users)?

答:
Administrator role with 2FA can be used with Eclipse IDE.

In your NS account as administrator, create a new integration:

Setup > Integration > Manage Integrations > New

Name your integration SuiteCloude IDE or something like that

Check the Token-Based authentication box.

Then from your Administrator dashboard, create a new access token.

Then in Eclipse, go to Manage accounts:

Netsuite menu > Manage Accounts

Select the account with the administrator role, and manage authentication.

Select the Administrator Role, and SAVE TOKEN.

Here you can enter the Token ID and Token Secret created in your NetSuite account.

Then you should be good to go in Eclipse. Make sure you set the Eclipse project to now use the Admin role.


问:
thread-aware gdb for the Linux kernel
I am using gdb attached to a serial port of a virtual machine to debug linux kernel.

I am wondering, if there is any patches/plugins which can make the gdb understand some of linux kernel's data structure and make it "thread aware"?

By that I mean under gdb I can see how many kernel threads are there, their status, and for each thread, their stack information.

答:
pyvmidbg developer here.

I will add some clarifications:
yes the goal of the project is indeed to have a cross-platform, guest-aware GDB stub.

Most of the implementation is already done for Windows, where we are aware of processes and their threads context.
It's possible to intercept a specific process (cmd.exe in the demo) and singlestep its execution (this is limited to 1 process with 1 thread for now), as well as attaching to a new process's entrypoint.

Regarding Linux, I looked at the internals and the resources that I could find, but I'm lacking the whole picture to figure out how I can:
- intercept a task when it's being scheduled (core/sched.c:switch_to() ?)
- read the task state (Windows's KTRAP_FRAME  equivalent for Linux ?)

I asked a question on SO, but nobody answered :/
Linux context switch internals: how does a process goes back to userland after the switch?

If you can help with this, I can guide you through the implementation :)

Regarding the hypervisor support, only Xen is fully supported in the Libvmi interface at the moment.
I added a section in the README to describe where we are in terms of VMI APIs with other hypervisors.

Thanks !

Title: thread-aware gdb for the Linux kernel


问:
How encrypt SQLite database with FireDAC?
I'm create SQLite databse with DB Browser for SQLite (non encrypted) and open with FireDAC in delphi.(Can retrive data Eg. Select * from abc).

How encrypt this SQLite database with FireDAC? When enter username, password and encrypt get message  "Cipher DB is not encrypdet"

Note:

When create SQLite database from Delphi FireDac I can use encryption!

答:
To encrypt a database, use a TFDSQLiteSecurity Component.  You'll also need a TFDSQLitePhysSQLiteDriverLink component to go along with it.

If a database is unencrypted, then its password is ''.  So use '' as the OldPassword and create the new password in that case.  Passwords are formatted as algorithm:PassPhrase.  See documentation on the choices, I use aes-256.  Also, the database needs to be closed when you do this.

```<code>...
//Change password
FDSQLiteSecurity1.Password := OldPassword;
FDSQLiteSecurity1.ToPassword := NewPassword;  // example: 'aes-256:mypassword123'
FDSQLiteSecurity1.ChangePassword;
...
//Remove Password
FDSQLiteSecurity1.Password := OldPassword;
FDSQLiteSecurity1.ToPassword := '';
FDSQLiteSecurity1.RemovePassword;
...
</code>```

Body:
To encrypt a database, use a TFDSQLiteSecurity Component.  You'll also need a TFDSQLitePhysSQLiteDriverLink component to go along with it.

If a database is unencrypted, then its password is ''.  So use '' as the OldPassword and create the new password in that case.  Passwords are formatted as algorithm:PassPhrase.  See documentation on the choices, I use aes-256.  Also, the database needs to be closed when you do this.

...
//Change password
FDSQLiteSecurity1.Password := OldPassword;
FDSQLiteSecurity1.ToPassword := NewPassword;  // example: 'aes-256:mypassword123'
FDSQLiteSecurity1.ChangePassword;
...
//Remove Password
FDSQLiteSecurity1.Password := OldPassword;
FDSQLiteSecurity1.ToPassword := '';
FDSQLiteSecurity1.RemovePassword;
...


问:
Where is NSAlert.h in the iOS  SDK?
According to iOS's Using and Creating Error Objects, one can display a error object with the following code.

```<code>NSError *theError = nil;
BOOL success = [myDoc writeToURL:[self docURL] ofType:@"html" error:&theError];

if (success == NO) {
    // Maybe try to determine cause of error and recover first.
    NSAlert *theAlert = [NSAlert alertWithError:theError];
    [theAlert runModal]; // Ignore return value.
}
</code>```

Unfortunately, I am not smart enough to figure out how to include NSAlert.h.

Any help would be appreciated.

答:
Its in the AppKit framework.
NSAlert

Import that framework to your project in xcode, then use the #include  directive at the top of your code

there are also some samples of using NSAlert if you go to that page and look at the "Sample Code". I always do that if I'm unsure of any part of a new framework

Title: Where is NSAlert.h in the iOS  SDK?

Body:
According to iOS's Using and Creating Error Objects, one can display a error object with the following code.

NSError *theError = nil;
BOOL success = [myDoc writeToURL:[self docURL] ofType:@"html" error:&theError];

if (success == NO) {
    // Maybe try to determine cause of error and recover first.
    NSAlert *theAlert = [NSAlert alertWithError:theError];
    [theAlert runModal]; // Ignore return value.
}

Unfortunately, I am not smart enough to figure out how to include NSAlert.h.

Any help would be appreciated.


问:
How to import excel spreadsheet into access and cross reference two tables
I have the following two Access tables

```<code>Employees
id          Name
1           bob smith
2           james bird
3           jane big

Events
id         emp_id        Notes
1          1             fell down the stairs
2          3             paper cut in the break room
</code>```

I also have the following Excel file that I would like to 'suck' (import) into the Events table. The problem is the data needs to be correlated on the name/emp_id field and I'm not sure the best way to do this.

```<code>Excel_sheet

Employee Name       Notes
bob smith           feel asleep while driving
</code>```

The access table uses references to the Employees table, whereas the Excel sheet is using names. What are some options for me to bring this Excel sheet into Events table and convert the names (bob smith) into their associated id's from the Employees table?

答:
Assuming names are consistently spelled in both datasets and only one person exists for each name, try:

INSERT INTO Events(emp_ID, Notes) SELECT ID, Notes FROM excel_sheet INNER JOIN Employees ON Employees.Name=excel_sheet.[Employee Name];

Build that SQL in a query object or run in VBA:

CurrentDb.Execute "INSERT INTO Events(emp_ID, Notes) " & _
           "SELECT ID, Notes FROM excel_sheet " & _
           "INNER JOIN Employees ON Employees.Name=excel_sheet.[Employee Name];"

Suggest you test with a copy of database.

Name is a reserved word and really should not use reserved words as names for anything.

Body:
I have the following two Access tables

Employees
id          Name
1           bob smith
2           james bird
3           jane big

Events
id         emp_id        Notes
1          1             fell down the stairs
2          3             paper cut in the break room

I also have the following Excel file that I would like to 'suck' (import) into the Events table. The problem is the data needs to be correlated on the name/emp_id field and I'm not sure the best way to do this.

Excel_sheet

Employee Name       Notes
bob smith           feel asleep while driving

The access table uses references to the Employees table, whereas the Excel sheet is using names. What are some options for me to bring this Excel sheet into Events table and convert the names (bob smith) into their associated id's from the Employees table?


问:
How to convert the result of invoke-request to a multidimensional array?
I used 'Invoke-request' to get the JSON bellow. I would like to convert it to a multi-dimensional array. I looked online but I can't find the appropriate solution. An answer would be great, if not, then point me to the appropriate resources would also help.

Thank you

```<code>{"ResultForName":
    [{"Name":"work","Values":["no"]},
    {"Name":"location","Values":["\\pc\\documents"]},
    {"Name":"Authority","Values":["10"]},
    {"Name":"City","Values":["Toronto"]},
    {"Name":"Country","Values":["CA"]},
    {"Name":"Created By","Values":["George"]},
    {"Name":"Money Vault Id","Values":["100000"]},
    {"Name":"Opened  On","Values":["Mark, John, L=Toronto, S=Ontario, C=CA","www.doman.com", O=Office, L=Toronto, S=Ontario, C="CA"]},
                    {"Name":"Driver Name","Values":["Honda"]},
                    {"Name":"Can drive","Values":["0"]},
                    {"Name":"Given Name","Values":["Steven"]},
                    {"Name":"Group Id","Values":["34324"]},
                    {"Name":"Internet System Address","Values"["www.doman.com/Locations"]},
                    {"Name":"Key value","Values":["AXU"]},
                    {"Name":"Key Encryption","Values":["128"]},
                    {"Name":"Last Check up","Values":["12\/20\/2018 04:00:08"]},
                    {"Name":"Last Notification","Values":["11\/22\/2018 05:00:59"]},
                    {"Name":"Last used by","Values":["David"]},
                    {"Name":"Last Used On","Values":["09\/11\/2018 14:57:50"]},
                    {"Name":"Validation","Values":["02\/22\/2019 04:06:18"]},
                    {"Name":"Last Validation query","Values":["Success"]},
                    {"Name":"Last Acceptence","Values":["04\/12\/2019 04:10:11"]},
                    {"Name":"Managed By","Values":["Manager"]},
                    {"Name":"Automatic","Values":["True"]},
                    {"Name":"Options","Values":["More options Needed"]},
                    {"Name":"Organization","Values":["Organization"]},
                    {"Name":"Organizational Unit","Values":["CSV"]},
                    {"Name":"Work Location Date","Values":["02\/29\/2019 02:00:40"]},
                    {"Name":"URL Details","Values":["CN=web.website.com,O=\"Organization\",OU=CSV,L=Toronto,ST=Ontario,C=CA"]},
                    {"Name":"Provence","Values":["Ontario"]},
                    {"Name":"Surname","Values":["Johnson"]},
                    {"Name":"Transaction value","Values":["23452523"]},
                    {"Name":"Validation Acceptance Values",
                                    "Values":["111.11.11.11|443|0|11|0|organization.com\\3$","111.11.111.111|443|0|11|0|orgaization.com\\2$","111.11.111.111|443|0|11|0|orgaization.com\\2$"]},
                    {"Name":"Acceptance  State","Values":["Success"]},
                    {"Name":"Validity Zone","Values":["120"]},
                    {"Name":"ClearMode","Values":["0"]},
                    {"Name":"Approval CA:Count","Values":["1"]},
                    {"Name":"Reader","Values":["Office"]},
                    {"Name":"End Date","Values":[""]},
                    {"Name":"Meeting Subject","Values":["adb.organization.com"]},
                    {"Name":"SubjectAltName DNS","Values":["adb.organization.com","ade.organization.com","Create.orgaization.com"]}],
"Result":1}
</code>```

答:
There are two problem lines in the JSON:

This line has a misplaced "

{"Name":"Opened  On","Values":["Mark, John, L=Toronto, S=Ontario, C=CA","www.doman.com", O=Office, L=Toronto, S=Ontario, C="CA"]},

It should probably be

{"Name":"Opened  On","Values":["Mark, John, L=Toronto, S=Ontario, C=CA","www.doman.com", "O=Office, L=Toronto, S=Ontario, C=CA"]},

And this line

{"Name":"Internet System Address","Values"["www.doman.com/Locations"]},

should have a : after "Values"

{"Name":"Internet System Address","Values":["www.doman.com/Locations"]},

Once you've fixed those issues, the result is valid JSON and can be piped to ConvertFrom-JSON:

```<code>$JSON = @"
{"ResultForName":
    [{"Name":"work","Values":["no"]},
    {"Name":"location","Values":["\\pc\\documents"]},
    {"Name":"Authority","Values":["10"]},
    {"Name":"City","Values":["Toronto"]},
    {"Name":"Country","Values":["CA"]},
    {"Name":"Created By","Values":["George"]},
    {"Name":"Money Vault Id","Values":["100000"]},
    {"Name":"Opened  On","Values":["Mark, John, L=Toronto, S=Ontario, C=CA","www.doman.com", "O=Office, L=Toronto, S=Ontario, C=CA"]},
    {"Name":"Driver Name","Values":["Honda"]},
    {"Name":"Can drive","Values":["0"]},
    {"Name":"Given Name","Values":["Steven"]},
    {"Name":"Group Id","Values":["34324"]},
    {"Name":"Internet System Address","Values":["www.doman.com/Locations"]},
    {"Name":"Key value","Values":["AXU"]},
    {"Name":"Key Encryption","Values":["128"]},
    {"Name":"Last Check up","Values":["12\/20\/2018 04:00:08"]},
    {"Name":"Last Notification","Values":["11\/22\/2018 05:00:59"]},
    {"Name":"Last used by","Values":["David"]},
    {"Name":"Last Used On","Values":["09\/11\/2018 14:57:50"]},
    {"Name":"Validation","Values":["02\/22\/2019 04:06:18"]},
    {"Name":"Last Validation query","Values":["Success"]},
    {"Name":"Last Acceptence","Values":["04\/12\/2019 04:10:11"]},
    {"Name":"Managed By","Values":["Manager"]},
    {"Name":"Automatic","Values":["True"]},
    {"Name":"Options","Values":["More options Needed"]},
    {"Name":"Organization","Values":["Organization"]},
    {"Name":"Organizational Unit","Values":["CSV"]},
    {"Name":"Work Location Date","Values":["02\/29\/2019 02:00:40"]},
    {"Name":"URL Details","Values":["CN=web.website.com,O=\"Organization\",OU=CSV,L=Toronto,ST=Ontario,C=CA"]},
    {"Name":"Provence","Values":["Ontario"]},
    {"Name":"Surname","Values":["Johnson"]},
    {"Name":"Transaction value","Values":["23452523"]},
    {"Name":"Validation Acceptance Values",
                    "Values":["111.11.11.11|443|0|11|0|organization.com\\3$","111.11.111.111|443|0|11|0|orgaization.com\\2$","111.11.111.111|443|0|11|0|orgaization.com\\2$"]},
    {"Name":"Acceptance  State","Values":["Success"]},
    {"Name":"Validity Zone","Values":["120"]},
    {"Name":"ClearMode","Values":["0"]},
    {"Name":"Approval CA:Count","Values":["1"]},
    {"Name":"Reader","Values":["Office"]},
    {"Name":"End Date","Values":[""]},
    {"Name":"Meeting Subject","Values":["adb.organization.com"]},
    {"Name":"SubjectAltName DNS","Values":["adb.organization.com","ade.organization.com","Create.orgaization.com"]}],
"Result":1}
"@
$JSON | ConvertFrom-Json
</code>```

Body:
I used 'Invoke-request' to get the JSON bellow. I would like to convert it to a multi-dimensional array. I looked online but I can't find the appropriate solution. An answer would be great, if not, then point me to the appropriate resources would also help.

Thank you

{"ResultForName":
    [{"Name":"work","Values":["no"]},
    {"Name":"location","Values":["\\pc\\documents"]},
    {"Name":"Authority","Values":["10"]},
    {"Name":"City","Values":["Toronto"]},
    {"Name":"Country","Values":["CA"]},
    {"Name":"Created By","Values":["George"]},
    {"Name":"Money Vault Id","Values":["100000"]},
    {"Name":"Opened  On","Values":["Mark, John, L=Toronto, S=Ontario, C=CA","www.doman.com", O=Office, L=Toronto, S=Ontario, C="CA"]},
                    {"Name":"Driver Name","Values":["Honda"]},
                    {"Name":"Can drive","Values":["0"]},
                    {"Name":"Given Name","Values":["Steven"]},
                    {"Name":"Group Id","Values":["34324"]},
                    {"Name":"Internet System Address","Values"["www.doman.com/Locations"]},
                    {"Name":"Key value","Values":["AXU"]},
                    {"Name":"Key Encryption","Values":["128"]},
                    {"Name":"Last Check up","Values":["12\/20\/2018 04:00:08"]},
                    {"Name":"Last Notification","Values":["11\/22\/2018 05:00:59"]},
                    {"Name":"Last used by","Values":["David"]},
                    {"Name":"Last Used On","Values":["09\/11\/2018 14:57:50"]},
                    {"Name":"Validation","Values":["02\/22\/2019 04:06:18"]},
                    {"Name":"Last Validation query","Values":["Success"]},
                    {"Name":"Last Acceptence","Values":["04\/12\/2019 04:10:11"]},
                    {"Name":"Managed By","Values":["Manager"]},
                    {"Name":"Automatic","Values":["True"]},
                    {"Name":"Options","Values":["More options Needed"]},
                    {"Name":"Organization","Values":["Organization"]},
                    {"Name":"Organizational Unit","Values":["CSV"]},
                    {"Name":"Work Location Date","Values":["02\/29\/2019 02:00:40"]},
                    {"Name":"URL Details","Values":["CN=web.website.com,O=\"Organization\",OU=CSV,L=Toronto,ST=Ontario,C=CA"]},
                    {"Name":"Provence","Values":["Ontario"]},
                    {"Name":"Surname","Values":["Johnson"]},
                    {"Name":"Transaction value","Values":["23452523"]},
                    {"Name":"Validation Acceptance Values",
                                    "Values":["111.11.11.11|443|0|11|0|organization.com\\3$","111.11.111.111|443|0|11|0|orgaization.com\\2$","111.11.111.111|443|0|11|0|orgaization.com\\2$"]},
                    {"Name":"Acceptance  State","Values":["Success"]},
                    {"Name":"Validity Zone","Values":["120"]},
                    {"Name":"ClearMode","Values":["0"]},
                    {"Name":"Approval CA:Count","Values":["1"]},
                    {"Name":"Reader","Values":["Office"]},
                    {"Name":"End Date","Values":[""]},
                    {"Name":"Meeting Subject","Values":["adb.organization.com"]},
                    {"Name":"SubjectAltName DNS","Values":["adb.organization.com","ade.organization.com","Create.orgaization.com"]}],
"Result":1}

Body:
There are two problem lines in the JSON:

This line has a misplaced "

{"Name":"Opened  On","Values":["Mark, John, L=Toronto, S=Ontario, C=CA","www.doman.com", O=Office, L=Toronto, S=Ontario, C="CA"]},

It should probably be

{"Name":"Opened  On","Values":["Mark, John, L=Toronto, S=Ontario, C=CA","www.doman.com", "O=Office, L=Toronto, S=Ontario, C=CA"]},

And this line

{"Name":"Internet System Address","Values"["www.doman.com/Locations"]},

should have a : after "Values"

{"Name":"Internet System Address","Values":["www.doman.com/Locations"]},

Once you've fixed those issues, the result is valid JSON and can be piped to ConvertFrom-JSON:

$JSON = @"
{"ResultForName":
    [{"Name":"work","Values":["no"]},
    {"Name":"location","Values":["\\pc\\documents"]},
    {"Name":"Authority","Values":["10"]},
    {"Name":"City","Values":["Toronto"]},
    {"Name":"Country","Values":["CA"]},
    {"Name":"Created By","Values":["George"]},
    {"Name":"Money Vault Id","Values":["100000"]},
    {"Name":"Opened  On","Values":["Mark, John, L=Toronto, S=Ontario, C=CA","www.doman.com", "O=Office, L=Toronto, S=Ontario, C=CA"]},
    {"Name":"Driver Name","Values":["Honda"]},
    {"Name":"Can drive","Values":["0"]},
    {"Name":"Given Name","Values":["Steven"]},
    {"Name":"Group Id","Values":["34324"]},
    {"Name":"Internet System Address","Values":["www.doman.com/Locations"]},
    {"Name":"Key value","Values":["AXU"]},
    {"Name":"Key Encryption","Values":["128"]},
    {"Name":"Last Check up","Values":["12\/20\/2018 04:00:08"]},
    {"Name":"Last Notification","Values":["11\/22\/2018 05:00:59"]},
    {"Name":"Last used by","Values":["David"]},
    {"Name":"Last Used On","Values":["09\/11\/2018 14:57:50"]},
    {"Name":"Validation","Values":["02\/22\/2019 04:06:18"]},
    {"Name":"Last Validation query","Values":["Success"]},
    {"Name":"Last Acceptence","Values":["04\/12\/2019 04:10:11"]},
    {"Name":"Managed By","Values":["Manager"]},
    {"Name":"Automatic","Values":["True"]},
    {"Name":"Options","Values":["More options Needed"]},
    {"Name":"Organization","Values":["Organization"]},
    {"Name":"Organizational Unit","Values":["CSV"]},
    {"Name":"Work Location Date","Values":["02\/29\/2019 02:00:40"]},
    {"Name":"URL Details","Values":["CN=web.website.com,O=\"Organization\",OU=CSV,L=Toronto,ST=Ontario,C=CA"]},
    {"Name":"Provence","Values":["Ontario"]},
    {"Name":"Surname","Values":["Johnson"]},
    {"Name":"Transaction value","Values":["23452523"]},
    {"Name":"Validation Acceptance Values",
                    "Values":["111.11.11.11|443|0|11|0|organization.com\\3$","111.11.111.111|443|0|11|0|orgaization.com\\2$","111.11.111.111|443|0|11|0|orgaization.com\\2$"]},
    {"Name":"Acceptance  State","Values":["Success"]},
    {"Name":"Validity Zone","Values":["120"]},
    {"Name":"ClearMode","Values":["0"]},
    {"Name":"Approval CA:Count","Values":["1"]},
    {"Name":"Reader","Values":["Office"]},
    {"Name":"End Date","Values":[""]},
    {"Name":"Meeting Subject","Values":["adb.organization.com"]},
    {"Name":"SubjectAltName DNS","Values":["adb.organization.com","ade.organization.com","Create.orgaization.com"]}],
"Result":1}
"@
$JSON | ConvertFrom-Json


问:
Join tables with JPA
I'm trying to create a JPQL query that gets specific fields from my 3 tables:

idCurso,nombCurso,fRegistro,idProfesor,nombProfe,idAula,descripcion

My entities JPA:

//TABLE: AULA

```<code>@Entity
@Table(name="aulas")
public class Aula implements Serializable{
private static final long serialVersionUID = 1L;

@Id
private String id;
private String descripcion;
@Temporal(TemporalType.DATE)
private Date fRegistro;
private Integer estado;
@OneToMany(mappedBy = "aula",cascade = {CascadeType.ALL})
private List<Curso> curso;
</code>```

//TABLE: PROFESOR

```<code>@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name="profesores")
public class Profesor implements Serializable{

private static final long serialVersionUID = 1L;
@Id
private String id;
private String nombProfe;
@Temporal(TemporalType.DATE)
private Date f_nacimiento;
private Integer estado;
@OneToMany(mappedBy = "profesor", cascade = {CascadeType.ALL})
private List<Curso> curso;
</code>```

//TABLE: CURSO

```<code>@Entity
@Table(name="cursos")
public class Curso implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 1L;

@Id
private String id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "profesor_id")
@JsonIgnore
private Profesor profesor;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "aula_id")
@JsonIgnore
private Aula aula;

private String nomCurso;

@Temporal(TemporalType.DATE)
private Date fRegistro;
</code>```

//REPOSITOY

```<code>public interface CursoRepositorio extends JpaRepository<Curso, String>{}
</code>```

//SERVICE

```<code>@Autowired
CursoRepositorio cursoRepositorio;
@PersistenceContext
private EntityManager em;
    public Curso buscarById(String id)
    {
        return (Curso) em.createQuery("SELECT c.id,c.nomCurso,c.fRegistro,a.id,a.descripcion,p.id,p.nombProfe FROM Curso c JOIN c.aula a JOIN c.profesor p WHERE c.id= :p1")
                .setParameter("p1", id)

      .getResultList();
}
</code>```

//CONTROLLER

```<code>@GetMapping("/curso/{id}")
public Curso CursoById(@PathVariable("id") String id) {
    return cursoServicio.buscarById(id);

}
</code>```

I tried with this query:

```<code>SELECT c.id,c.nomCurso,c.fRegistro,a.id,a.descripcion,p.id,p.nombProfe FROM Curso c JOIN c.aula a JOIN c.profesor p WHERE c.id= :p1
</code>```

error(SOAPUI):

java.util.ArrayList cannot be cast to com.unjfsc.rest.model.Curso

I think maybe I should create a temporary table to make the query easier, but how do I achieve this?

答:
You are trying to cast List on Curso class.
To fix this issue you should do the following:

List<Object[]> results = em.createQuery("SELECT c.id,c.nomCurso,c.fRegistro,a.id,a.descripcion,p.id,p.nombProfe FROM Curso c JOIN c.aula a JOIN c.profesor p WHERE c.id= :p1").setParameter("p1", id).getResultList();

And subsequently, do appropriate mapping, and return properly initialized object from your method.

Title: Join tables with JPA

Body:
I'm trying to create a JPQL query that gets specific fields from my 3 tables:

idCurso,nombCurso,fRegistro,idProfesor,nombProfe,idAula,descripcion

My entities JPA:

//TABLE: AULA

@Entity
@Table(name="aulas")
public class Aula implements Serializable{
private static final long serialVersionUID = 1L;

@Id
private String id;
private String descripcion;
@Temporal(TemporalType.DATE)
private Date fRegistro;
private Integer estado;
@OneToMany(mappedBy = "aula",cascade = {CascadeType.ALL})
private List<Curso> curso;

//TABLE: PROFESOR

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name="profesores")
public class Profesor implements Serializable{

private static final long serialVersionUID = 1L;
@Id
private String id;
private String nombProfe;
@Temporal(TemporalType.DATE)
private Date f_nacimiento;
private Integer estado;
@OneToMany(mappedBy = "profesor", cascade = {CascadeType.ALL})
private List<Curso> curso;

//TABLE: CURSO

@Entity
@Table(name="cursos")
public class Curso implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 1L;

@Id
private String id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "profesor_id")
@JsonIgnore
private Profesor profesor;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "aula_id")
@JsonIgnore
private Aula aula;

private String nomCurso;

@Temporal(TemporalType.DATE)
private Date fRegistro;

//REPOSITOY

public interface CursoRepositorio extends JpaRepository<Curso, String>{}

//SERVICE

@Autowired
CursoRepositorio cursoRepositorio;
@PersistenceContext
private EntityManager em;
    public Curso buscarById(String id)
    {
        return (Curso) em.createQuery("SELECT c.id,c.nomCurso,c.fRegistro,a.id,a.descripcion,p.id,p.nombProfe FROM Curso c JOIN c.aula a JOIN c.profesor p WHERE c.id= :p1")
                .setParameter("p1", id)

      .getResultList();
}

//CONTROLLER

@GetMapping("/curso/{id}")
public Curso CursoById(@PathVariable("id") String id) {
    return cursoServicio.buscarById(id);

}

I tried with this query:

SELECT c.id,c.nomCurso,c.fRegistro,a.id,a.descripcion,p.id,p.nombProfe FROM Curso c JOIN c.aula a JOIN c.profesor p WHERE c.id= :p1

error(SOAPUI):

java.util.ArrayList cannot be cast to com.unjfsc.rest.model.Curso

I think maybe I should create a temporary table to make the query easier, but how do I achieve this?


问:
spplot() - make color.key look nice
I'm afraid I have a spplot() question again.

I want the colors in my spplot() to represent absolute values, not automatic values as spplot does it by default.

I achieve this by making a factor out of the variable I want to draw (using the command cut()). This works very fine, but the color-key doesn't look good at all.

See it yourself:

```<code>library(sp)

data(meuse.grid)
gridded(meuse.grid) = ~x+y

meuse.grid$random <- rnorm(nrow(meuse.grid), 7, 2)
meuse.grid$random[meuse.grid$random < 0] <- 0
meuse.grid$random[meuse.grid$random > 10] <- 10
# making a factor out of meuse.grid$ random to have absolute values plotted
meuse.grid$random <- cut(meuse.grid$random, seq(0, 10, 0.1))

spplot(meuse.grid, c("random"), col.regions = rainbow(100, start = 4/6, end = 1))
</code>```

How can I have the color.key on the right look good - I'd like to have fewer ticks and fewer labels (maybe just one label on each extreme of the color.key)

Thank you in advance!

[edit]
To make clear what I mean with absolute values: Imagine a map where I want to display the sea height. Seaheight = 0 (which is the min-value) should always be displayed blue. Seaheight = 10 (which, just for the sake of the example, is the max-value) should always be displayed red. Even if there is no sea on the regions displayed on the map, this shouldn't change.
I achieve this with the cut() command in my example. So this part works fine.

THIS IS WHAT MY QUESTION IS ABOUT
What I don't like is the color description on the right side. There are 100 ticks and each tick has a label. I want fewer ticks and fewer labels.

答:
The way to go is using the attribute colorkey. For example:</p>

```<code>## labels
labelat = c(1, 2, 3, 4, 5)
labeltext = c("one", "two", "three", "four", "five")

## plot
spplot(meuse.grid,
    c("random"),
    col.regions = rainbow(100, start = 4/6, end = 1),
    colorkey = list(
        labels=list(
            at = labelat,
            labels = labeltext
        )
    )
)
</code>```

ContentLicense: CC BY-SA 2.5

Title: spplot() - make color.key look nice

Body:
I'm afraid I have a spplot() question again.

I want the colors in my spplot() to represent absolute values, not automatic values as spplot does it by default.

I achieve this by making a factor out of the variable I want to draw (using the command cut()). This works very fine, but the color-key doesn't look good at all.

See it yourself:

library(sp)

data(meuse.grid)
gridded(meuse.grid) = ~x+y

meuse.grid$random <- rnorm(nrow(meuse.grid), 7, 2)
meuse.grid$random[meuse.grid$random < 0] <- 0
meuse.grid$random[meuse.grid$random > 10] <- 10
# making a factor out of meuse.grid$ random to have absolute values plotted
meuse.grid$random <- cut(meuse.grid$random, seq(0, 10, 0.1))

spplot(meuse.grid, c("random"), col.regions = rainbow(100, start = 4/6, end = 1))

How can I have the color.key on the right look good - I'd like to have fewer ticks and fewer labels (maybe just one label on each extreme of the color.key)

Thank you in advance!

[edit]
To make clear what I mean with absolute values: Imagine a map where I want to display the sea height. Seaheight = 0 (which is the min-value) should always be displayed blue. Seaheight = 10 (which, just for the sake of the example, is the max-value) should always be displayed red. Even if there is no sea on the regions displayed on the map, this shouldn't change.
I achieve this with the cut() command in my example. So this part works fine.

THIS IS WHAT MY QUESTION IS ABOUT
What I don't like is the color description on the right side. There are 100 ticks and each tick has a label. I want fewer ticks and fewer labels.

Body:
The way to go is using the attribute colorkey. For example:

## labels
labelat = c(1, 2, 3, 4, 5)
labeltext = c("one", "two", "three", "four", "five")

## plot
spplot(meuse.grid,
    c("random"),
    col.regions = rainbow(100, start = 4/6, end = 1),
    colorkey = list(
        labels=list(
            at = labelat,
            labels = labeltext
        )
    )
)


问:
Admob Rewarded Video If the user closes the video without watching it
I'm using WebView and I've set everything up. If the user goes to the site called X, the ads appear. If the user closes the ad without tracking it, I want the WebView page to go back one step. How can I do that? I thought about adding it to the onRewardedVideoAdClosed() side, but the users who are successful in video playback are also taking a step back.

```<code>  @Override
public void onRewardedVideoAdClosed() {
    Toast.makeText(getActivity(), "Reklam sayfası kapatıldı.", Toast.LENGTH_SHORT).show();
    loadRewardedVideoAd();
    webView.goBack(); //doesn't work
}
</code>```

```<code> private void loadRewardedVideoAd() {
    mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
            new AdRequest.Builder().build());
}

@Override
public void onRewarded(RewardItem reward) {
    Toast.makeText(getActivity(), "Başarılı! İçerik görüntüleme hakkı kazandınız. " ,/*+ reward.getType() + "  amount: " + reward.getAmount(),*/ Toast.LENGTH_SHORT).show();
    // Reward the user.

}

@Override
public void onRewardedVideoAdLeftApplication() {
    Toast.makeText(getActivity(), "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoAdClosed() {
    Toast.makeText(getActivity(), "Reklam sayfası kapatıldı.", Toast.LENGTH_SHORT).show();
    loadRewardedVideoAd();
}

@Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
    Toast.makeText(getActivity(), "Reklam yükelmesi başarısız oldu.", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoAdLoaded() {
    Toast.makeText(getActivity(), "Geçiş reklamları hazır.", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoAdOpened() {
    Toast.makeText(getActivity(), "Geçiş reklamı açıldı.", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoStarted() {
    Toast.makeText(getActivity(), "Geçiş reklamı başladı.", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoCompleted() {
    Toast.makeText(getActivity(), "Reklam bitti.", Toast.LENGTH_SHORT).show();
}

@Override
public void onResume() {
    mRewardedVideoAd.resume(getActivity());
    super.onResume();
}

@Override
public void onPause() {
    mRewardedVideoAd.pause(getActivity());
    super.onPause();
}

@Override
public void onDestroy() {
    mRewardedVideoAd.destroy(getActivity());
    super.onDestroy();
}
</code>```

答:
You can simply remember, if the user earned the reward. The following code is based on the new API, but it should be trivial to implement this idea with the old API.</p>

```<code>        RewardedAdCallback adCallback = new RewardedAdCallback() {
            boolean rewardEarned = false;

            @Override
            public void onRewardedAdOpened() {
                // Ad opened.
            }

            @Override
            public void onRewardedAdClosed() {
                loadAd();
                showResponse(rewardEarned ? R.string.rewardEarned : R.string.adAborted);
            }

            @Override
            public void onUserEarnedReward(@NonNull RewardItem reward) {
                rewardEarned = true;
            }

            @Override
            public void onRewardedAdFailedToShow(int errorCode) {
                // Ad failed to display
            }
        };
</code>```

Body:
I'm using WebView and I've set everything up. If the user goes to the site called X, the ads appear. If the user closes the ad without tracking it, I want the WebView page to go back one step. How can I do that? I thought about adding it to the onRewardedVideoAdClosed() side, but the users who are successful in video playback are also taking a step back.

  @Override
public void onRewardedVideoAdClosed() {
    Toast.makeText(getActivity(), "Reklam sayfası kapatıldı.", Toast.LENGTH_SHORT).show();
    loadRewardedVideoAd();
    webView.goBack(); //doesn't work
}

 private void loadRewardedVideoAd() {
    mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
            new AdRequest.Builder().build());
}

@Override
public void onRewarded(RewardItem reward) {
    Toast.makeText(getActivity(), "Başarılı! İçerik görüntüleme hakkı kazandınız. " ,/*+ reward.getType() + "  amount: " + reward.getAmount(),*/ Toast.LENGTH_SHORT).show();
    // Reward the user.

}

@Override
public void onRewardedVideoAdLeftApplication() {
    Toast.makeText(getActivity(), "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoAdClosed() {
    Toast.makeText(getActivity(), "Reklam sayfası kapatıldı.", Toast.LENGTH_SHORT).show();
    loadRewardedVideoAd();
}

@Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
    Toast.makeText(getActivity(), "Reklam yükelmesi başarısız oldu.", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoAdLoaded() {
    Toast.makeText(getActivity(), "Geçiş reklamları hazır.", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoAdOpened() {
    Toast.makeText(getActivity(), "Geçiş reklamı açıldı.", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoStarted() {
    Toast.makeText(getActivity(), "Geçiş reklamı başladı.", Toast.LENGTH_SHORT).show();
}

@Override
public void onRewardedVideoCompleted() {
    Toast.makeText(getActivity(), "Reklam bitti.", Toast.LENGTH_SHORT).show();
}

@Override
public void onResume() {
    mRewardedVideoAd.resume(getActivity());
    super.onResume();
}

@Override
public void onPause() {
    mRewardedVideoAd.pause(getActivity());
    super.onPause();
}

@Override
public void onDestroy() {
    mRewardedVideoAd.destroy(getActivity());
    super.onDestroy();
}

Body:
You can simply remember, if the user earned the reward. The following code is based on the new API, but it should be trivial to implement this idea with the old API.

        RewardedAdCallback adCallback = new RewardedAdCallback() {
            boolean rewardEarned = false;

            @Override
            public void onRewardedAdOpened() {
                // Ad opened.
            }

            @Override
            public void onRewardedAdClosed() {
                loadAd();
                showResponse(rewardEarned ? R.string.rewardEarned : R.string.adAborted);
            }

            @Override
            public void onUserEarnedReward(@NonNull RewardItem reward) {
                rewardEarned = true;
            }

            @Override
            public void onRewardedAdFailedToShow(int errorCode) {
                // Ad failed to display
            }
        };


问:
Using linq to get nth word from each line in a list in C#
Hi I have a list of multi word strings.

```<code>List<string> myList = new List<string>();
myList.Add("Robert is a bank manager");
myList.Add("Alice is a cashier");
myList.Add("Andrew is bank customer");
</code>```

Now for each string line in myList, I wanted to get nth word. So let's say I want to retrieve even number positioned word from each string, I want to get output as:

```<code>var[] output = {"is", "bank", "is", "cashier", "is", "customer"};
</code>```

I can simply use a for loop and store every nth word in the output array, but curious how to do the same using linq.

答:
```<code>var n = 2;
myList.Select(s => s.Split().Where((t, i) => (i - 1) % n == 0))
</code>```

This uses the overload of Where that includes the index as an argument. Note this is not robust/heavily tested/etc.

Body:
Hi I have a list of multi word strings.

List<string> myList = new List<string>();
myList.Add("Robert is a bank manager");
myList.Add("Alice is a cashier");
myList.Add("Andrew is bank customer");

Now for each string line in myList, I wanted to get nth word. So let's say I want to retrieve even number positioned word from each string, I want to get output as:

var[] output = {"is", "bank", "is", "cashier", "is", "customer"};

I can simply use a for loop and store every nth word in the output array, but curious how to do the same using linq.

Body:
var n = 2;
myList.Select(s => s.Split().Where((t, i) => (i - 1) % n == 0))

This uses the overload of Where that includes the index as an argument. Note this is not robust/heavily tested/etc.


问:
react-router-dom not rendering components on route change
If I click on a navigation link, I can see that the slug has changed but the component is not rendering. I have to manually refresh the page in order to see the component, while the page should re-render by itself on route/slug change.

App.js

```<code>import React, { Component } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Me from './components/me';
import Contrib from './components/contrib';
import Projects from './components/projects';
import Contact from './components/contact';

class App extends Component {
  render() {
    return (
      <div className="container">
        <BrowserRouter>
          <Switch>
            <Route exact path="/" component={Me} />
            <Route path="/contrib" component={Contrib} />
            <Route path="/projects" component={Projects} />
            <Route path="/contact" component={Contact} />
          </Switch>
        </BrowserRouter>
      </div>
    );
  }
}
</code>```

header.jsx

```<code>import { BrowserRouter, NavLink} from 'react-router-dom';

const Header = () => {
    return (
        <div className="container">
            <div id="logo">
                <img src={Earth} alt="placeholdit" className="rounded" />
            </div>
            <nav>
                <BrowserRouter>
                    <ul>
                        <li><NavLink to="/">Home</NavLink></li>
                        <li><NavLink to="/contrib">Contributions</NavLink></li>
                        <li><NavLink to="/projects">Projects</NavLink></li>
                        <li><NavLink to="/contact">Contact</NavLink></li>
                        <li></li>
                    </ul>
                </BrowserRouter>
            </nav>
        </div>
    )
}
</code>```

If I remove the <BrowserRouter> from header.jsx I get an error telling me that: "You should not use <Route> or withRouter() outside a <Router>".

If add the <BrowserRouter> inside of header.jsx the error is gone, but the components are not rendering on route/slug change.

答:
I had the same problem. Delete the  from header.jsx and put it in your index.js like this:</p>

```<code>ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>
, document.getElementById('root'));
</code>```

Body:
If I click on a navigation link, I can see that the slug has changed but the component is not rendering. I have to manually refresh the page in order to see the component, while the page should re-render by itself on route/slug change.

App.js

import React, { Component } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Me from './components/me';
import Contrib from './components/contrib';
import Projects from './components/projects';
import Contact from './components/contact';

class App extends Component {
  render() {
    return (

        <BrowserRouter>
          <Switch>
            <Route exact path="/" component={Me} />
            <Route path="/contrib" component={Contrib} />
            <Route path="/projects" component={Projects} />
            <Route path="/contact" component={Contact} />
          </Switch>
        </BrowserRouter>

    );
  }
}

header.jsx

import { BrowserRouter, NavLink} from 'react-router-dom';

const Header = () => {
    return (

                <BrowserRouter>

<NavLink to="/">Home</NavLink>

<NavLink to="/contrib">Contributions</NavLink>

<NavLink to="/projects">Projects</NavLink>

<NavLink to="/contact">Contact</NavLink>

                </BrowserRouter>

    )
}

If I remove the <BrowserRouter> from header.jsx I get an error telling me that: "You should not use <Route> or withRouter() outside a <Router>".

If add the <BrowserRouter> inside of header.jsx the error is gone, but the components are not rendering on route/slug change.

Body:
I had the same problem. Delete the  from header.jsx and put it in your index.js like this:

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>
, document.getElementById('root'));


问:
Functions in Haskell
I'm new to functional programming. I have a basic question.

I'm using the Hugs interpreter,

I would like to write a function in Haskell; I went though several tutorials, but I'm not getting it.

```<code>fact :: Int -> Int
fact n = if n == 0 then
1
else
n * fact (n-1)
</code>```

This gives me a syntax error :-S

```<code>ERROR - Syntax error in input (unexpected `=')
</code>```

答:
I assume you type this right into the interactive prompt. Sadly, these are relatively primitive in Haskell - complex definitions, such as fact, can't be entered at the prompt, at least not in the same way you'd normally write them.

You need to put function definitions etc. into modules, then load those via (e.g.) :load fact.hs. There are resources for Hugs specifically that provide more information on this and other topic (I used http://cvs.haskell.org/Hugs/pages/hugsman/index.html to check my assumptions).

Also note that indentation matters, so the code won't work the way you posted it here even when in a module. Those tutorials will have correct versions. If not, they're useless and you should forget them.

Title: Functions in Haskell

Body:
I'm new to functional programming. I have a basic question.

I'm using the Hugs interpreter,

I would like to write a function in Haskell; I went though several tutorials, but I'm not getting it.

fact :: Int -> Int
fact n = if n == 0 then
1
else
n * fact (n-1)

This gives me a syntax error :-S

ERROR - Syntax error in input (unexpected `=')


答:
One approach to doing this in LINQ would be the following:

```<code>var res = myList.Select(x => x.Split()
                              .Where((_,i) => (i + 1) % 2 == 0))
                .SelectMany(x => x);
</code>```

This creates a list of lists of words that have been filtered via index, then flattens the list of lists down with SelectMany on an identity function.

As @Xiaoy312 points out in the comments, you can simplify this further by using SelectMany outright, resulting in the following:

```<code>var res = myList.SelectMany(x => x.Split().Where((_, i) => (i + 1) % 2 == 0));
</code>```

Title: Using linq to get nth word from each line in a list in C#

Body:
One approach to doing this in LINQ would be the following:

var res = myList.Select(x => x.Split()
                              .Where((_,i) => (i + 1) % 2 == 0))
                .SelectMany(x => x);

This creates a list of lists of words that have been filtered via index, then flattens the list of lists down with SelectMany on an identity function.

As @Xiaoy312 points out in the comments, you can simplify this further by using SelectMany outright, resulting in the following:

var res = myList.SelectMany(x => x.Split().Where((_, i) => (i + 1) % 2 == 0));


问:
how reserve height while display is none
I have a div with default display:none. how do I reserve the height so when the div shows, it does not reshift the elements around it? thanks</p>

答:
Or if you are playing with jQuery fadeIn/fadeOut and need that spot to remain empty but with reserved height, then just wrap around needed element  with fixed height, for example:</p>

```<code><div style="height: 52px;">
     <img id="loader" src="loader.gif />
</div>
</code>```

Body:
Or if you are playing with jQuery fadeIn/fadeOut and need that spot to remain empty but with reserved height, then just wrap around needed element  with fixed height, for example:

<div style="height: 52px;">
     <img id="loader" src="loader.gif />
</div>


问:
Counting the number of occurrences of an ID in a dataframe in R
I have a dataframe with roughly 6000 objects that looks like this:

V1 and V2 are IDs of people who have communicated with each other (messages from V1 to V2), and V3 can be ignored. I am trying to find out the number of persons someone has communicated with i.e. the number of times an ID appears in either column V1 or V2 (I removed the duplicates). Can I use the count function to do this? If so, how?

Body:
With table:

set.seed(1)
df <- data.frame(V1 = sample(x = 50, replace = T),
                 V2 = sample(x = 50, replace = T))

df$V1 <- as.factor(df$V1)
df$V2 <- as.factor(df$V2)
table(df$V1)

> table(df$V1)

 1  2  4  6  7  9 10 11 14 18 19 20 21 24 25 27 28 29 30 32 33 34 35 36 37 39 40 42 44 45 46 47 48 50
 1  1  1  1  1  1  1  3  2  1  1  4  1  1  3  1  1  1  1  1  2  2  2  1  2  2  3  2  1  1  1  1  1  1

table(df$V2)

> table(df$V2)

 3  4  5  7  8 11 12 13 15 16 17 18 20 21 22 23 24 26 31 33 34 36 38 39 40 41 42 44 45 46 49
 1  1  2  1  1  1  1  3  1  1  4  1  2  2  2  2  3  1  1  2  1  2  1  3  1  1  1  4  1  1  1


问:
Set name of attributes of reactive form on HTML - Angular
I have a reative form like this:

```<code>  profileForm = this.fb.group({
    firstName: ['', Validators.required],
    aliases: this.fb.array([
      this.fb.control('')
    ])
  });
</code>```

How can I display firstName?

My HTML:

```<code>  <span>profileForm.controls.firstName</span>
</code>```

This will display profileForm.controls.firstName. How can I can do this?

答:
Try this:</p>

```<code> <span>profileForm.get('firstName').value</span>
</code>```

Body:
I have a reative form like this:

  profileForm = this.fb.group({
    firstName: ['', Validators.required],
    aliases: this.fb.array([
      this.fb.control('')
    ])
  });

How can I display firstName?

My HTML:

  profileForm.controls.firstName

This will display profileForm.controls.firstName. How can I can do this?

Body:
Try this:

 <span>profileForm.get('firstName').value</span>


问:
Keep a job running even after shell window has been closed
I'm writing a simple PS script to start or stop all my VM's hosted in Azure. Doing this sequentially takes forever, so I made this into a Job (i.e. each Start/Stop of the VM is a separate job).

Now the script executes much faster since each Start/Stop action is independent of the other, however if I close the PS shell window the jobs obviously stop and the action doesn't get performed on the VM. What I want is some sort of a "fire and forget" type of action, where I can just run the script, see that it has started executing the jobs then shut down my laptop and pack up.

Is this possible in PS to start a job even if the PS window has been closed?

Thanks

答:
It may not help everyone, but I found that putting try {} finally {} in the job lets you run code in the finally block even after the window closes.

For my scenario, I was deleting a folder in a background job so it was easy to pick up the delete and continue it in the finally block.

Something like:

```<code>Start-Job -ScriptBlock {
    $Directory = "c:\temp"
    try
    {
        del $Directory
    }
    finally
    {
        # If the window was closed, continue deleting here
        if (Test-Path $Directory)
        {
            del $Directory
        }
    }
}
</code>```

Body:
It may not help everyone, but I found that putting try {} finally {} in the job lets you run code in the finally block even after the window closes.

For my scenario, I was deleting a folder in a background job so it was easy to pick up the delete and continue it in the finally block.

Something like:

Start-Job -ScriptBlock {
    $Directory = "c:\temp"
    try
    {
        del $Directory
    }
    finally
    {
        # If the window was closed, continue deleting here
        if (Test-Path $Directory)
        {
            del $Directory
        }
    }
}


问:
MySQL root password change
I have been trying to reset my MySQL root password.  I have run mysqld_safe --skip-grant-tables, updated the root password, and checked the user table to make sure it is there.

Once restarting the MySQL daemon I tried logging in with the new root password that I just set and still get Access denied for user 'root' errors.  I have also tried completely removing and reinstalling MySQL (including removing the my.cnf file) and still no luck. What can I do next?

答:
For the current latest MySQL version (8.0.16), none of these answers worked for me.

After looking at several different answers and combining them together, this is what I ended up using that worked:

```<code>update user set authentication_string='test' where user='root';
</code>```

Title: MySQL root password change

Body:
For the current latest MySQL version (8.0.16), none of these answers worked for me.

After looking at several different answers and combining them together, this is what I ended up using that worked:

update user set authentication_string='test' where user='root';


问:
Why does ActionController process image requests, but not process streaming requests?
When some image was not found (it's "src" attribute points to wrong path), i get following error:

Processing ApplicationController#index (for 127.0.0.1 at 2011-04-12 16:44:19) [GET]

ActionController::RoutingError (No route matches "non-existent-image.jpg" with {:method=>:get}):
    /Library/Ruby/Gems/1.8/gems/ruby-debug-ide-0.4.9/lib/ruby-debug-ide.rb:109:in debug_load'
    /Library/Ruby/Gems/1.8/gems/ruby-debug-ide-0.4.9/lib/ruby-debug-ide.rb:109:indebug_program'
    /Library/Ruby/Gems/1.8/gems/ruby-debug-ide-0.4.9/bin/rdebug-ide:87
    /usr/bin/rdebug-ide:19:in load'
    /usr/bin/rdebug-ide:19
    -e:2:inload'
    -e:2

Rendering rescues/layout (not_found)

But, when there is a HTML5 video element, i don't see any complains of ActionController, when it is not found.

What's going on here ?

答:
It looks like you're generating HTML that looks like  and that path is not defined in your config/routes.rb so it can't be handled by the Rails application.

What you might be intending is:

```<code><%= image_tag('non-existent-image.jpg') %>
</code>```

This will generate a tag that looks like:

```<code><img src="/images/non-existent-image.jpg">
</code>```

So long as that file is present in your public/ folder, it should work.

Body:
It looks like you're generating HTML that looks like <img src="/non-existent-image.jpg"> and that path is not defined in your config/routes.rb so it can't be handled by the Rails application.

What you might be intending is:

<%= image_tag('non-existent-image.jpg') %>

This will generate a tag that looks like:

<img src="/images/non-existent-image.jpg">

So long as that file is present in your public/ folder, it should work.


问:
RegEx for an autocomplete feature
I am writing a search bar with an autocomplete feature that is hooked up to an endpoint. I am using regex to determine the "context" that I am in inside of the query I type in the search bar. The three contexts are "attribute," "value," and "operator." The two operators that are allowed are "AND" and "OR." Below is an example of an example query.

Color: Blue AND Size: "Women's Large" (<-- multi-word values or attribute names are surrounded by quotation marks)

I need my regex to match after you put a space after Blue, and if the user begins type "A/AN/AND/O/OR", I need it to match. Once they have put a space after the operator, I need it to stop matching.

This is the expression I have come up with.

```<code>const contextIsOperator = /[\w\d\s"]+: *[\w\s\d"]+ [\w]*$/
</code>```

It matches once I put a space after "Blue," but matches for everything I put after that. If I replace the last * in the expression with a +, it works when I put a space after "Blue" and start manually typing one of the operators, but not if I just have a space after "Blue."

The pattern I have in my head written in words is:

group of one or more characters/digits/spaces/quotation marks

followed by a colon

followed by an optional space

followed by another group of one or more characters/digits/space/quotation marks

followed by a space (after the value)

followed by one or more characters (this is the operator)

How do I solve this problem?

答:
Edit: this is the final one, check the unit tests here

const regex = /((("[\w\s"'']+(?="\b))"|[\w"'']+):\s?(("[\w\s"'']+(?="\b))"|[\w"'']+)\s(AND|OR)(?=\b\s))+/
```

<p>That monstrosity should match (<code>NOTE: QUOTED KEYS/VALUES MUST BE DOUBLE QUOTED</code>): </p>

```Color: Blue AND "Size5":"Women's Large"
"weird KEy":regularvalue OR otherKey: "quoted value"
```

Title: RegEx for an autocomplete feature

Body:
I am writing a search bar with an autocomplete feature that is hooked up to an endpoint. I am using regex to determine the "context" that I am in inside of the query I type in the search bar. The three contexts are "attribute," "value," and "operator." The two operators that are allowed are "AND" and "OR." Below is an example of an example query.

Color: Blue AND Size: "Women's Large" (<-- multi-word values or attribute names are surrounded by quotation marks)

I need my regex to match after you put a space after Blue, and if the user begins type "A/AN/AND/O/OR", I need it to match. Once they have put a space after the operator, I need it to stop matching.

This is the expression I have come up with.

const contextIsOperator = /[\w\d\s"]+: *[\w\s\d"]+ [\w]*$/

It matches once I put a space after "Blue," but matches for everything I put after that. If I replace the last * in the expression with a +, it works when I put a space after "Blue" and start manually typing one of the operators, but not if I just have a space after "Blue."

The pattern I have in my head written in words is:

group of one or more characters/digits/spaces/quotation marks

followed by a colon

followed by an optional space

followed by another group of one or more characters/digits/space/quotation marks

followed by a space (after the value)

followed by one or more characters (this is the operator)

How do I solve this problem?

Body:
Edit: this is the final one, check the unit tests here

const regex = /((("[\w\s"'']+(?="\b))"|[\w"'']+):\s?(("[\w\s"'']+(?="\b))"|[\w"'']+)\s(AND|OR)(?=\b\s))+/

That monstrosity should match (NOTE: QUOTED KEYS/VALUES MUST BE DOUBLE QUOTED):

Color: Blue AND "Size5":"Women's Large"
"weird KEy":regularvalue OR otherKey: "quoted value"


问:
Header and Navigation-tab on a react-native application

I'm building my first react-native application, and I encountered a problem I could not solve.
on the home screen, I don't want any header, and on the other pages, I would like to keep the navigation option.

I want to build a simple home page, with I buttons sign-up and login, the problem is I can't hide the first header on any of the app pages, i dont know if the problem is in the header, or maybe in some other component?
please review the code below.

```<code>class HomeScreen extends React.Component {

  static navigationOptions =  {
         header:null,
         headerVisible:false
  }

  render() {
    return (
      <ImageBackground source = {backgroundImage} style = {styles.backgroundImage}>
      <View style = {styles.container}>

        <View style = {styles.btn_login}>
         <Button title = "SIGNUP NOW" color='#69428F' onPress ={this._showSignUpPage}/>
        </View>

        <View style = {styles.btn_signup}>
         <Button title = "LOGIN" color='#AAA3A3' onPress = {this._showLoginPage}/>
        </View>

      </View>

      </ImageBackground>
    );
  }
</code>```

```<code>class SignupScreen extends React.Component{
  // this hides the navigation, and i cannot see the navigation
  //  static navigationOptions =  {
  //        header:null,
  // }

  render(){
    return (
    <View style={styles.container_Signup}>
        <Button title="SignupScreen"/>
        <StatusBar barStyle="default" />
      </View>
      );
  }
}
</code>```

```<code>const AppStack = createStackNavigator(
  {
    Home:{
     screen:HomeScreen,
     navigationOptions:{
      header:null
     }
    },
    SIGNUP:SignupScreen,
    LOGIN:LoginScreen
  },
  {
  navigationOptions :{
    header:null
  }});

</code>```

as you can see, I tried placing the header:null inside the class, and inside the stackNavigator, but nothing seems to work.

答:
Try to set header mode none as follow:

```<code>const AppStack = createStackNavigator( {
   Home:{
     screen: HomeScreen,
     navigationOptions: {
       header: null
     }
   },
   SIGNUP: SignupScreen,
   LOGIN: LoginScreen
}, {
   headerMode: "none"
});
</code>```

I hope it help you.

Body:
I'm building my first react-native application, and I encountered a problem I could not solve.
on the home screen, I don't want any header, and on the other pages, I would like to keep the navigation option.

I want to build a simple home page, with I buttons sign-up and login, the problem is I can't hide the first header on any of the app pages, i dont know if the problem is in the header, or maybe in some other component?
please review the code below.

class HomeScreen extends React.Component {

  static navigationOptions =  {
         header:null,
         headerVisible:false
  }

  render() {
    return (
      <ImageBackground source = {backgroundImage} style = {styles.backgroundImage}>
      <View style = {styles.container}>

        <View style = {styles.btn_login}>
         <Button title = "SIGNUP NOW" color='#69428F' onPress ={this._showSignUpPage}/>
        </View>

        <View style = {styles.btn_signup}>
         <Button title = "LOGIN" color='#AAA3A3' onPress = {this._showLoginPage}/>
        </View>

      </View>

      </ImageBackground>
    );
  }

class SignupScreen extends React.Component{
  // this hides the navigation, and i cannot see the navigation
  //  static navigationOptions =  {
  //        header:null,
  // }

  render(){
    return (
    <View style={styles.container_Signup}>
        <Button title="SignupScreen"/>
        <StatusBar barStyle="default" />
      </View>
      );
  }
}

const AppStack = createStackNavigator(
  {
    Home:{
     screen:HomeScreen,
     navigationOptions:{
      header:null
     }
    },
    SIGNUP:SignupScreen,
    LOGIN:LoginScreen
  },
  {
  navigationOptions :{
    header:null
  }});

as you can see, I tried placing the header:null inside the class, and inside the stackNavigator, but nothing seems to work.

Body:
Try to set header mode none as follow:

const AppStack = createStackNavigator( {
   Home:{
     screen: HomeScreen,
     navigationOptions: {
       header: null
     }
   },
   SIGNUP: SignupScreen,
   LOGIN: LoginScreen
}, {
   headerMode: "none"
});

I hope it help you.


问:
Empty variable due to asynchronous callback
There is some very simplified pseudo-ish code to understand the structure of my code.

What would be a simple approach to solve my asynchronous callback dilemma.

The token will be empty when it's used in requestOption. So the following usage of requestOption will not give any results due to the missing token.

```<code>var token = ''
var auth1 = someData
var auth2 = someFunc(auth1)
var auth3 = someOtherData
var auth4 = someOtherFunc(auth3)
var finalAuth = someFinalData
var finalAuth2 = finalAuth.someFinalFunc(auth4, cb)
  cb.onSuccess(result)
    token = result.getToken()

var requestOption = {
  someData: ...,
  'authToken': token,
  someMoreData: ...
}
req = request.post(requestOption)
</code>```

There are many solutions and most of them includes using functions to some extend.

Maybe it is useful to modularize the authentication and processing the the requests in another file.

But I would like to keep it simple and not be dependant on something like this

```<code>var empty = ''
var data = 'xyz'
auth(data, {
    onSuccess: function(res) {
        doSomething(res)
    }
})

function doSomething(var) {
 // do something
}
</code>```

What I found so far couldn't help me without overcomplicating my code.

答:
If you don't want to deal with promises and callbacks then mark your function as async and then await your result, it is syntactic sugar that magically wraps promises for you. When dealing with an async function like a post some will have to wait for the response.

https://javascript.info/async-await

Body:
There is some very simplified pseudo-ish code to understand the structure of my code.

What would be a simple approach to solve my asynchronous callback dilemma.

The token will be empty when it's used in requestOption. So the following usage of requestOption will not give any results due to the missing token.

var token = ''
var auth1 = someData
var auth2 = someFunc(auth1)
var auth3 = someOtherData
var auth4 = someOtherFunc(auth3)
var finalAuth = someFinalData
var finalAuth2 = finalAuth.someFinalFunc(auth4, cb)
  cb.onSuccess(result)
    token = result.getToken()

var requestOption = {
  someData: ...,
  'authToken': token,
  someMoreData: ...
}
req = request.post(requestOption)

There are many solutions and most of them includes using functions to some extend.

Maybe it is useful to modularize the authentication and processing the the requests in another file.

But I would like to keep it simple and not be dependant on something like this

var empty = ''
var data = 'xyz'
auth(data, {
    onSuccess: function(res) {
        doSomething(res)
    }
})

function doSomething(var) {
 // do something
}

What I found so far couldn't help me without overcomplicating my code.


问:
Laravel Migration - Update Enum Options
I'm trying to add an enum option to a table (without losing the current dataset) using the schema builder.

The only thing I've really been able to find about column alteration is http://www.flipflops.org/2013/05/25/modify-an-existing-database-column-in-a-laravel-migration/ and I believe that was written for Laravel3.

Even so, I tried using the DB::query('ALTER TABLE ...'); command but it errored out with  call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'query'.

```<code>DB::query("ALTER TABLE users CHANGE COLUMN permissions permissions ENUM('admin', 'user', 'candidate')");
</code>```

I also tried doing this:

```<code>Schema::table('users', function ($table) {
    $table->enum('permissions', array('admin', 'user', 'candidate'))->default('user');
});
</code>```

but it errors out saying the column already exists.

What's the best way to do what I'm trying to do without losing all the data in that column?

答:
Modifying Columns

Prerequisites

Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column:

```<code>Schema::table('users', function (Blueprint $table) {
    $table->enum('name', [])->change();
});
</code>```

https://laravel.com/docs/5.8/migrations#modifying-columns

Title: Laravel Migration - Update Enum Options

Body:
I'm trying to add an enum option to a table (without losing the current dataset) using the schema builder.

The only thing I've really been able to find about column alteration is http://www.flipflops.org/2013/05/25/modify-an-existing-database-column-in-a-laravel-migration/ and I believe that was written for Laravel3.

Even so, I tried using the DB::query('ALTER TABLE ...'); command but it errored out with  call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'query'.

DB::query("ALTER TABLE users CHANGE COLUMN permissions permissions ENUM('admin', 'user', 'candidate')");

I also tried doing this:

Schema::table('users', function ($table) {
    $table->enum('permissions', array('admin', 'user', 'candidate'))->default('user');
});

but it errors out saying the column already exists.

What's the best way to do what I'm trying to do without losing all the data in that column?

Body:
Modifying Columns

Prerequisites

Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column:

Schema::table('users', function (Blueprint $table) {
    $table->enum('name', [])->change();
});

https://laravel.com/docs/5.8/migrations#modifying-columns


答:
Wow, people are quick on this one! Here's how I would implement it in a method:

```<code>public static IEnumerable<string> GetEveryNthWord(string input, int n)
{
    return input.Split().Where((value, index) => (index + 1) % n == 0);
}

public static IEnumerable<string> GetEveryNthWord(IEnumerable<string> input, int n)
{
    return input.SelectMany(sentence => GetEveryNthWord(sentence, n));
}
</code>```

And in use:

```<code>private static void Main()
{
    var myList = new List<string>
    {
        "Robert is a bank manager",
        "Alice is a cashier",
        "Andrew is bank customer"
    };

    var result = GetEveryNthWord(myList, 2).ToList();

    /* result
        Count = 6
            [0]: "is"
            [1]: "bank"
            [2]: "is"
            [3]: "cashier"
            [4]: "is"
            [5]: "customer"
    */
}
</code>```

Body:
Hi I have a list of multi word strings.

List<string> myList = new List<string>();
myList.Add("Robert is a bank manager");
myList.Add("Alice is a cashier");
myList.Add("Andrew is bank customer");

Now for each string line in myList, I wanted to get nth word. So let's say I want to retrieve even number positioned word from each string, I want to get output as:

var[] output = {"is", "bank", "is", "cashier", "is", "customer"};

I can simply use a for loop and store every nth word in the output array, but curious how to do the same using linq.

Body:
Wow, people are quick on this one! Here's how I would implement it in a method:

public static IEnumerable<string> GetEveryNthWord(string input, int n)
{
    return input.Split().Where((value, index) => (index + 1) % n == 0);
}

public static IEnumerable<string> GetEveryNthWord(IEnumerable<string> input, int n)
{
    return input.SelectMany(sentence => GetEveryNthWord(sentence, n));
}

And in use:

private static void Main()
{
    var myList = new List<string>
    {
        "Robert is a bank manager",
        "Alice is a cashier",
        "Andrew is bank customer"
    };

    var result = GetEveryNthWord(myList, 2).ToList();

    /* result
        Count = 6
            [0]: "is"
            [1]: "bank"
            [2]: "is"
            [3]: "cashier"
            [4]: "is"
            [5]: "customer"
    */
}


问:
how secure is the Ticket.UserData in User.Identity in asp.net
My website uses ASP.NET's forms authentication and i am inserting user specific information into the UserData portion of the authentication ticket/cookie. Since the UserData is inside the authentication ticket it is encrypted like so

```<code>authCookie.Value = FormsAuthentication.Encrypt(newTicket);
</code>```

Now I am not too worried about the data being compromised at this point since it's encrypted. but i noticed that the data is available in unencrypted form like this

```<code>FormsIdentity fid = User.Identity as FormsIdentity;
string plainTextUserData = fid.Ticket.UserData;
</code>```

The data itself is not too important. i am still ok even if other people can see it. but i cannot allow people to hijack this information and start using it as their own. for example, i don't want one user to be logged in pretending to be a different user (based on the userID contained in UserData

Is this something I have to worry about?

Edit 1:

The reason i want to do this is so i can stop using sessions and just use cookies and Ticket.UserData

Edit 2:

The data in Ticket.UserData is not changing. it's constant once the user is logged in.

答:
i need more data on certain pages
  depending on what the user does. right
  now i am using sessions but now i want
  to move everything over into cookies.
  it's not a lot of data so i figured i
  could piggyback everything into the
  auth ticket/cookie

@jorsh1 based on your commend to @Portman, Ticket.UserData isn't the place to store changing data. You don't want to recreate the authentication ticket all the time when going from one page to another.

Either use Session data with the Session Service or Sql Server. If you don't want the data in session, and the data is small and not sensitive then use a cookie. (*)

The MS canonical example with UserData is to store things like a list of Roles so that you can say things like "Do I think this user is an admin" but if it's something like an admin role, you'd probably hit the database to check before you implicitly trust what's in the cookie.

string plainTextUserData = fid.Ticket.UserData;

This does work inside your app only because Asp.Net has already decrypted the ticket for you. However, if you want to set the data IIRC you need to recreate and reattach the forms authentication cookie.

```<code>FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    currentTicket.Version + 1,
    currentUser.UserName,
    now,
    now.Add(formsAuthentication.Timeout),
    false,
    "new user data string",
    FormsAuthentication.FormsCookiePath);

string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
    FormsAuthentication.FormsCookieName,
    hash);

Response.Cookies.Add(cookie);
</code>```

Another App can't decode this ticket unless it knows the decryption key or it was brute-forced. If you load-balance the App or use web gardens, you even need to keep the keys in sync.

* I'm not a proponent of storing things in session. Usually there's another way to persist that data.

[edit] What I use session for:

The only thing I often find myself doing is storing a lite version of the users critical data in the session-server based session. We however make it transparently-loaded, and make sure not to duplicate what's in the Ticket.

That way we don't expose anything sensitive in cookies, and we don't rely on session. We also set aggressive session reclamation. Combined with the small amount of data being stored in session, sessions don't cause us problems, and as only 1 piece of code knows whats in the session, we could refactor it easily.

For anything else, sessions are evil. I prefer to maintain viewstate within a page that needs it, or otherwise just persist the temporary state in the database.

Body:
My website uses ASP.NET's forms authentication and i am inserting user specific information into the UserData portion of the authentication ticket/cookie. Since the UserData is inside the authentication ticket it is encrypted like so

authCookie.Value = FormsAuthentication.Encrypt(newTicket);

Now I am not too worried about the data being compromised at this point since it's encrypted. but i noticed that the data is available in unencrypted form like this

FormsIdentity fid = User.Identity as FormsIdentity;
string plainTextUserData = fid.Ticket.UserData;

The data itself is not too important. i am still ok even if other people can see it. but i cannot allow people to hijack this information and start using it as their own. for example, i don't want one user to be logged in pretending to be a different user (based on the userID contained in UserData

Is this something I have to worry about?

Edit 1:

The reason i want to do this is so i can stop using sessions and just use cookies and Ticket.UserData

Edit 2:

The data in Ticket.UserData is not changing. it's constant once the user is logged in.

LastEditorDisplayName: Rich B

Body:
i need more data on certain pages
  depending on what the user does. right
  now i am using sessions but now i want
  to move everything over into cookies.
  it's not a lot of data so i figured i
  could piggyback everything into the
  auth ticket/cookie

@jorsh1 based on your commend to @Portman, Ticket.UserData isn't the place to store changing data. You don't want to recreate the authentication ticket all the time when going from one page to another.

Either use Session data with the Session Service or Sql Server. If you don't want the data in session, and the data is small and not sensitive then use a cookie. (*)

The MS canonical example with UserData is to store things like a list of Roles so that you can say things like "Do I think this user is an admin" but if it's something like an admin role, you'd probably hit the database to check before you implicitly trust what's in the cookie.

string plainTextUserData = fid.Ticket.UserData;

This does work inside your app only because Asp.Net has already decrypted the ticket for you. However, if you want to set the data IIRC you need to recreate and reattach the forms authentication cookie.

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    currentTicket.Version + 1,
    currentUser.UserName,
    now,
    now.Add(formsAuthentication.Timeout),
    false,
    "new user data string",
    FormsAuthentication.FormsCookiePath);

string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
    FormsAuthentication.FormsCookieName,
    hash);

Response.Cookies.Add(cookie);

Another App can't decode this ticket unless it knows the decryption key or it was brute-forced. If you load-balance the App or use web gardens, you even need to keep the keys in sync.

* I'm not a proponent of storing things in session. Usually there's another way to persist that data.

[edit] What I use session for:

The only thing I often find myself doing is storing a lite version of the users critical data in the session-server based session. We however make it transparently-loaded, and make sure not to duplicate what's in the Ticket.

That way we don't expose anything sensitive in cookies, and we don't rely on session. We also set aggressive session reclamation. Combined with the small amount of data being stored in session, sessions don't cause us problems, and as only 1 piece of code knows whats in the session, we could refactor it easily.

For anything else, sessions are evil. I prefer to maintain viewstate within a page that needs it, or otherwise just persist the temporary state in the database.

OwnerDisplayName: Robert Paulson

LastEditorDisplayName: Robert Paulson