问:
Cannot handle a Dataflow failed state after wait_to_finish()
I have a Python script that run a Beam/Dataflow jobs

```<code># add config
p = beam.Pipeline(options=pipeline_options)
# multiple dataflow processes . . .
# in some process I tryna raise the error to make dataflow job failed

result = p.run()
job_status = result.wait_until_finish()
if job_status == "FAILED":
   # run something else
</code>```

As code above, I am trying to handle a case where Dataflow job might failed which there will be a process in case its failed. But after trying with both Direct runner and Dataflow runner. The job ended at the exception I raised in the function. But for the case if the job success it can handle the job_status function e.g. job_status == "DONE"

The wait_until_finish() will return the final state of the pipeline. So, I think I can make use of this function to handle the failed job but its not working. Any idea?

The log shown in Dataflow console show the Exception I raised and its end like that without running anything in my IF condition

Edit:
I found this from Dataflow document that it the wait_til_finish() handle non-success like this. Not sure if there's an alternative to do this?

Edit:
What my job actually did is to scrape a data from some website and push it to GCS. The failed part is always on the scraping function where I somehow get 403 by the website in which I have to fix it by running the new Dataflow job manually. I just want to use this to handle to start new job automatically.

```<code>def scrape_data():
  # scrape data and return a json

def load_to_gcs():
  # dump json to gcs

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    known_args, pipeline_args = parser.parse_known_args(sys.argv)

    # Parse pipeline paramerters
    pipeline_options = PipelineOptions(pipeline_args)
    pipeline_options.view_as(SetupOptions).save_main_session = True

    p = beam.Pipeline(options=pipeline_options)
    id_list = ['aa','bb','cc'] # input param for scrape_data()
    id = p | "init"  >> beam.Create(id_list)
    js = id | "scrape" >> beam.Map(scrape_data)
    js | "load to gcs" >> beam.Map(load_to_gcs)
    result = p.run()
    job_status = result.wait_until_finish()
    if job_status == "FAILED":
       # run something else >> call dataflow api to start new job

</code>```

When its failed (during scrape) the dataflow job will automatically retry for another 4 times and the job will fail. But once its failed, it did not go into the if condition.

答: This issue has been raised in this issue tracker. We cannot provide an ETA at this moment but you can follow the progress in the issue tracker and you can ‘STAR’ the issue to receive automatic updates and give it traction by referring to this Link.</p>

Body:
I have a Python script that run a Beam/Dataflow jobs

# add config
p = beam.Pipeline(options=pipeline_options)
# multiple dataflow processes . . .
# in some process I tryna raise the error to make dataflow job failed

result = p.run()
job_status = result.wait_until_finish()
if job_status == "FAILED":
   # run something else

As code above, I am trying to handle a case where Dataflow job might failed which there will be a process in case its failed. But after trying with both Direct runner and Dataflow runner. The job ended at the exception I raised in the function. But for the case if the job success it can handle the job_status function e.g. job_status == "DONE"

The wait_until_finish() will return the final state of the pipeline. So, I think I can make use of this function to handle the failed job but its not working. Any idea?

The log shown in Dataflow console show the Exception I raised and its end like that without running anything in my IF condition

Edit:
I found this from Dataflow document that it the wait_til_finish() handle non-success like this. Not sure if there's an alternative to do this?

Edit:
What my job actually did is to scrape a data from some website and push it to GCS. The failed part is always on the scraping function where I somehow get 403 by the website in which I have to fix it by running the new Dataflow job manually. I just want to use this to handle to start new job automatically.

def scrape_data():
  # scrape data and return a json

def load_to_gcs():
  # dump json to gcs

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    known_args, pipeline_args = parser.parse_known_args(sys.argv)

    # Parse pipeline paramerters
    pipeline_options = PipelineOptions(pipeline_args)
    pipeline_options.view_as(SetupOptions).save_main_session = True

    p = beam.Pipeline(options=pipeline_options)
    id_list = ['aa','bb','cc'] # input param for scrape_data()
    id = p | "init"  >> beam.Create(id_list)
    js = id | "scrape" >> beam.Map(scrape_data)
    js | "load to gcs" >> beam.Map(load_to_gcs)
    result = p.run()
    job_status = result.wait_until_finish()
    if job_status == "FAILED":
       # run something else >> call dataflow api to start new job

When its failed (during scrape) the dataflow job will automatically retry for another 4 times and the job will fail. But once its failed, it did not go into the if condition.


来源: stackexchange

问:
How to check if a suspend function has completed executing
Hello I have a suspend function updateUserWithNewPersonalDetails(), I want check if the function has been executed and once executed I want to call success() function.

I am unable to use invokeOnCompletion  on the function call

How can I do this please or what is the other way I can call success() function once updateUserWithNewPersonalDetails is executed

suspend function

```<code>suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
    userDao.get().collect { cachedUser ->
        val updatedCachedUser = UserDB(cachedUser.id, ...)
        userDao.save(updatedCachedUser)
    }
}
</code>```

from viewmodel I want to call the above function and on success or invoke successfull I want to call success function

```<code> userRepo.updateUserWithNewPersonalDetails(details). invokeOnCompletion{

                        success()
}
</code>```

Thanks
R

答:
Currently your function updateUserWithNewPersonalDetails never completes because the Flow returned by Room never completes (it monitors for DB changes forever).

Assuming you are interested only in the first change you can do:

```<code>suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
        val cachedUSer = userDao.get().first() // this will get the current value from the DB
        val updatedCachedUser = UserDB(cachedUser.id, ...)
        userDao.save(updatedCachedUser)
    }

</code>```

Here first() gets the current value from the DB (or throws if it doesn't exist) and does NOT observe forever. Alternatively you can use firstOrNull().

Then your other function becomes:

```<code>updateUserWithNewPersonalDetails()
success()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hello I have a suspend function updateUserWithNewPersonalDetails(), I want check if the function has been executed and once executed I want to call success() function.

I am unable to use invokeOnCompletion  on the function call

How can I do this please or what is the other way I can call success() function once updateUserWithNewPersonalDetails is executed

suspend function

suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
    userDao.get().collect { cachedUser ->
        val updatedCachedUser = UserDB(cachedUser.id, ...)
        userDao.save(updatedCachedUser)
    }
}

from viewmodel I want to call the above function and on success or invoke successfull I want to call success function

 userRepo.updateUserWithNewPersonalDetails(details). invokeOnCompletion{

                        success()
}

Thanks
R

Body:
Currently your function updateUserWithNewPersonalDetails never completes because the Flow returned by Room never completes (it monitors for DB changes forever).

Assuming you are interested only in the first change you can do:

suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
        val cachedUSer = userDao.get().first() // this will get the current value from the DB
        val updatedCachedUser = UserDB(cachedUser.id, ...)
        userDao.save(updatedCachedUser)
    }

Here first() gets the current value from the DB (or throws if it doesn't exist) and does NOT observe forever. Alternatively you can use firstOrNull().

Then your other function becomes:

updateUserWithNewPersonalDetails()
success()


问:
How to implement CI/CD using Jenkins for non GitHub repository?
I have repo in my server without GitHub and just want to check that is there any possibility of implementing the Jenkins CI/CD for this repo.

If possible, please direct me to some documentation.

答: GitHub is not a pre-requisite forJenkins nor Git. You can use amy remote repository store, including local or file for your pipeline, as documented in the git plugin configuration, repository url


问:
Angular: how to initialize variable inside *ngFor
I have an Angular template:

  <input type="radio" class="form-check-input" id="radio-{{rand}}" name="field-radio"
    [value]="item.key">

    {{ item.key }}

```

I want to execute random() function for every iteration of loop. But I get an error:

Property 'random' does not exist on type...

How can I use internal variable inside Angular template?

答:
You can't create a custom local variable within a ngFor. You can only use the exported values that can be aliased to local variables. Perhaps, you need another array of random numbers to use in your iteration at the same time like bellow :

```<code><li *ngFor="let item of list | keyvalue; let i = index">
  <input type="radio" class="form-check-input" id="radio-{{random[i]}}" name="field-radio"
    [value]="item.key">
  <label class="form-check-label" for="radio-{{random[i]}}">
    {{ item.key }}
  </label>
</li>
</code>```

Body:
I have an Angular template:

  <input type="radio" class="form-check-input" id="radio-{{rand}}" name="field-radio"
    [value]="item.key">

    {{ item.key }}

I want to execute random() function for every iteration of loop. But I get an error:

Property 'random' does not exist on type...

How can I use internal variable inside Angular template?

Body:
You can't create a custom local variable within a ngFor. You can only use the exported values that can be aliased to local variables. Perhaps, you need another array of random numbers to use in your iteration at the same time like bellow :

<li *ngFor="let item of list | keyvalue; let i = index">
  <input type="radio" class="form-check-input" id="radio-{{random[i]}}" name="field-radio"
    [value]="item.key">
  <label class="form-check-label" for="radio-{{random[i]}}">
    {{ item.key }}
  </label>
</li>


问:
Spring specification avoid unexpected CROSS JOIN
I have 2 entities:

1 is the Org Structure (with a self-join refers to its parent org structure)

2 is the Device (has FK from OrgStructure)

```<code>public class OrgStructure{

   @Id
   private Long id;

   @ManyToOne
   private OrgStructure parentOrgStructure;

}
</code>```
```<code>public class Device {

   @Id
   private Long id;

   @ManyToOne
   private OrgStructure hospitalRoom
}
</code>```

I have 1 specification which generates a CROSS JOIN query. My question is how to avoid unnecessary CROSS JOIN like this

```<code>criteriaBuilder.equal(root.get(Device_.orgStructure).get(OrgStructure_.parentOrgStructure).get(OrganizationStructure_.id), *param goes here*)
</code>```
```<code>The generated query:
SELECT
    *
FROM
    devices device0_
CROSS JOIN org_structures organizati1_
WHERE
    device0_.hospital_room_id = organizati1_.id_organization_structure
    AND organizati1_.organization_structure_id =?
</code>```

答:
please change :

```<code>root.get(Device_.orgStructure).get(OrgStructure_.parentOrgStructure)
</code>```

to

```<code>root.join(Device_.orgStructure).join(OrgStructure_.parentOrgStructure)
</code>```

Body:
I have 2 entities:

1 is the Org Structure (with a self-join refers to its parent org structure)

2 is the Device (has FK from OrgStructure)

public class OrgStructure{

   @Id
   private Long id;

   @ManyToOne
   private OrgStructure parentOrgStructure;

}

public class Device {

   @Id
   private Long id;

   @ManyToOne
   private OrgStructure hospitalRoom
}

I have 1 specification which generates a CROSS JOIN query. My question is how to avoid unnecessary CROSS JOIN like this

criteriaBuilder.equal(root.get(Device_.orgStructure).get(OrgStructure_.parentOrgStructure).get(OrganizationStructure_.id), *param goes here*)

The generated query:
SELECT
    *
FROM
    devices device0_
CROSS JOIN org_structures organizati1_
WHERE
    device0_.hospital_room_id = organizati1_.id_organization_structure
    AND organizati1_.organization_structure_id =?

Body:
please change :

root.get(Device_.orgStructure).get(OrgStructure_.parentOrgStructure)

to

root.join(Device_.orgStructure).join(OrgStructure_.parentOrgStructure)


问:
Next.js middleware Module not found: Can't resolve 'fs'
Getting this error in Next.js _middleware file when I try to initialize Firebase admin V9. Anyone know how to solve this issue?

```<code>./node_modules/@google-cloud/storage/build/src/bucket.js:22:0
Module not found: Can't resolve 'fs'
</code>```

../../firebase/auth-admin

```<code>import * as admin from "firebase-admin";

if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert({
      projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: process.env.FIREBASE_ADMIN_PRIVATE_KEY,
    }),
  });
}

const firestore = admin.firestore();

const auth = admin.auth();

export { firestore, auth };
</code>```

Calling it in my _middleware

```<code>import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { auth } from "../../firebase/auth-admin";

export default async function authenticate(
  req: NextRequest,
  ev: NextFetchEvent
) {
  const token = req.headers.get("token");
  console.log("auth = ", auth);
  //   const decodeToken = await auth.verifyIdToken(token);
  return NextResponse.next();
}
</code>```

I saw a solution here by customizing webpack but this does not fix it.

```<code>/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: (config, { isServer, node }) => {
    node = {
      ...node,
      fs: "empty",
      child_process: "empty",
      net: "empty",
      tls: "empty",
    };
    return config;
  },
};

module.exports = nextConfig;
</code>```

答:
The Edge Runtime, which is used by Next.js Middleware, does not support Node.js native APIs.

From the Edge Runtime documentation:

The Edge Runtime has some restrictions including:

Native Node.js APIs are not supported. For example, you can't read or write to the filesystem

Node Modules can be used, as long as they implement ES Modules and do not use any native Node.js APIs

You can't use Node.js libraries that use fs in Next.js Middleware. Try using a client-side library instead.

Body:
Getting this error in Next.js _middleware file when I try to initialize Firebase admin V9. Anyone know how to solve this issue?

./node_modules/@google-cloud/storage/build/src/bucket.js:22:0
Module not found: Can't resolve 'fs'

../../firebase/auth-admin

import * as admin from "firebase-admin";

if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert({
      projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: process.env.FIREBASE_ADMIN_PRIVATE_KEY,
    }),
  });
}

const firestore = admin.firestore();

const auth = admin.auth();

export { firestore, auth };

Calling it in my _middleware

import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { auth } from "../../firebase/auth-admin";

export default async function authenticate(
  req: NextRequest,
  ev: NextFetchEvent
) {
  const token = req.headers.get("token");
  console.log("auth = ", auth);
  //   const decodeToken = await auth.verifyIdToken(token);
  return NextResponse.next();
}

I saw a solution here by customizing webpack but this does not fix it.

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: (config, { isServer, node }) => {
    node = {
      ...node,
      fs: "empty",
      child_process: "empty",
      net: "empty",
      tls: "empty",
    };
    return config;
  },
};

module.exports = nextConfig;


问:
.NET MVC - Submitting multiple models of the same type at once
I think I've got a pretty simple scenario but can't seem to grasp how to do it in .NET's MVC framework.  At its simplest, this is a form that has people with a ranking.  I'd like to have each person's name and a textbox next to their name listed on one page.  Here's what the (Razor) Html looks like:

```<code>@using (Html.BeginForm()) {
<fieldset>
    @foreach (var b in Model.Ballots) {
        <p>
            <label>@b.Person.FullName</label>
            @Html.TextBox("Rank")
            @Html.ValidationMessage("Rank")
        </p>
    }
</fieldset>
 <input type="submit" value="Vote" />
</code>```

}

A ballot is a simple object that has a person and a ranking:

```<code>public class Ballot {
    public Person Person { get; set; }
    [Range(1, 6, ErrorMessage="The voting range is 1 through 6")]
    public int Rank { get; set; }
}
</code>```

Here's my controller's method for handling the form submission, but it never gets called.

```<code>[AcceptVerbs("POST")]
    public ActionResult Vote(IEnumerable<Ballot> ballots) {

        return View("BallotComplete");
    }
</code>```

How do I go about iterating all the models that the form submits back to the server?

答:
I did a quick example using a Customer object, but I think it's similar.  Note how the form fields are labeled. Prefixed with name of parameter in action in controller. Index is needed to treat as a collection. Yours might be slightly more complex, because you have a nested class. (Person inside of ballot). I think by doing customers[@counter].Person.Id for form fields would work though. Sorry I didn't have an example with ballots. :)

This would be the relevant part of the View:

```<code>@using (Html.BeginForm())
{
    var counter = 0;
    foreach (var customer in this.Model)
     {
         <input type="text" name="customers[@counter].Id" value="@customer.Id"/>
         <input type="text" name="customers[@counter].CompanyName" value="@customer.CompanyName"/>
         counter++;
     }
     <input type="submit" />
}
</code>```

and this would be the relevant part of the controller:

```<code>public ActionResult Test()
{
    return View(Service.GetCustomers());
}

[HttpPost]
public ActionResult Test(Customer[] customers )
{
    return View(customers);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think I've got a pretty simple scenario but can't seem to grasp how to do it in .NET's MVC framework.  At its simplest, this is a form that has people with a ranking.  I'd like to have each person's name and a textbox next to their name listed on one page.  Here's what the (Razor) Html looks like:

@using (Html.BeginForm()) {
<fieldset>
    @foreach (var b in Model.Ballots) {

            @b.Person.FullName
            @Html.TextBox("Rank")
            @Html.ValidationMessage("Rank")

    }
</fieldset>
 <input type="submit" value="Vote" />

}

A ballot is a simple object that has a person and a ranking:

public class Ballot {
    public Person Person { get; set; }
    [Range(1, 6, ErrorMessage="The voting range is 1 through 6")]
    public int Rank { get; set; }
}

Here's my controller's method for handling the form submission, but it never gets called.

[AcceptVerbs("POST")]
    public ActionResult Vote(IEnumerable<Ballot> ballots) {

        return View("BallotComplete");
    }

How do I go about iterating all the models that the form submits back to the server?

Body:
I did a quick example using a Customer object, but I think it's similar.  Note how the form fields are labeled. Prefixed with name of parameter in action in controller. Index is needed to treat as a collection. Yours might be slightly more complex, because you have a nested class. (Person inside of ballot). I think by doing customers[@counter].Person.Id for form fields would work though. Sorry I didn't have an example with ballots. :)

This would be the relevant part of the View:

@using (Html.BeginForm())
{
    var counter = 0;
    foreach (var customer in this.Model)
     {
         <input type="text" name="customers[@counter].Id" value="@customer.Id"/>
         <input type="text" name="customers[@counter].CompanyName" value="@customer.CompanyName"/>
         counter++;
     }
     <input type="submit" />
}

and this would be the relevant part of the controller:

public ActionResult Test()
{
    return View(Service.GetCustomers());
}

[HttpPost]
public ActionResult Test(Customer[] customers )
{
    return View(customers);
}


问:
How can change the display of the product images on the PDP? Spartacus
Im new with spartacus and angular and I am trying to change the style that spartacus brings by default in the PDP, more specifically the images component. I want to delete the carrousel and put the images one on top of the other, as it appears in the capybara theme. i have made a new component for this but i can't loop over the images, I can't find in the product object where the images are.

I've tried  {{product.images}}, {{product.images.GALLERY[0].product}}    {{product.images.GALLERY[0].thumbnail}} and i get [Object Object]

thanks in advance!

look like this

答:
Try using the cx-media tag:</p>
```<code><cx-media class="cx-product-image"
                  [container]="product.images?.PRIMARY"
                  format="product"
                  [alt]="product.summary">
</cx-media>
</code>```

Body:
Try using the cx-media tag:

<cx-media class="cx-product-image"
                  [container]="product.images?.PRIMARY"
                  format="product"
                  [alt]="product.summary">
</cx-media>


问:
EF Core domain-wide value conversion for (nested) owned types
I have several value objects (DDD paradigm) set up in EF Core as Owned Types.

EF Core supports configuring owned types in a way that it will automatically treat all references to the given type as an owned type, via the Owned() method.

However, I cannot seem to find a way to specify their configuration, especially value conversion, in a similar, centralized manner.

    {   // Configure value objects as owned types.
        builder.Owned(typeof(Money));
        builder.Owned(typeof(Currency));
        builder.Owned(typeof(Address));
        builder.Owned(typeof(Mass));
        builder.Owned(typeof(MassUnit));

        // Store and restore mass unit as symbol.
        builder.Entity<Product>()
            .OwnsOne(p => p.Mass, c => c.Property(m => m.Unit)
                .HasConversion(
                    u => u.Symbol,
                    s => MassUnit.FromSymbol(s))
                .HasMaxLength(3)
            );
    }
```

As you can see above, there is a value conversion configured for MassUnit, which is a Value Object nested in Mass.

But I'd have to do this manually for all places where the value objects are used. For example I'm already using the Money type at 3 distinct places, and this type contains Currency, for which I'd wish to configure a similar value conversion.

Is there any (good) way to specify general, domain-wide configuration for the owned types?

I already tried to configure them through builder.Entity<Mass>().Property(m => m.Unit).HasConversion(..), but it seems that EF Core throws if you try to configure an owned type via Entity<>.

答:
This is possible using a shared ValueConverter:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    var converter = new ValueConverter<EquineBeast, string>(
        v => v.ToString(),
        v => (EquineBeast)Enum.Parse(typeof(EquineBeast), v));

    modelBuilder
        .Entity<Rider>()
        .Property(e => e.Mount)
        .HasConversion(converter);
}
```

Body:
I have several value objects (DDD paradigm) set up in EF Core as Owned Types.

EF Core supports configuring owned types in a way that it will automatically treat all references to the given type as an owned type, via the Owned() method.

However, I cannot seem to find a way to specify their configuration, especially value conversion, in a similar, centralized manner.

    {   // Configure value objects as owned types.
        builder.Owned(typeof(Money));
        builder.Owned(typeof(Currency));
        builder.Owned(typeof(Address));
        builder.Owned(typeof(Mass));
        builder.Owned(typeof(MassUnit));

        // Store and restore mass unit as symbol.
        builder.Entity<Product>()
            .OwnsOne(p => p.Mass, c => c.Property(m => m.Unit)
                .HasConversion(
                    u => u.Symbol,
                    s => MassUnit.FromSymbol(s))
                .HasMaxLength(3)
            );
    }

As you can see above, there is a value conversion configured for MassUnit, which is a Value Object nested in Mass.

But I'd have to do this manually for all places where the value objects are used. For example I'm already using the Money type at 3 distinct places, and this type contains Currency, for which I'd wish to configure a similar value conversion.

Is there any (good) way to specify general, domain-wide configuration for the owned types?

I already tried to configure them through builder.Entity<Mass>().Property(m => m.Unit).HasConversion(..), but it seems that EF Core throws if you try to configure an owned type via Entity<>.


问:
Getting a unique_ptr out of a priority queue
I am maintaining a set of unique_ptr instances in a priority_queue. At some point, I want to get the first element and remove it from the queue. However, this always produces a compiler error. See sample code below.

```<code>int main ()
{
  std::priority_queue<std::unique_ptr<int>> queue;
  queue.push(std::unique_ptr<int>(new int(42)));

  std::unique_ptr<int> myInt = std::move(queue.top());
  return 1;
}
</code>```

This produces the following compiler error (gcc 4.8.0):

```<code>uptrtest.cpp: In function ‘int main()’: uptrtest.cpp:6:53: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’    std::unique_ptr<int> myInt = std::move(queue.top());
                                                     ^ In file included from /usr/include/c++/4.8/memory:81:0,
                 from uptrtest.cpp:1: /usr/include/c++/4.8/bits/unique_ptr.h:273:7: error: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^
</code>```

Changing the code to use queue like in this question fixes the issue and the code compiles just fine.

Is there no way to keep unique_ptrs in a priority_queue or am I missing something?

答:
Since std::priority_queue::top() returns a const reference, we have to use some alternative approach for addressing it. Depending on your objects' life time, you may choose this solution:

store a const MyObject * as the value in the priority_queue

std::priority_queue::top() will give you an const MyObject *

use the const_cast (https://en.cppreference.com/w/cpp/language/const_cast) to drop the const qualifier from the pointer

With this solution, if you need to manage the objects' life time as well, you may manage the unique_ptr outside of priority_queue in another container while still leveraing priority_queue's capability for ordering your objects.

Body:
I am maintaining a set of unique_ptr instances in a priority_queue. At some point, I want to get the first element and remove it from the queue. However, this always produces a compiler error. See sample code below.

int main ()
{
  std::priority_queue<std::unique_ptr<int>> queue;
  queue.push(std::unique_ptr<int>(new int(42)));

  std::unique_ptr<int> myInt = std::move(queue.top());
  return 1;
}

This produces the following compiler error (gcc 4.8.0):

uptrtest.cpp: In function ‘int main()’: uptrtest.cpp:6:53: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’    std::unique_ptr<int> myInt = std::move(queue.top());
                                                     ^ In file included from /usr/include/c++/4.8/memory:81:0,
                 from uptrtest.cpp:1: /usr/include/c++/4.8/bits/unique_ptr.h:273:7: error: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^

Changing the code to use queue like in this question fixes the issue and the code compiles just fine.

Is there no way to keep unique_ptrs in a priority_queue or am I missing something?


问:
How do I import NON-CSV-DELIMITED ASCII data into SQLite 3?
How do I import non-CSV ASCII data into SQLite 3?

I have a large amount of newline (0x0A)-terminated ASCII data that I want to import to SQLite 3. I can't use CSV format, because many of the text fields have embedded commas and quotes.  I can reformat the data any which way, but I'd rather not reformat as SQL insert statements (over 400 million rows).

I want the use the ".import" command, which supposedly supports an "ascii" format where a column separator of 0x1F and row separator of 0x1E is used.  Somehow, it doesn't work. I keep getting "Expected 120 columns but found 1".

All the Google results that I'm getting are about CSV import, which is why I'm asking here.

I'm including a simplified example of my problem below. As mentioned, the sample data can contain quotes (single and double), tabs and commas, so I can't use those as delimiters. I can use any other byte value for column and row delimiters.

Example.

Table

```<code>create table testtable ( item char(20), descr char(30), misc char(40) );
</code>```

Data

item
descr
misc

apple
a fruit
no "other" comments, for now

grape
another fruit
Yes, I like grapes

答:
Background

Where a CSV has (,,\n) for awk-termed field and record separators, or column and row separators, respectively, Sqlite's .import --ascii [file] [db] expects (\x37, \x36) which are ASCII Unit Separator (us) and Record Separator (rs) of the standard. See man ascii or other reference.

Demo

Obtain a plain example CSV using seq 9 | rs -C, 3 | sed 's/,$//' | tee seq.csv, note no trailing column delimiter.

<seq.csv tr ',' '\037' | tr '\n' '\036' | tee seq.ascii | less -RF translates the CSV row and column separators to ASCII unit- and record- separators respectively.

sqlite3 seq.db '.import --ascii seq.ascii tbl' imports.

sqlite3 seq.db '.dump tbl' shows the imported table.

Other hints

In sqlite, if the table does not exist before .import, the first row will become the header. Tables need column names.

In processing other large files, less -R, head -c [char #s], and vim may be your friend in munging these files and previewing changes.

I found quoting more finicky than I care to understand. bash or command interpret escape sequences in some contexts. tr correctly accepts $'\x1f' and '\037', but not "\x1f". Note tr accepts multichar arguments, so quoting is essential, tr , \x1f vs tr , '\x1f' makes a difference. gnu-sed adds a later stage of interpretation.

Other selected references

$ printf "\036\037 \x1e\x1f" | xxd
00000000: 1e1f 201e 1f                             .. ..
```

from man ascii,

in octal:

034 fs   035 gs   036 rs   037 us

and hexadecimal:

1c fs    1d gs    1e rs    1f us.

Sqlite also allows specifying other column, and optionally row, separators.
.separator COL ?ROW?     Change the column and row separators

Body:
How do I import non-CSV ASCII data into SQLite 3?

I have a large amount of newline (0x0A)-terminated ASCII data that I want to import to SQLite 3. I can't use CSV format, because many of the text fields have embedded commas and quotes.  I can reformat the data any which way, but I'd rather not reformat as SQL insert statements (over 400 million rows).

I want the use the ".import" command, which supposedly supports an "ascii" format where a column separator of 0x1F and row separator of 0x1E is used.  Somehow, it doesn't work. I keep getting "Expected 120 columns but found 1".

All the Google results that I'm getting are about CSV import, which is why I'm asking here.

I'm including a simplified example of my problem below. As mentioned, the sample data can contain quotes (single and double), tabs and commas, so I can't use those as delimiters. I can use any other byte value for column and row delimiters.

Example.

Table

create table testtable ( item char(20), descr char(30), misc char(40) );

Data

item
descr
misc

apple
a fruit
no "other" comments, for now

grape
another fruit
Yes, I like grapes

Body:
Background

Where a CSV has (,,\n) for awk-termed field and record separators, or column and row separators, respectively, Sqlite's .import --ascii [file] [db] expects (\x37, \x36) which are ASCII Unit Separator (us) and Record Separator (rs) of the standard. See man ascii or other reference.

Demo

Obtain a plain example CSV using seq 9 | rs -C, 3 | sed 's/,$//' | tee seq.csv, note no trailing column delimiter.

<seq.csv tr ',' '\037' | tr '\n' '\036' | tee seq.ascii | less -RF translates the CSV row and column separators to ASCII unit- and record- separators respectively.

sqlite3 seq.db '.import --ascii seq.ascii tbl' imports.

sqlite3 seq.db '.dump tbl' shows the imported table.

Other hints

In sqlite, if the table does not exist before .import, the first row will become the header. Tables need column names.

In processing other large files, less -R, head -c [char #s], and vim may be your friend in munging these files and previewing changes.

I found quoting more finicky than I care to understand. bash or command interpret escape sequences in some contexts. tr correctly accepts $'\x1f' and '\037', but not "\x1f". Note tr accepts multichar arguments, so quoting is essential, tr , \x1f vs tr , '\x1f' makes a difference. gnu-sed adds a later stage of interpretation.

Other selected references

$ printf "\036\037 \x1e\x1f" | xxd
00000000: 1e1f 201e 1f                             .. ..

from man ascii,

in octal:

034 fs   035 gs   036 rs   037 us

and hexadecimal:

1c fs    1d gs    1e rs    1f us.

Sqlite also allows specifying other column, and optionally row, separators.
.separator COL ?ROW?     Change the column and row separators


问:
Matching multiline text between specific strings with an optional end
I have problem writing a conditional regex. I need to find multiline text with an optional end. Usually it is the "normal end", sometimes I have this additional suffix.

Could some one please support me with this problem.

Here is my example:

```<code>Start of Text
 some thing in between
 some thing in between
 some thing in between
Normal end of text
Optional suffix

^(?:Start)[\d\w\s]*?(?(?=Optional.*)Optional.*|Normal.*)
</code>```

It only matches until "Normal end of text"
Even though, the "Optional" is present. What I understood from contional regex, it should find "Optional" and though match "Optional"

Thank you so much.

答:
You can use

^(Start)((?s:.*?))(Normal.*)(\s*Optional.*)?
```

See the regex demo. Details:

^ - start of string

(Start) - Group 1: Start

((?s:.*?)) - Group 2: any zero or more chars as few as possible

(Normal.*) - Group 3: Normal and then any zero or more chars other than line break chars as few as possible

(\s*Optional.*)? - an optional Group 4 matching zero or more whitespaces, Optional and then any zero or more chars other than line break chars as few as possible.

Body:
I have problem writing a conditional regex. I need to find multiline text with an optional end. Usually it is the "normal end", sometimes I have this additional suffix.

Could some one please support me with this problem.

Here is my example:

Start of Text
 some thing in between
 some thing in between
 some thing in between
Normal end of text
Optional suffix

^(?:Start)[\d\w\s]*?(?(?=Optional.*)Optional.*|Normal.*)

It only matches until "Normal end of text"
Even though, the "Optional" is present. What I understood from contional regex, it should find "Optional" and though match "Optional"

Thank you so much.

Body:
You can use

^(Start)((?s:.*?))(Normal.*)(\s*Optional.*)?

See the regex demo. Details:

^ - start of string

(Start) - Group 1: Start

((?s:.*?)) - Group 2: any zero or more chars as few as possible

(Normal.*) - Group 3: Normal and then any zero or more chars other than line break chars as few as possible

(\s*Optional.*)? - an optional Group 4 matching zero or more whitespaces, Optional and then any zero or more chars other than line break chars as few as possible.


问:
How to copy individual files into folder directory at relevant search depth reading from Google Sheet
I managed to find a way to create a folder directory from reading a Google Sheet linked below.

https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit#gid=0

Now, my predicament is to transfer individual files into those newly created folders and the relevant search Depth. I thought this would be possible; however, I am now thinking it isn't hence the limited code below.

This is because for each file (Column C), I would need to read the source parent folder ID (Column D) and then convert this to the destination folder equivalent recorded in Column F. I'm not sure how I can go about doing this? Moreover, should the Google Sheet be sorted into folders and files in a first instance (Column C), ideally the solution should still work when files and folders are out of order.

I know this is not the best solution; however, I am looking for a solution I can understand in order to advance my understanding.

```<code>function copyFiles() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Details');
  const range = ws.getDataRange();
  const values = range.getValues();
  values.forEach(function(row, index) {
    if (row[2] == 'File'){

    } else {

    }
    })
}
</code>```

Thank you in advance

答:
Assuming your data is well organized sequentially (based on files'id in column B)</p>
```<code>function copyFiles() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Sheet1');
  const range = ws.getDataRange();
  const values = range.getValues();
  var parentID = ''
  values.forEach(r => {
    if (r[2] == 'Folder') { parentID = r[5] }
    else if (r[2] == 'File') {
      r[5] = DriveApp.getFileById(r[1]).makeCopy(r[0], DriveApp.getFolderById(parentID)).getId()
    }
  })
  range.setValues(values)
}
</code>```

Body:
I managed to find a way to create a folder directory from reading a Google Sheet linked below.

https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit#gid=0

Now, my predicament is to transfer individual files into those newly created folders and the relevant search Depth. I thought this would be possible; however, I am now thinking it isn't hence the limited code below.

This is because for each file (Column C), I would need to read the source parent folder ID (Column D) and then convert this to the destination folder equivalent recorded in Column F. I'm not sure how I can go about doing this? Moreover, should the Google Sheet be sorted into folders and files in a first instance (Column C), ideally the solution should still work when files and folders are out of order.

I know this is not the best solution; however, I am looking for a solution I can understand in order to advance my understanding.

function copyFiles() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Details');
  const range = ws.getDataRange();
  const values = range.getValues();
  values.forEach(function(row, index) {
    if (row[2] == 'File'){

    } else {

    }
    })
}

Thank you in advance

Body:
Assuming your data is well organized sequentially (based on files'id in column B)

function copyFiles() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Sheet1');
  const range = ws.getDataRange();
  const values = range.getValues();
  var parentID = ''
  values.forEach(r => {
    if (r[2] == 'Folder') { parentID = r[5] }
    else if (r[2] == 'File') {
      r[5] = DriveApp.getFileById(r[1]).makeCopy(r[0], DriveApp.getFolderById(parentID)).getId()
    }
  })
  range.setValues(values)
}


问:
SpringBoot security on heroku-deployed project even without using its dependency
I am using java 1.8 for Gradle SpringBoot restAPI.

I haven't used spring-boot-starter-security and API works accordingly but after deploying the same code on heroku the API asks for the signup.

I tried disabling it via following way,

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@SpringBootApplication (exclude = { SecurityAutoConfiguration.class })
public class LawCaseApplication {

    public static void main(String[] args) {
        SpringApplication.run(LawCaseApplication.class, args);
    }

}
</code>```

But still after re-deploying the screen appeared.
Then I tried giving it my own user name and password by writing the following in the application.properties as I wasn't getting any randomly generated password in the logs too,

```<code>spring.security.user.name="user"
spring.security.user.password="user"
</code>```

And I am still getting this screen.

However, the dependencies I used are,

```<code>dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.projectlombok:lombok:1.18.20'
    runtimeOnly 'org.postgresql:postgresql'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation "org.jsoup:jsoup:1.13.1"
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
}
</code>```

I repeat that there is no security when run on local host but on the heroku deployed version.

答:
Actually, there is a most important step before you redeploy each time.
build the jar/war file so that it gets updated by the recent changes you made...

The steps you used are working on localhost proving them to be correct...
Try building the jar/war file then check if it works or not...

Body:
I am using java 1.8 for Gradle SpringBoot restAPI.

I haven't used spring-boot-starter-security and API works accordingly but after deploying the same code on heroku the API asks for the signup.

I tried disabling it via following way,

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@SpringBootApplication (exclude = { SecurityAutoConfiguration.class })
public class LawCaseApplication {

    public static void main(String[] args) {
        SpringApplication.run(LawCaseApplication.class, args);
    }

}

But still after re-deploying the screen appeared.
Then I tried giving it my own user name and password by writing the following in the application.properties as I wasn't getting any randomly generated password in the logs too,

spring.security.user.name="user"
spring.security.user.password="user"

And I am still getting this screen.

However, the dependencies I used are,

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.projectlombok:lombok:1.18.20'
    runtimeOnly 'org.postgresql:postgresql'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation "org.jsoup:jsoup:1.13.1"
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
}

I repeat that there is no security when run on local host but on the heroku deployed version.


问:
'data-clipboard-target' copying even words in the button
I'm using the below code to copy text to clipboard. The error is, it's copying even the text on the button which shouldn't happen. Can anyone explain why this is happening, and the way to prevent it?

https://www.tumblr.com/<button data-clipboard-target="#a">copy</button>

javascript:$('.overlay').slice(0, 100).click()<button data-clipboard-target="#b">copy</button>

```

答:
If you want to use Jquery to create this function you can find a demo below!

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p id="p1">Hello, I'm TEXT 1</p><button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>

<p id="p2">Hi, I'm the 2nd TEXT</p><br/>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button></code>```

Body:
If you want to use Jquery to create this function you can find a demo below!

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p id="p1">Hello, I'm TEXT 1</p><button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>

<p id="p2">Hi, I'm the 2nd TEXT</p><br/>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>


问:
What is the meaning of "universal: true" from a slate.js example?
What is the "universal: true" statement in the following code for?

```<code>isAziendaMarkActive(editor) {
    const [match] = Editor.nodes(editor, {
    match: n => n.isAzienda === true,
    universal: true,
})
</code>```

Thanks so much,
Elena

答:
Setting universal: true returns the matching nodes if and only if all of the selected nodes match your query.

So, in your case, isAziendaMarkActive() would return false for the following selection:

```<code><AziendaMark> A </AziendaMark>   B   <AziendaMark> C </AziendaMark>
</code>```

but true for this:

```<code><AziendaMark> A B C </AziendaMark>
</code>```

See: https://github.com/ianstormtaylor/slate/issues/3248#issue-533523682

Body:
What is the "universal: true" statement in the following code for?

isAziendaMarkActive(editor) {
    const [match] = Editor.nodes(editor, {
    match: n => n.isAzienda === true,
    universal: true,
})

Thanks so much,
Elena

Body:
Setting universal: true returns the matching nodes if and only if all of the selected nodes match your query.

So, in your case, isAziendaMarkActive() would return false for the following selection:

<AziendaMark> A </AziendaMark>   B   <AziendaMark> C </AziendaMark>

but true for this:

<AziendaMark> A B C </AziendaMark>

See: https://github.com/ianstormtaylor/slate/issues/3248#issue-533523682


问:
Snowflake Replace to joins with group by clause with single join
I have to take the LATEST CLICK as the latest date for that ID where the Event_Type is click. And do the similar thing for Event_Type = 'open'. I have the data like :

Id
Event_Type
SRC_CREATED

1
click
2021-04-10 01:50:08.490

1
click
2021-03-10 02:221:05.115

1
open
2021-06-10 01:12:08.288

1
click
2021-08-10 01:50:08.490

Outcome required :

Id
Event_Type
SRC_CREATED

1
click
2021-08-10 01:50:08.490

1
open
2021-06-10 01:12:08.288

I have used the query mentioned below, which is working fine, but I want to replace the 2 somehow joins used with a single join to fetch both these data. Can anyone think of a workaround query for that?

```<code>CREATE OR REPLACE table CUSTOMER AS
select CONCAT(NVL(ADD1,''),NVL(ADD2,'')) AS ADDRESS,
    CASE
WHEN NVL(GENDER,'')='F' THEN 'Female'
WHEN NVL(GENDER,'')='M' THEN 'Male'
WHEN NVL(GENDER,'')='U' Then 'Other'
ELSE ''
END AS GENDER,
***CLICK AS LAST_CLICK,
OPENS AS LAST_EMAIL_CLICK,***
B.PHONE AS PHONE,
A.SRC_CREATED AS SINCE,
from "HXP_SANDBOX"."BASE_RA_TEST"."IDENTITY" A
inner join "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" B
on A.DIGITALID = B.DIGITALID
***inner JOIN (SELECT DIGITALID,MAX(SRC_CREATED) CLICK
 from "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
  where EVENT_TYPE = 'click'
 group by DIGITALID) C
on A.DIGITALID = C.DIGITALID
inner JOIN (SELECT DIGITALID,MAX(SRC_CREATED) OPENS
 from "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
  where EVENT_TYPE = 'open'
 group by DIGITALID) D
on A.DIGITALID = D.DIGITALID;***
</code>```

答:
with this CTE to provide data

```<code>    SELECT column1 as id, column2 as event_type, to_timestamp(column3) as src_created
    FROM VALUES
    (1,'click','2021-04-10 01:50:08'),
    (1,'click','2021-03-10 02:21:05'),
    (1,'open','2021-06-10 01:12:08'),
    (1,'click','2021-08-10 01:50:08')
)
</code>```

the following SQL gives the answers you want:

```<code>SELECT
    id
    ,event_type
    ,max(src_created)
FROM fake_data
GROUP BY 1,2
ORDER BY 1,2;
</code>```

which gives:

ID
EVENT_TYPE
MAX(SRC_CREATED)

1
click
2021-08-10 01:50:08.000

1
open
2021-06-10 01:12:08.000

BUT what you asked for is not what your SQL does, and Dale's answer shows how to do that.

Which is the the same in my example data as:

```<code>SELECT
    id
    ,max(iff(event_type='click', src_created, null)) as last_click
    ,max(iff(event_type='open', src_created, null)) as last_click
FROM fake_data
GROUP BY 1
</code>```

you can use CASE or IFF, I prefer the IFF as it's shorter and explicit. If you are going to CASE path, you can drop the ELSE NULL as that is the default behavior.

Thus Dale's example can be:

```<code>  ,MAX(CASE WHEN event_type = 'click' THEN src_createdEND) AS click
  ,MAX(CASE WHEN event_type = 'open' THEN src_createdEND) AS opens
``

</code>```

Body:
I have to take the LATEST CLICK as the latest date for that ID where the Event_Type is click. And do the similar thing for Event_Type = 'open'. I have the data like :

Id
Event_Type
SRC_CREATED

1
click
2021-04-10 01:50:08.490

1
click
2021-03-10 02:221:05.115

1
open
2021-06-10 01:12:08.288

1
click
2021-08-10 01:50:08.490

Outcome required :

Id
Event_Type
SRC_CREATED

1
click
2021-08-10 01:50:08.490

1
open
2021-06-10 01:12:08.288

I have used the query mentioned below, which is working fine, but I want to replace the 2 somehow joins used with a single join to fetch both these data. Can anyone think of a workaround query for that?

CREATE OR REPLACE table CUSTOMER AS
select CONCAT(NVL(ADD1,''),NVL(ADD2,'')) AS ADDRESS,
    CASE
WHEN NVL(GENDER,'')='F' THEN 'Female'
WHEN NVL(GENDER,'')='M' THEN 'Male'
WHEN NVL(GENDER,'')='U' Then 'Other'
ELSE ''
END AS GENDER,
***CLICK AS LAST_CLICK,
OPENS AS LAST_EMAIL_CLICK,***
B.PHONE AS PHONE,
A.SRC_CREATED AS SINCE,
from "HXP_SANDBOX"."BASE_RA_TEST"."IDENTITY" A
inner join "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" B
on A.DIGITALID = B.DIGITALID
***inner JOIN (SELECT DIGITALID,MAX(SRC_CREATED) CLICK
 from "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
  where EVENT_TYPE = 'click'
 group by DIGITALID) C
on A.DIGITALID = C.DIGITALID
inner JOIN (SELECT DIGITALID,MAX(SRC_CREATED) OPENS
 from "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
  where EVENT_TYPE = 'open'
 group by DIGITALID) D
on A.DIGITALID = D.DIGITALID;***

Body:
with this CTE to provide data

    SELECT column1 as id, column2 as event_type, to_timestamp(column3) as src_created
    FROM VALUES
    (1,'click','2021-04-10 01:50:08'),
    (1,'click','2021-03-10 02:21:05'),
    (1,'open','2021-06-10 01:12:08'),
    (1,'click','2021-08-10 01:50:08')
)

the following SQL gives the answers you want:

SELECT
    id
    ,event_type
    ,max(src_created)
FROM fake_data
GROUP BY 1,2
ORDER BY 1,2;

which gives:

ID
EVENT_TYPE
MAX(SRC_CREATED)

1
click
2021-08-10 01:50:08.000

1
open
2021-06-10 01:12:08.000

BUT what you asked for is not what your SQL does, and Dale's answer shows how to do that.

Which is the the same in my example data as:

SELECT
    id
    ,max(iff(event_type='click', src_created, null)) as last_click
    ,max(iff(event_type='open', src_created, null)) as last_click
FROM fake_data
GROUP BY 1

you can use CASE or IFF, I prefer the IFF as it's shorter and explicit. If you are going to CASE path, you can drop the ELSE NULL as that is the default behavior.

Thus Dale's example can be:

  ,MAX(CASE WHEN event_type = 'click' THEN src_createdEND) AS click
  ,MAX(CASE WHEN event_type = 'open' THEN src_createdEND) AS opens
``


问:
Cuda 4.0 with Visual Studio 2010 cl compiler error
As I did not get any help in the Nvidia forums (see my post at the bottom of the thread), and it seems I am not the only one struggeling with similar problems, I will give it a try here.

I tried to compile the Cuda SDK 4.0 examples as well as following the very nice tutorial by Ade Miller. But compiling the ".cu" file won't work.

This is the (exemplary) command the compiler invokes:

```<code>"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\bin\nvcc.exe"
-gencode=arch=compute_10,code=\"sm_10,compute_10\" --use-local-env
--cl-version 2010 -ccbin "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC bin\x86_amd64"
-I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\include"  -G0
--keep-dir "x64\Debug" -maxrregcount=0  --machine 64 --compile  -D_NEXUS_DEBUG
-g    -Xcompiler "/EHsc /nologo /Od /Zi  /MDd " -o "x64\Debug\Hello.cu.obj"
"D:\Code\CUDA\Test_Cuda_4_0\Test_Cuda_4_0\Hello.cu"
</code>```

And this is the strange error message I always get.

```<code>nvcc fatal   : Compiler 'cl' in PATH different than the one specified with -ccbin
</code>```

EDIT: To be a bit more precise: Visual Studio just tells me the command did not succeed ("exit code -1") -> to see this error message I have to invoke the command by myself in the command line.

1) Why should nvcc care about the path in the environment variable differing from the one specified with the command line option? If it would care, wouldn't this make the command line option completely useless?

2) How to fix ;) ?

I use Win7 64Bit, VS2010 Prof SP1, and the following nvidia versions:
cudatoolkit_4.0.17_win_64
devdriver_4.0_winvista-win7_64_270.81_general
gpucomputingsdk_4.0.19_win_64

Many thanks for your help!

答: try using the conventional method to start writing a CUDA program, as given in Getting Started guide(Copy the sample). To solve the above problem you have to add it as an environment variable. But since the SDK samples are already linked, they don't give problems. </p>

Body:
As I did not get any help in the Nvidia forums (see my post at the bottom of the thread), and it seems I am not the only one struggeling with similar problems, I will give it a try here.

I tried to compile the Cuda SDK 4.0 examples as well as following the very nice tutorial by Ade Miller. But compiling the ".cu" file won't work.

This is the (exemplary) command the compiler invokes:

"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\bin\nvcc.exe"
-gencode=arch=compute_10,code=\"sm_10,compute_10\" --use-local-env
--cl-version 2010 -ccbin "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC bin\x86_amd64"
-I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\include"  -G0
--keep-dir "x64\Debug" -maxrregcount=0  --machine 64 --compile  -D_NEXUS_DEBUG
-g    -Xcompiler "/EHsc /nologo /Od /Zi  /MDd " -o "x64\Debug\Hello.cu.obj"
"D:\Code\CUDA\Test_Cuda_4_0\Test_Cuda_4_0\Hello.cu"

And this is the strange error message I always get.

nvcc fatal   : Compiler 'cl' in PATH different than the one specified with -ccbin

EDIT: To be a bit more precise: Visual Studio just tells me the command did not succeed ("exit code -1") -> to see this error message I have to invoke the command by myself in the command line.

1) Why should nvcc care about the path in the environment variable differing from the one specified with the command line option? If it would care, wouldn't this make the command line option completely useless?

2) How to fix ;) ?

I use Win7 64Bit, VS2010 Prof SP1, and the following nvidia versions:
cudatoolkit_4.0.17_win_64
devdriver_4.0_winvista-win7_64_270.81_general
gpucomputingsdk_4.0.19_win_64

Many thanks for your help!


问:
Get the name or label from django IntegerChoices providing a valid value
I have django 3.2 and an IntegerChoices class

```<code> class Type(models.IntegerChoices):
        GENERAL = 2, _("general address")
        DELIVERY = 4, _("delivery address")
        BILLING = 6, _("billing address")
</code>```

I can get the Value name and label easily by doing Type.GENERAL , Type.GENERAL.name and Type.GENERAL.label.

But how can I get these values if I only have the value, e.g. I want to get the Name DELIVERY from the value 4.

Type[4].name ist not working as the list values does not correspond to the int values of the enum.

Thanks
Matt

答:
You can also do something like this if you can be sure that it is a valid value:</p>
```<code>print(Type(2).name)
print(Type(2).label)
</code>```

Body:
I have django 3.2 and an IntegerChoices class

 class Type(models.IntegerChoices):
        GENERAL = 2, _("general address")
        DELIVERY = 4, _("delivery address")
        BILLING = 6, _("billing address")

I can get the Value name and label easily by doing Type.GENERAL , Type.GENERAL.name and Type.GENERAL.label.

But how can I get these values if I only have the value, e.g. I want to get the Name DELIVERY from the value 4.

Type[4].name ist not working as the list values does not correspond to the int values of the enum.

Thanks
Matt

Body:
You can also do something like this if you can be sure that it is a valid value:

print(Type(2).name)
print(Type(2).label)


问:
Add Metadata, headers (Expires, CacheControl) to a file uploaded to Amazon S3 using the Laravel 5.0 Storage facade
I am trying to find out how to add in Metadata or headers (Expires, CacheControl etc.) to a file uploaded using the Laravel 5.0 Storage facade. I have use the page here as reference.

http://laravel.com/docs/5.0/filesystem

The following code works correctly:

```<code>Storage::disk('s3')->put('/test.txt', 'test');
</code>```

After digging I also found that there is a 'visibility' parameter which sets the ACL to 'public-read' so the following also works correctly.

```<code>Storage::disk('s3')->put('/test.txt', 'test', 'public');
</code>```

But I would like to be able to set some other values to the header of the file. I have tried the following:

```<code>Storage::disk('s3')->put('/index4.txt', 'test', 'public', array('Expires'=>'Expires, Fri, 30 Oct 1998 14:19:41 GMT'));
</code>```

Which doesn't work, I have also tried:

```<code>Storage::disk('s3')->put('/index4.txt', 'test', array('ACL'=>'public-read'));
</code>```

But that creates an error where the 'visibility' parameter can not be converted from a string to an array. I have checked the source of AwsS3Adapter and it seems there is code for options but I can not seem to see how to pass them correctly. I think it takes the following:

```<code>protected static $metaOptions = [
    'CacheControl',
    'Expires',
    'StorageClass',
    'ServerSideEncryption',
    'Metadata',
    'ACL',
    'ContentType',
    'ContentDisposition',
    'ContentLanguage',
    'ContentEncoding',
];
</code>```

Any help on how to accomplish this would be appreciated.

答:
For Laravel 9 users this has became more easy. You do not need to call ->getDriver() anymore. You can directly pass options to the put command.

```<code>Storage::disk('s3')->put('/index.txt', 'file content', [
    // S3 Object ACL
    'visibility' => 'public', // or 'private',

    // HTTP Headers
    'CacheControl' => 'public,max-age=315360000',
    'ContentDisposition' => 'attachment; filename="index.txt"',
    'Expires' => 'Thu, 12 Feb 2032 08:24:43 GMT',

    // Metadata or other S3 options
    'MetadataDirective' => 'REPLACE'
    'Metadata' => [
        'Custom-Key' => 'test',
    ],
])
</code>```

In case you need other headers or options, please checkout the flysystem source code for all available headers and options.

https://github.com/thephpleague/flysystem-aws-s3-v3/blob/master/src/AwsS3Adapter.php#L38

```<code>public const AVAILABLE_OPTIONS = [
    'ACL',
    'CacheControl',
    'ContentDisposition',
    'ContentEncoding',
    'ContentLength',
    'ContentType',
    'Expires',
    'GrantFullControl',
    'GrantRead',
    'GrantReadACP',
    'GrantWriteACP',
    'Metadata',
    'MetadataDirective',
    'RequestPayer',
    'SSECustomerAlgorithm',
    'SSECustomerKey',
    'SSECustomerKeyMD5',
    'SSEKMSKeyId',
    'ServerSideEncryption',
    'StorageClass',
    'Tagging',
    'WebsiteRedirectLocation',
];
</code>```

Body:
I am trying to find out how to add in Metadata or headers (Expires, CacheControl etc.) to a file uploaded using the Laravel 5.0 Storage facade. I have use the page here as reference.

http://laravel.com/docs/5.0/filesystem

The following code works correctly:

Storage::disk('s3')->put('/test.txt', 'test');

After digging I also found that there is a 'visibility' parameter which sets the ACL to 'public-read' so the following also works correctly.

Storage::disk('s3')->put('/test.txt', 'test', 'public');

But I would like to be able to set some other values to the header of the file. I have tried the following:

Storage::disk('s3')->put('/index4.txt', 'test', 'public', array('Expires'=>'Expires, Fri, 30 Oct 1998 14:19:41 GMT'));

Which doesn't work, I have also tried:

Storage::disk('s3')->put('/index4.txt', 'test', array('ACL'=>'public-read'));

But that creates an error where the 'visibility' parameter can not be converted from a string to an array. I have checked the source of AwsS3Adapter and it seems there is code for options but I can not seem to see how to pass them correctly. I think it takes the following:

protected static $metaOptions = [
    'CacheControl',
    'Expires',
    'StorageClass',
    'ServerSideEncryption',
    'Metadata',
    'ACL',
    'ContentType',
    'ContentDisposition',
    'ContentLanguage',
    'ContentEncoding',
];

Any help on how to accomplish this would be appreciated.

Body:
For Laravel 9 users this has became more easy. You do not need to call ->getDriver() anymore. You can directly pass options to the put command.

Storage::disk('s3')->put('/index.txt', 'file content', [
    // S3 Object ACL
    'visibility' => 'public', // or 'private',

    // HTTP Headers
    'CacheControl' => 'public,max-age=315360000',
    'ContentDisposition' => 'attachment; filename="index.txt"',
    'Expires' => 'Thu, 12 Feb 2032 08:24:43 GMT',

    // Metadata or other S3 options
    'MetadataDirective' => 'REPLACE'
    'Metadata' => [
        'Custom-Key' => 'test',
    ],
])

In case you need other headers or options, please checkout the flysystem source code for all available headers and options.

https://github.com/thephpleague/flysystem-aws-s3-v3/blob/master/src/AwsS3Adapter.php#L38

public const AVAILABLE_OPTIONS = [
    'ACL',
    'CacheControl',
    'ContentDisposition',
    'ContentEncoding',
    'ContentLength',
    'ContentType',
    'Expires',
    'GrantFullControl',
    'GrantRead',
    'GrantReadACP',
    'GrantWriteACP',
    'Metadata',
    'MetadataDirective',
    'RequestPayer',
    'SSECustomerAlgorithm',
    'SSECustomerKey',
    'SSECustomerKeyMD5',
    'SSEKMSKeyId',
    'ServerSideEncryption',
    'StorageClass',
    'Tagging',
    'WebsiteRedirectLocation',
];


问:
How can I create java array[][] using undefined number of arrays[]
Just out of curiosity, based on that code is there a way to that instead of

```<code>int [][]d = { obj[0].ar , obj[1].ar , obj[2].ar };
</code>```

can be written  under a for like this

```<code>for(int i=0;i<obj.ar.length;i++)
</code>```

or to just combine all arrays of obj[].ar using obj.length in one 2 dimenstional array?

```<code>public class Main
{
    public static void main(String[] args)
    {
        int nb = 3;
        arr[] obj = new arr[nb];

        for(int i=0;i<obj.length;i++)
        {
            obj[i] = new arr(i+2);
        }

        int [][]d = { obj[0].ar , obj[1].ar , obj[2].ar };

        for(int i=0;i<d.length;i++)
        {
            for(int j=0;j<d[i].length;j++)
                System.out.print(d[i][j]+"\t");
            System.out.println();
        }
    }
}
class arr
{
    int []ar;
    arr(int nb)
    {
        ar = new int[nb];
        for(int i=0;i<ar.length;i++)
            ar[i]=i;
    }
}
</code>```

答:
Java arrays must always have a determined size upon creation.

Notice you are always setting nb in the calls to new arrays, or by using the {} instantiator which will count the number of objects statically.

What you are asking for is probably what ArrayList is meant to achieve. It will grow as you go, while having an array implementation behind the scenes. If the contents cannot fit in the array, a new - larger - array is created to fit them all. You won't notice this while using it though.

```<code>ArrayList<ArrayList<Integer>> obj = new ArrayList<>();

obj.add(new ArrayList<>());
obj.add(new ArrayList<>());
obj.add(new ArrayList<>());
// There are now three empty lists, in the main list.
</code>```

Since java 9, you can use some extra helper methods:

```<code>List<List<Integer>> obj = List.of(
    List.of(1,2,3),
    List.of(2,3,4)
);
</code>```

If you want, you can implement you own ArrayList class, it's not that hard!

Body:
Just out of curiosity, based on that code is there a way to that instead of

int [][]d = { obj[0].ar , obj[1].ar , obj[2].ar };

can be written  under a for like this

for(int i=0;i<obj.ar.length;i++)

or to just combine all arrays of obj[].ar using obj.length in one 2 dimenstional array?

public class Main
{
    public static void main(String[] args)
    {
        int nb = 3;
        arr[] obj = new arr[nb];

        for(int i=0;i<obj.length;i++)
        {
            obj[i] = new arr(i+2);
        }

        int [][]d = { obj[0].ar , obj[1].ar , obj[2].ar };

        for(int i=0;i<d.length;i++)
        {
            for(int j=0;j<d[i].length;j++)
                System.out.print(d[i][j]+"\t");
            System.out.println();
        }
    }
}
class arr
{
    int []ar;
    arr(int nb)
    {
        ar = new int[nb];
        for(int i=0;i<ar.length;i++)
            ar[i]=i;
    }
}

Body:
Java arrays must always have a determined size upon creation.

Notice you are always setting nb in the calls to new arrays, or by using the {} instantiator which will count the number of objects statically.

What you are asking for is probably what ArrayList is meant to achieve. It will grow as you go, while having an array implementation behind the scenes. If the contents cannot fit in the array, a new - larger - array is created to fit them all. You won't notice this while using it though.

ArrayList<ArrayList<Integer>> obj = new ArrayList<>();

obj.add(new ArrayList<>());
obj.add(new ArrayList<>());
obj.add(new ArrayList<>());
// There are now three empty lists, in the main list.

Since java 9, you can use some extra helper methods:

List<List<Integer>> obj = List.of(
    List.of(1,2,3),
    List.of(2,3,4)
);

If you want, you can implement you own ArrayList class, it's not that hard!


问:
error while using make to compile Glibc-2.11.1 for Linux From Scratch
I am building LFS and I am in the part where we need to install Glibc-2.11.1

http://www.linuxfromscratch.org/lfs/view/6.6/chapter05/glibc.html

I have successfully configured it but I cant run the make command. Whenever I run the command it runs for a while then stops.

I think the following lines show that something I did is incorrect:

mawk: scripts/gen-sorted.awk: line 19: regular expression compile failed (bad class -- [], [^] or [)
/[^
mawk: scripts/gen-sorted.awk: line 19: syntax error at or near ]
mawk: scripts/gen-sorted.awk: line 19: runaway regular expression /, "", subd ...
make[1]: Leaving directory `/mnt/lfs/sources/glibc-2.11.1'
make[1]: Entering directory `/mnt/lfs/sources/glibc-2.11.1'
mawk -f scripts/gen-sorted.awk \
           -v subdirs='csu assert ctype locale intl catgets math setjmp signal stdlib stdio-common libio malloc string wcsmbs time dirent grp pwd posix io termios resource misc socket sysvipc gmon gnulib iconv iconvdata wctype manual shadow gshadow po argp crypt nss localedata timezone rt conform debug libidn dlfcn elf' \
           -v srcpfx='' \
           nptl/sysdeps/pthread/Subdirs sysdeps/unix/inet/Subdirs sysdeps/unix/Subdirs assert/Depend intl/Depend catgets/Depend stdlib/Depend stdio-common/Depend libio/Depend malloc/Depend string/Depend wcsmbs/Depend time/Depend posix/Depend iconvdata/Depend nss/Depend localedata/Depend rt/Depend debug/Depend > /mnt/lfs/sources/glibc-build/sysd-sorted-tmp
mawk: scripts/gen-sorted.awk: line 19: regular expression compile failed (bad class -- [], [^] or [)
/[^
mawk: scripts/gen-sorted.awk: line 19: syntax error at or near ]
mawk: scripts/gen-sorted.awk: line 19: runaway regular expression /, "", subd ...
rm -f /mnt/lfs/sources/glibc-build/stamp.o; > /mnt/lfs/sources/glibc-build/stamp.o
rm -f /mnt/lfs/sources/glibc-build/stamp.os; > /mnt/lfs/sources/glibc-build/stamp.os
rm -f /mnt/lfs/sources/glibc-build/stamp.oS; > /mnt/lfs/sources/glibc-build/stamp.oS
cd /mnt/lfs/sources/glibc-build && /mnt/lfs/tools/bin/../lib/gcc/i686-lfs-linux-gnu/4.4.3/../../../../i686-lfs-linux-gnu/bin/ar cruv libc.a `cat stamp.o`
: /mnt/lfs/sources/glibc-build/libc.a
cd /mnt/lfs/sources/glibc-build && /mnt/lfs/tools/bin/../lib/gcc/i686-lfs-linux-gnu/4.4.3/../../../../i686-lfs-linux-gnu/bin/ar cruv libc_pic.a `cat stamp.os`
: /mnt/lfs/sources/glibc-build/libc_pic.a
cd /mnt/lfs/sources/glibc-build && /mnt/lfs/tools/bin/../lib/gcc/i686-lfs-linux-gnu/4.4.3/../../../../i686-lfs-linux-gnu/bin/ar cruv libc_nonshared.a `cat stamp.oS`
: /mnt/lfs/sources/glibc-build/libc_nonshared.a
make[1]: *** No rule to make target `/mnt/lfs/sources/glibc-build/Versions.all', needed by `/mnt/lfs/sources/glibc-build/abi-versions.h'.  Stop.
make[1]: Leaving directory `/mnt/lfs/sources/glibc-2.11.1'
make: *** [all] Error 2

real    0m11.390s
user    0m2.044s
sys 0m1.724s
lfs@rohanchrome:/mnt/lfs/sources/glibc-build$ make
make -r PARALLELMFLAGS="" CVSOPTS="" -C /mnt/lfs/sources/glibc-2.11.1 objdir=`pwd` all
make[1]: Entering directory `/mnt/lfs/sources/glibc-2.11.1'
mawk -f scripts/gen-sorted.awk \
           -v subdirs='csu assert ctype locale intl catgets math setjmp signal stdlib stdio-common libio malloc string wcsmbs time dirent grp pwd posix io termios resource misc socket sysvipc gmon gnulib iconv iconvdata wctype manual shadow gshadow po argp crypt nss localedata timezone rt conform debug libidn dlfcn elf' \
           -v srcpfx='' \
           nptl/sysdeps/pthread/Subdirs sysdeps/unix/inet/Subdirs sysdeps/unix/Subdirs assert/Depend intl/Depend catgets/Depend stdlib/Depend stdio-common/Depend libio/Depend malloc/Depend string/Depend wcsmbs/Depend time/Depend posix/Depend iconvdata/Depend nss/Depend localedata/Depend rt/Depend debug/Depend > /mnt/lfs/sources/glibc-build/sysd-sorted-tmp
mawk: scripts/gen-sorted.awk: line 19: regular expression compile failed (bad class -- [], [^] or [)
/[^
mawk: scripts/gen-sorted.awk: line 19: syntax error at or near ]
mawk: scripts/gen-sorted.awk: line 19: runaway regular expression /, "", subd ...
make[1]: *** No rule to make target `/mnt/lfs/sources/glibc-build/Versions.all', needed by `/mnt/lfs/sources/glibc-build/abi-versions.h'.  Stop.
make[1]: Leaving directory `/mnt/lfs/sources/glibc-2.11.1'
make: *** [all] Error 2
```

I dont understand where the things went wrong. What I should to correct them?

答:
You need to install gawk.

```<code>sudo apt-get install gawk
</code>```

The regex on Line 19 was

```<code>/\/[^/]+$/
</code>```

It is a known issue that mawk does not understand unescaped '/' in character classes at least up to version 1.3.3-15 (the one supplied on Ubuntu 11.04 (Natty)). mawk will think the / inside the bracket terminates the regex, and interpret as \/[^, which is surely a syntax error due to unmatched ].

The fix for glibc is trivial: just add a \ before the /. But this may also be a dedicate "check" to ensure gawk is used. At least this is still not changed on glibc-2.14…

(Source of solution: http://www.linuxquestions.org/questions/linux-from-scratch-13/urgent-help-on-glibc-make-error-with-clfs-590753/)

Body:
I am building LFS and I am in the part where we need to install Glibc-2.11.1

http://www.linuxfromscratch.org/lfs/view/6.6/chapter05/glibc.html

I have successfully configured it but I cant run the make command. Whenever I run the command it runs for a while then stops.

I think the following lines show that something I did is incorrect:

mawk: scripts/gen-sorted.awk: line 19: regular expression compile failed (bad class -- [], [^] or [)
/[^
mawk: scripts/gen-sorted.awk: line 19: syntax error at or near ]
mawk: scripts/gen-sorted.awk: line 19: runaway regular expression /, "", subd ...
make[1]: Leaving directory `/mnt/lfs/sources/glibc-2.11.1'
make[1]: Entering directory `/mnt/lfs/sources/glibc-2.11.1'
mawk -f scripts/gen-sorted.awk \
           -v subdirs='csu assert ctype locale intl catgets math setjmp signal stdlib stdio-common libio malloc string wcsmbs time dirent grp pwd posix io termios resource misc socket sysvipc gmon gnulib iconv iconvdata wctype manual shadow gshadow po argp crypt nss localedata timezone rt conform debug libidn dlfcn elf' \
           -v srcpfx='' \
           nptl/sysdeps/pthread/Subdirs sysdeps/unix/inet/Subdirs sysdeps/unix/Subdirs assert/Depend intl/Depend catgets/Depend stdlib/Depend stdio-common/Depend libio/Depend malloc/Depend string/Depend wcsmbs/Depend time/Depend posix/Depend iconvdata/Depend nss/Depend localedata/Depend rt/Depend debug/Depend > /mnt/lfs/sources/glibc-build/sysd-sorted-tmp
mawk: scripts/gen-sorted.awk: line 19: regular expression compile failed (bad class -- [], [^] or [)
/[^
mawk: scripts/gen-sorted.awk: line 19: syntax error at or near ]
mawk: scripts/gen-sorted.awk: line 19: runaway regular expression /, "", subd ...
rm -f /mnt/lfs/sources/glibc-build/stamp.o; > /mnt/lfs/sources/glibc-build/stamp.o
rm -f /mnt/lfs/sources/glibc-build/stamp.os; > /mnt/lfs/sources/glibc-build/stamp.os
rm -f /mnt/lfs/sources/glibc-build/stamp.oS; > /mnt/lfs/sources/glibc-build/stamp.oS
cd /mnt/lfs/sources/glibc-build && /mnt/lfs/tools/bin/../lib/gcc/i686-lfs-linux-gnu/4.4.3/../../../../i686-lfs-linux-gnu/bin/ar cruv libc.a `cat stamp.o`
: /mnt/lfs/sources/glibc-build/libc.a
cd /mnt/lfs/sources/glibc-build && /mnt/lfs/tools/bin/../lib/gcc/i686-lfs-linux-gnu/4.4.3/../../../../i686-lfs-linux-gnu/bin/ar cruv libc_pic.a `cat stamp.os`
: /mnt/lfs/sources/glibc-build/libc_pic.a
cd /mnt/lfs/sources/glibc-build && /mnt/lfs/tools/bin/../lib/gcc/i686-lfs-linux-gnu/4.4.3/../../../../i686-lfs-linux-gnu/bin/ar cruv libc_nonshared.a `cat stamp.oS`
: /mnt/lfs/sources/glibc-build/libc_nonshared.a
make[1]: *** No rule to make target `/mnt/lfs/sources/glibc-build/Versions.all', needed by `/mnt/lfs/sources/glibc-build/abi-versions.h'.  Stop.
make[1]: Leaving directory `/mnt/lfs/sources/glibc-2.11.1'
make: *** [all] Error 2

real    0m11.390s
user    0m2.044s
sys 0m1.724s
lfs@rohanchrome:/mnt/lfs/sources/glibc-build$ make
make -r PARALLELMFLAGS="" CVSOPTS="" -C /mnt/lfs/sources/glibc-2.11.1 objdir=`pwd` all
make[1]: Entering directory `/mnt/lfs/sources/glibc-2.11.1'
mawk -f scripts/gen-sorted.awk \
           -v subdirs='csu assert ctype locale intl catgets math setjmp signal stdlib stdio-common libio malloc string wcsmbs time dirent grp pwd posix io termios resource misc socket sysvipc gmon gnulib iconv iconvdata wctype manual shadow gshadow po argp crypt nss localedata timezone rt conform debug libidn dlfcn elf' \
           -v srcpfx='' \
           nptl/sysdeps/pthread/Subdirs sysdeps/unix/inet/Subdirs sysdeps/unix/Subdirs assert/Depend intl/Depend catgets/Depend stdlib/Depend stdio-common/Depend libio/Depend malloc/Depend string/Depend wcsmbs/Depend time/Depend posix/Depend iconvdata/Depend nss/Depend localedata/Depend rt/Depend debug/Depend > /mnt/lfs/sources/glibc-build/sysd-sorted-tmp
mawk: scripts/gen-sorted.awk: line 19: regular expression compile failed (bad class -- [], [^] or [)
/[^
mawk: scripts/gen-sorted.awk: line 19: syntax error at or near ]
mawk: scripts/gen-sorted.awk: line 19: runaway regular expression /, "", subd ...
make[1]: *** No rule to make target `/mnt/lfs/sources/glibc-build/Versions.all', needed by `/mnt/lfs/sources/glibc-build/abi-versions.h'.  Stop.
make[1]: Leaving directory `/mnt/lfs/sources/glibc-2.11.1'
make: *** [all] Error 2

I dont understand where the things went wrong. What I should to correct them?

Body:
You need to install gawk.

sudo apt-get install gawk

The regex on Line 19 was

/\/[^/]+$/

It is a known issue that mawk does not understand unescaped '/' in character classes at least up to version 1.3.3-15 (the one supplied on Ubuntu 11.04 (Natty)). mawk will think the / inside the bracket terminates the regex, and interpret as \/[^, which is surely a syntax error due to unmatched ].

The fix for glibc is trivial: just add a \ before the /. But this may also be a dedicate "check" to ensure gawk is used. At least this is still not changed on glibc-2.14…

(Source of solution: http://www.linuxquestions.org/questions/linux-from-scratch-13/urgent-help-on-glibc-make-error-with-clfs-590753/)


问:
How undo setState if Fecth was failed?
Im trying change state and if internet connection lost. Component renders new state, but it doesn't changed on server. How i can undo last setState to prevent state change?

```<code>const Position = ({ value }) => {
  const [position, setPosition] = useState(value)

  useEffect(() => {
    async function fetchData() {
      try {
        const { position } = await changePosition(position)
        setPosition(position)
      } catch (e) {
        console.log(e)
      }
    }

    fetchData()
  }, [position])

  return (
    <Select
      value={position}
      onChange={(value) => setPosition(value)}
    >
     <Option value="left">Left</Option>
      <Option value="top">Top</Option>
      <Option value="right">Right</Option>
      <Option value="bottom">Bottom</Option>
    </Select>
  )
}
</code>```

答:
You can use useRef hook to save previous position, for example:

const Position = ({ value }) => {
  const [position, setPosition] = useState(value)
  // useRef here
  const prevPosition = useRef(position)

  useEffect(() => {
    async function fetchData() {
      try {
        const { position } = await changePosition(position)
        // if success save new position and do something you want.
        prevPostion.current = position

      } catch (e) {
        console.log(e)
        // if fail setState to previous position.
        setPosition(prevPosition)
      }
    }

    fetchData()
  }, [position])

  return (
    <Select
      value={position}
      onChange={(value) => setPosition(value)}
    >
     <Option value="left">Left</Option>
      <Option value="top">Top</Option>
      <Option value="right">Right</Option>
      <Option value="bottom">Bottom</Option>
    </Select>
  )
}
```

Hope to help you !

Title: How undo setState if Fecth was failed?

Body:
Im trying change state and if internet connection lost. Component renders new state, but it doesn't changed on server. How i can undo last setState to prevent state change?

const Position = ({ value }) => {
  const [position, setPosition] = useState(value)

  useEffect(() => {
    async function fetchData() {
      try {
        const { position } = await changePosition(position)
        setPosition(position)
      } catch (e) {
        console.log(e)
      }
    }

    fetchData()
  }, [position])

  return (
    <Select
      value={position}
      onChange={(value) => setPosition(value)}
    >
     <Option value="left">Left</Option>
      <Option value="top">Top</Option>
      <Option value="right">Right</Option>
      <Option value="bottom">Bottom</Option>
    </Select>
  )
}

Body:
You can use useRef hook to save previous position, for example:

const Position = ({ value }) => {
  const [position, setPosition] = useState(value)
  // useRef here
  const prevPosition = useRef(position)

  useEffect(() => {
    async function fetchData() {
      try {
        const { position } = await changePosition(position)
        // if success save new position and do something you want.
        prevPostion.current = position

      } catch (e) {
        console.log(e)
        // if fail setState to previous position.
        setPosition(prevPosition)
      }
    }

    fetchData()
  }, [position])

  return (
    <Select
      value={position}
      onChange={(value) => setPosition(value)}
    >
     <Option value="left">Left</Option>
      <Option value="top">Top</Option>
      <Option value="right">Right</Option>
      <Option value="bottom">Bottom</Option>
    </Select>
  )
}

Hope to help you !


问:
Forex send orders using Python without Metatrader5
Need solutions to Forex order_send in Python.
using Metatrader5 its so easy:

```<code>import MetaTrader5 as mt5

            request = {
                "action": mt5.TRADE_ACTION_DEAL,
                "symbol": symbol,
                "volume": lot,
                "type": trade_type,
                "price": price,
                "tp": tp,
                "sl": sl,
            }

            result = mt5.order_send(request)
</code>```

But for some reason I only have one Linux server now. My attempts to install MetaTrader 5 were completely unsuccessful (even after trying the Windows emulator).

Is there a way to Send my forex orders without using Metatrader5?

Thank you all

答: you can use mt5linux package, it's a package that work in the same manner on linux.</p>

Body:
Need solutions to Forex order_send in Python.
using Metatrader5 its so easy:

import MetaTrader5 as mt5

            request = {
                "action": mt5.TRADE_ACTION_DEAL,
                "symbol": symbol,
                "volume": lot,
                "type": trade_type,
                "price": price,
                "tp": tp,
                "sl": sl,
            }

            result = mt5.order_send(request)

But for some reason I only have one Linux server now. My attempts to install MetaTrader 5 were completely unsuccessful (even after trying the Windows emulator).

Is there a way to Send my forex orders without using Metatrader5?

Thank you all


问:
Exporting In-Memory HSQL Database Content as SQL During Maven Build
During a Maven build's integration test phase I am populating an in-memory HSQL database based on the performed tests. Afterwards, I would like to capture this state by exporting the database content as SQL statements (for later import).

Is there some Maven plugin or command line tool suitable for this task? For MySQL we are using mysqldump, so I am basically looking for an equivalent for HSQL.

答:
With HSQLDB use:

```<code>SCRIPT <filepath>
</code>```

Example:

```<code>SCRIPT '/opt/dump/mydb.script'
</code>```

Body:
With HSQLDB use:

SCRIPT <filepath>

Example:

SCRIPT '/opt/dump/mydb.script'


问:
gcloud auth login throwing error: gcloud crashed (ConnectionError): HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded

gcloud builds submit failed for me yesterday.

Then I tried gcloud config set project, that also failed.

So I thought login might have expired so tried gcloud auth login.

In all cases, it always throws following error:

```<code>ERROR: gcloud crashed (ConnectionError): HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000198B0B26970>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

If you would like to report this issue, please run the following command:
  gcloud feedback

To check gcloud for common problems, please run the following command:
  gcloud info --run-diagnostics
</code>```

On running diagnostics as suggested, everything seems fine.

```<code>>  gcloud info --run-diagnostics
Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

Property diagnostic detects issues that may be caused by properties.
Checking hidden properties...done.
Hidden Property Check passed.
Property diagnostic passed (1/1 checks passed).
</code>```

I have also tried with my other google account, threw same error. It was working fine 1 day before. Have tried all Stackoverflow solutions, nothing seems to work.

答:
connect to a VPN
or
mac users enable Private Relay(Beta) in icloud setting</p>

Body:
gcloud builds submit failed for me yesterday.

Then I tried gcloud config set project, that also failed.

So I thought login might have expired so tried gcloud auth login.

In all cases, it always throws following error:

ERROR: gcloud crashed (ConnectionError): HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000198B0B26970>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

If you would like to report this issue, please run the following command:
  gcloud feedback

To check gcloud for common problems, please run the following command:
  gcloud info --run-diagnostics

On running diagnostics as suggested, everything seems fine.

>  gcloud info --run-diagnostics
Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

Property diagnostic detects issues that may be caused by properties.
Checking hidden properties...done.
Hidden Property Check passed.
Property diagnostic passed (1/1 checks passed).

I have also tried with my other google account, threw same error. It was working fine 1 day before. Have tried all Stackoverflow solutions, nothing seems to work.


问:
How can I generate random vectors with conditions? (Using Python)
I'm a beginner in programming and I'm looking for a nice idea how to generate n random 2D vectors
[a1,b1] [a2,b2] ... [an,bn] that satisfy the 3 conditions below.

```<code>(1) a1+a2+...+an=0

(2) b1+b2+...+bn=0

(3) (a1**2+b1**2)=(a2**2+b2**2)=...=(an**2+bn**2)=1/10000
</code>```

example : for n=4

```<code>[0.00258819045102518, 0.00965925826289069]

[0.00866025403784439, 0.00499999999999999]

[-0.00258819045102518, -0.00965925826289069]

[-0.00866025403784439, -0.00499999999999999]
</code>```

These four vectors satisfy all the conditions.

When n=4, I found the 4 vectors geometrically mean rhombus with a length of one side of 1/100. So I could solve it like this. (I used the Python 3)

```<code>import random

from math import *

import math

k1=pi*random.random()*2

k2=pi*random.random()*2

a1=math.cos(k1)/100

b1=math.sin(k1)/100

a2=math.cos(k2)/100

b2=math.sin(k2)/100

c1=[a1,b1]

c2=[a2,b2]

c3=[-a1,-b1]

c4=[-a2,-b2]

print(c1)

print(c2)

print(c3)

print(c4)
</code>```

But I failed to solve this problem for general n other than 4. Is there anyone who can help me? Thanks for reading this.

答:
Interesting puzzle. You did all hard work for even N (2, 4, 6, etc). After that you just need to wrap this logic inside loop:

import random
from math import pi, cos, sin

# insert how many iterations you want
n = int(input('insert N: '))

# is number of iterations odd?
is_odd = bool(n % 2)

# set number of iterations to even
# and devide it to 2
# because we need to set only half of all vectors
n = int(n / 2)

positive_vectors = []

# set N/2 vectors
for _ in range(0, n):
    k = pi*random.random()*2
    a = cos(k)/100
    b = sin(k)/100
    positive_vectors.append((a, b))

negative_vectors = []

# generate negative vectors with
# reversed values to satisfy 1 and 2 conditions (-0.4 + 0.4 = 0)
for el in positive_vectors:
    negative_vectors.append((-el[0], -el[1]))

# merge positive and negative vectors
vectors = positive_vectors + negative_vectors

if is_odd:
    # do something to satisfy conditions for odd N
    # we need to add one more last Nth element
    pass

# print results
sum_a = 0
sum_b = 0
i = 1

print(' ---')
for vector in vectors:
    sum_a = sum_a + vector[0]
    sum_b = sum_b + vector[1]
    print(vector)
    print(f"a{i}**2 + b{i}**2 =", "%.5f" % (vector[0]**2 + vector[1]**2))
    print(' ---')
    i += 1

print('a1+a2+...+an =', round(sum_a, 16))
print('b1+b2+...+bn =', round(sum_b, 16))
```
<p>Output will be:</p>
```insert N: 6
 ---
(0.009997486005014973, -0.00022421770565627118)
a1**2 + b1**2 = 0.00010
 ---
(0.0030141777667107295, -0.00953492172965603)
a2**2 + b2**2 = 0.00010
 ---
(0.0010585510434668018, -0.009943815650361553)
a3**2 + b3**2 = 0.00010
 ---
(-0.009997486005014973, 0.00022421770565627118)
a4**2 + b4**2 = 0.00010
 ---
(-0.0030141777667107295, 0.00953492172965603)
a5**2 + b5**2 = 0.00010
 ---
(-0.0010585510434668018, 0.009943815650361553)
a6**2 + b6**2 = 0.00010
 ---
a1+a2+...+an = 0.0
b1+b2+...+bn = 0.0
```

However if N is odd (3, 5, 7, etc) this solution will not work. I guess that we need to change last even element in vectors and add one last odd element to satisfy 1 and 2 conditions.

Body:
I'm a beginner in programming and I'm looking for a nice idea how to generate n random 2D vectors
[a1,b1] [a2,b2] ... [an,bn] that satisfy the 3 conditions below.

(1) a1+a2+...+an=0

(2) b1+b2+...+bn=0

(3) (a1**2+b1**2)=(a2**2+b2**2)=...=(an**2+bn**2)=1/10000

example : for n=4

[0.00258819045102518, 0.00965925826289069]

[0.00866025403784439, 0.00499999999999999]

[-0.00258819045102518, -0.00965925826289069]

[-0.00866025403784439, -0.00499999999999999]

These four vectors satisfy all the conditions.

When n=4, I found the 4 vectors geometrically mean rhombus with a length of one side of 1/100. So I could solve it like this. (I used the Python 3)

import random

from math import *

import math

k1=pi*random.random()*2

k2=pi*random.random()*2

a1=math.cos(k1)/100

b1=math.sin(k1)/100

a2=math.cos(k2)/100

b2=math.sin(k2)/100

c1=[a1,b1]

c2=[a2,b2]

c3=[-a1,-b1]

c4=[-a2,-b2]

print(c1)

print(c2)

print(c3)

print(c4)

But I failed to solve this problem for general n other than 4. Is there anyone who can help me? Thanks for reading this.

Body:
Interesting puzzle. You did all hard work for even N (2, 4, 6, etc). After that you just need to wrap this logic inside loop:

import random
from math import pi, cos, sin

# insert how many iterations you want
n = int(input('insert N: '))

# is number of iterations odd?
is_odd = bool(n % 2)

# set number of iterations to even
# and devide it to 2
# because we need to set only half of all vectors
n = int(n / 2)

positive_vectors = []

# set N/2 vectors
for _ in range(0, n):
    k = pi*random.random()*2
    a = cos(k)/100
    b = sin(k)/100
    positive_vectors.append((a, b))

negative_vectors = []

# generate negative vectors with
# reversed values to satisfy 1 and 2 conditions (-0.4 + 0.4 = 0)
for el in positive_vectors:
    negative_vectors.append((-el[0], -el[1]))

# merge positive and negative vectors
vectors = positive_vectors + negative_vectors

if is_odd:
    # do something to satisfy conditions for odd N
    # we need to add one more last Nth element
    pass

# print results
sum_a = 0
sum_b = 0
i = 1

print(' ---')
for vector in vectors:
    sum_a = sum_a + vector[0]
    sum_b = sum_b + vector[1]
    print(vector)
    print(f"a{i}**2 + b{i}**2 =", "%.5f" % (vector[0]**2 + vector[1]**2))
    print(' ---')
    i += 1

print('a1+a2+...+an =', round(sum_a, 16))
print('b1+b2+...+bn =', round(sum_b, 16))

Output will be:

insert N: 6
 ---
(0.009997486005014973, -0.00022421770565627118)
a1**2 + b1**2 = 0.00010
 ---
(0.0030141777667107295, -0.00953492172965603)
a2**2 + b2**2 = 0.00010
 ---
(0.0010585510434668018, -0.009943815650361553)
a3**2 + b3**2 = 0.00010
 ---
(-0.009997486005014973, 0.00022421770565627118)
a4**2 + b4**2 = 0.00010
 ---
(-0.0030141777667107295, 0.00953492172965603)
a5**2 + b5**2 = 0.00010
 ---
(-0.0010585510434668018, 0.009943815650361553)
a6**2 + b6**2 = 0.00010
 ---
a1+a2+...+an = 0.0
b1+b2+...+bn = 0.0

However if N is odd (3, 5, 7, etc) this solution will not work. I guess that we need to change last even element in vectors and add one last odd element to satisfy 1 and 2 conditions.


问:
Crash when using erase–remove idiom
When i execute the code below containing erase–remove idiom , i get a crash (segmentation fault). Id like to know what is the problem.</p>
```<code>class One
{
public:
    One() {}
    void print(){  std::cout << "print id: " << id << "\n"; }
    void setId(int i) { id =i;}
    int getID(){ return id;}
private:
    int id;
};

int main()
{
    std::vector<One*> v;
    std::vector<One*> v2;

    for (int i = 0; i < 10; ++i) {
        One* one = new One;
        one->setId(i);
        v.push_back(one);
        v2.push_back(one);
    }

    v.erase((std::remove(v.begin(), v.end(), v2[2]), v.end()));

    return 0;
}
</code>```

答:
This line of code:

```<code>v.erase((std::remove(v.begin(), v.end(), v2[2]), v.end()));
</code>```

is the equivalent of this:

```<code>v.erase((some_iterator, v.end()));
</code>```

where some_iterator is the return value of the call to std::remove.

That now becomes the equivalent of:

```<code>v.erase(v.end());
</code>```

The reason why is that the parentheses enclosed this statement:

```<code>(some_iterator, v.end())
</code>```

into an expression that invokes the comma operator.  The comma operator takes the value on the right of the comma, and uses that as the final value.

The correction is to remove the excessive parentheses:

```<code>v.erase(std::remove(v.begin(), v.end(), v2[2]), v.end());
</code>```

Title: Crash when using erase–remove idiom

Body:
When i execute the code below containing erase–remove idiom , i get a crash (segmentation fault). Id like to know what is the problem.

class One
{
public:
    One() {}
    void print(){  std::cout << "print id: " << id << "\n"; }
    void setId(int i) { id =i;}
    int getID(){ return id;}
private:
    int id;
};

int main()
{
    std::vector<One*> v;
    std::vector<One*> v2;

    for (int i = 0; i < 10; ++i) {
        One* one = new One;
        one->setId(i);
        v.push_back(one);
        v2.push_back(one);
    }

    v.erase((std::remove(v.begin(), v.end(), v2[2]), v.end()));

    return 0;
}

Body:
This line of code:

v.erase((std::remove(v.begin(), v.end(), v2[2]), v.end()));

is the equivalent of this:

v.erase((some_iterator, v.end()));

where some_iterator is the return value of the call to std::remove.

That now becomes the equivalent of:

v.erase(v.end());

The reason why is that the parentheses enclosed this statement:

(some_iterator, v.end())

into an expression that invokes the comma operator.  The comma operator takes the value on the right of the comma, and uses that as the final value.

The correction is to remove the excessive parentheses:

v.erase(std::remove(v.begin(), v.end(), v2[2]), v.end());