问:
CSS: How to shrink td containing ellipsis
I have done quite a bit or searching on this but could not find a solution for my specific case. I am a beginner to CSS and the solution is probably really simple, I just cannot find it. So I am trying to create a table that has some columns with long text. I am able to show ellipsis to cut off too long text, but I would like to have the column resize and the ellipsis be updated if I reduce the size of the window, that also reduces the size of the table itself. Now the cell width remains the same and a horizontal scroll bar is shown, which I want to prevent. I know using fixed width for the column is probably the problem, but it is the only way I am able to show the ellipsis in the first place, without fixed width no ellipsis is shown. Here is a very simplified piece of code and the css that easily shows the problem:

```<code><div class="tableFixHead">
  <table>
    <thead>
      <tr>
        <th>one</th>
        <th>two</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          first column
        </td>
        <td>
          <div class="overflowTableText">
            the entire text that is way too long to show all at once
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>
</code>```
```<code>.tableFixHead {
  overflow: scroll;
  height: 200px;
  max-width: 50%;
}

.overflowTableText {
  width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
</code>```

Any pointers are appreciated

答:
Good day, Do you know bootstap? you can easily do that with bootsrap
https://getbootstrap.com/docs/4.1/content/tables/#responsive-tables</p>

Body:
I have done quite a bit or searching on this but could not find a solution for my specific case. I am a beginner to CSS and the solution is probably really simple, I just cannot find it. So I am trying to create a table that has some columns with long text. I am able to show ellipsis to cut off too long text, but I would like to have the column resize and the ellipsis be updated if I reduce the size of the window, that also reduces the size of the table itself. Now the cell width remains the same and a horizontal scroll bar is shown, which I want to prevent. I know using fixed width for the column is probably the problem, but it is the only way I am able to show the ellipsis in the first place, without fixed width no ellipsis is shown. Here is a very simplified piece of code and the css that easily shows the problem:

        one
        two

          first column

            the entire text that is way too long to show all at once

.tableFixHead {
  overflow: scroll;
  height: 200px;
  max-width: 50%;
}

.overflowTableText {
  width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

Any pointers are appreciated


来源: stackexchange

问:
Connect Delphi XE OSX Firemonkey application with SQLite database
I need to convert applications wrote in Delphi XE3 to use it on a Mac OSX.
I use for this applicatiopn database SQLite but i cannot found firemonkey compatible components that i can use to connect with my databases.

How can i do?

Thank you

答: If you need to connect from Delphi XE3 to SQLite on Mac OSX, then you can use LiteDAC for this because these components are fully compatible with Firemonkey and support Mac OSX.</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to attach html element to angular
I'm using third party js tool, which inject some html code into the page, as far as I know it using  runOutsideAngular.

I need to find one of the element of that generated content and inject my component into it.
What I'm trying to do is

```<code>const element=document.getElementById("page");

const factory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
const ref = factory.create(this.injector, [],element);
this.applicationRef.attachView(ref.hostView);
</code>```

But this code doesn't work because that "page" element isn't tracked by angular. (If I inject my component into any tag defined in angular template it works)

How can I achieve this?

答:
Thanks.
I finally figure out.

so basically what i had to do is to run everything inside the angular zone.

```<code>    this.ngZone.run(() => {
      const element=document.getElementById("page");
      const factory = this.resolver.resolveComponentFactory(PdfRedactionComponent);
      const ref = factory.create(this.injector, [], element);
      this.app.attachView(ref.hostView);
    });
</code>```

And now everything is working as I expected.

Title: How to attach html element to angular

Body:
I'm using third party js tool, which inject some html code into the page, as far as I know it using  runOutsideAngular.

I need to find one of the element of that generated content and inject my component into it.
What I'm trying to do is

const element=document.getElementById("page");

const factory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
const ref = factory.create(this.injector, [],element);
this.applicationRef.attachView(ref.hostView);

But this code doesn't work because that "page" element isn't tracked by angular. (If I inject my component into any tag defined in angular template it works)

How can I achieve this?

Body:
Thanks.
I finally figure out.

so basically what i had to do is to run everything inside the angular zone.

    this.ngZone.run(() => {
      const element=document.getElementById("page");
      const factory = this.resolver.resolveComponentFactory(PdfRedactionComponent);
      const ref = factory.create(this.injector, [], element);
      this.app.attachView(ref.hostView);
    });

And now everything is working as I expected.


问:
JSON.parse() Returning Unexpected end of input
[`const express = require('express');
const app = express();
const https = require('https');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req ,res) => {
res.send("Server is Running")

```<code>https.get(url, (response) => {

    response.on("data", (data) => {

        const TimelineData = JSON.parse(data);
        console.log(TimelineData);

    })
})
</code>```

})

app.listen(3000, ()=>console.log("Server is Running 0n 5000"));`]1

const express = require('express');
const app = express();
const https = require('https');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req ,res) => {
    res.send("Server is Running")

    https.get(url, (response) => {

        response.on("data", (data) => {

            const TimelineData = JSON.parse(data);
            console.log(TimelineData);

        })
    })
})

app.listen(3000, ()=>console.log("Server is Running 0n 5000"));```

答: Listen for 'end ' the problem will be resolved</p>

Body:
[`const express = require('express');
const app = express();
const https = require('https');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req ,res) => {
res.send("Server is Running")

https.get(url, (response) => {

    response.on("data", (data) => {

        const TimelineData = JSON.parse(data);
        console.log(TimelineData);

    })
})

})

app.listen(3000, ()=>console.log("Server is Running 0n 5000"));`]1

const express = require('express');
const app = express();
const https = require('https');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req ,res) => {
    res.send("Server is Running")

    https.get(url, (response) => {

        response.on("data", (data) => {

            const TimelineData = JSON.parse(data);
            console.log(TimelineData);

        })
    })
})

app.listen(3000, ()=>console.log("Server is Running 0n 5000"));


问:
SQL Max from Subquery, Msg 102, Incorrect syntax near ')'
I'm trying to get only the Max-Results of the sums per day. I'm trying this with
Select Max(Anzahl) from (Subquery)

The Subquery itself works, but when I put it into the brackets, I get the following error message:

Msg 102, Level 15, State 1, Line 8
 Incorrect syntax near ')'.

See below for the whole query.

Many thanks for any hints!
Cheers
Lukas

```<code>select Max(Anzahl) from
(
select CONVERT(VARCHAR(10), log1.timestamp, 104) as Date, log1.ID, count(*) Anzahl
from log1
inner join base on log1.ID = base.ID
where abc like '%test%' and log1.xyz = 3
GROUP BY CONVERT(VARCHAR(10), log1.timestamp, 104), log1.ID
)
</code>```

答:
In SQL every derived table requires an alias so it can be uniquely identified, so

```<code>select Max(Anzahl) from
(
select CONVERT(VARCHAR(10), log1.timestamp, 104) as Date, log1.ID, count(*) Anzahl
from log1
inner join base on log1.ID = base.ID
where abc like '%test%' and log1.xyz = 3
GROUP BY CONVERT(VARCHAR(10), log1.timestamp, 104), log1.ID
) as AliasName
</code>```

Body:
I'm trying to get only the Max-Results of the sums per day. I'm trying this with
Select Max(Anzahl) from (Subquery)

The Subquery itself works, but when I put it into the brackets, I get the following error message:

Msg 102, Level 15, State 1, Line 8
 Incorrect syntax near ')'.

See below for the whole query.

Many thanks for any hints!
Cheers
Lukas

select Max(Anzahl) from
(
select CONVERT(VARCHAR(10), log1.timestamp, 104) as Date, log1.ID, count(*) Anzahl
from log1
inner join base on log1.ID = base.ID
where abc like '%test%' and log1.xyz = 3
GROUP BY CONVERT(VARCHAR(10), log1.timestamp, 104), log1.ID
)

Body:
In SQL every derived table requires an alias so it can be uniquely identified, so

select Max(Anzahl) from
(
select CONVERT(VARCHAR(10), log1.timestamp, 104) as Date, log1.ID, count(*) Anzahl
from log1
inner join base on log1.ID = base.ID
where abc like '%test%' and log1.xyz = 3
GROUP BY CONVERT(VARCHAR(10), log1.timestamp, 104), log1.ID
) as AliasName


问:
C# ToList inside LINQ
I'm working with LINQ and I wonder what's the difference between the two codes below. The result seems same but does using ToList() inside the query like student1 makes one more access to Database?

var students1 = (from stud in dbContext.Students.Where(s => s.LastName == "Doe").ToList()
               join class in dbContext.Classes
               on ...).ToList();

var students2 = (from stud in dbContext.Students.Where(s => s.LastName == "Doe")
               join class in dbContext.Classes
               on ...).ToList();
```

答:
LINQ to SQL is a facility for managing and accessing relational data as objects.

It connects to a database, converts LINQ constructs into SQL

submits the SQL

transforms results into objects

Even tracks changes and automatically requests database updates

Title: C# ToList inside LINQ


问:
uni-app vue3 script setup could not find the globalData in other vue components
I use vue3 setup in uni-app and I am adding globalData but it does not work in setup sugar:

App.vue

```
<p>I could not get the globalData in my <code>index.vue</code></p>
<pre class="lang-js prettyprint-override"><code>const app = getApp() as any;
let text = app.globalData.text;
</code>```

However,when I put it out of the setup then it works well.

App.vue

```

How to resolve it using setup?

答:
From Vue 3 docs:

Components using
```
<p>When a parent gets an instance of this component via template refs, the retrieved instance will be of the shape <code>{ a: number, b: number }</code> (refs are automatically unwrapped just like on normal instances).</p>
</blockquote>
<p>In your case, to expose <code>globalData</code>:</p>
<pre class="lang-html prettyprint-override"><code><script setup lang="ts">
⋮
const globalData = {
  text: 'mytext'
}

defineExpose({ globalData })
</script>
</code>```

demo

Body:
I use vue3 setup in uni-app and I am adding globalData but it does not work in setup sugar:

App.vue

I could not get the globalData in my index.vue

const app = getApp() as any;
let text = app.globalData.text;

However,when I put it out of the setup then it works well.

App.vue

How to resolve it using setup?

Body:
From Vue 3 docs:

Components using <script setup> are closed by default - i.e. the public instance of the component, which is retrieved via template refs or $parent chains, will not expose any of the bindings declared inside <script setup>.

To explicitly expose properties in a <script setup> component, use the defineExpose compiler macro:

<script setup>
import { ref } from 'vue'

const a = 1
const b = ref(2)

defineExpose({
  a,
  b
})
</script>

When a parent gets an instance of this component via template refs, the retrieved instance will be of the shape { a: number, b: number } (refs are automatically unwrapped just like on normal instances).

In your case, to expose globalData:

<script setup lang="ts">
⋮
const globalData = {
  text: 'mytext'
}

defineExpose({ globalData })
</script>

demo


问:
how to make GLSurfaceView as Translucent in Android 1.6?
My intention is to place an background image for a rendering cube.for that i need to make my GLSurfaceView as translucent, i tried APIDemos example,it give me how to make entire activity as translucent which is not my intention.  GLSurfaceViewObject.setZorderOnTop(true) statement worked fine but this method was not available till Android 2.1. Is there any alternative way for setZOrderOnTop(true) in Android 1.6 SDK?or is there any other way to make GLSurfaceView as translucent?</p>

答:
Why not simply draw a viewport filling textured quad as background? As in:</p>

```<code>glViewport(0,0,w,h);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,1,0,1,-1,1);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

GLfloat verts[8] = {0,0, 1,0, 1,1, 0,1};
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, verts);
glTexCoordPointer(2, GL_FLOAT, 0, verts);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

glClear(GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
YOUR_PROJECTION();

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
YOUR_MODELVIEW();

DRAW_YOUR_SCENE();
</code>```

Body:
Why not simply draw a viewport filling textured quad as background? As in:

glViewport(0,0,w,h);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,1,0,1,-1,1);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

GLfloat verts[8] = {0,0, 1,0, 1,1, 0,1};
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, verts);
glTexCoordPointer(2, GL_FLOAT, 0, verts);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

glClear(GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
YOUR_PROJECTION();

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
YOUR_MODELVIEW();

DRAW_YOUR_SCENE();


问:
MotionEvent's ACTION_UP could not work after ACTION_DOWN evet
I tried to users while to pressed button, run handler, then release button, finish it. But MotionEvent.ACTION_UP could not work like this below code, then my runnable infinite loop continue. How can I triggered ?</p>
```<code>myButton.setOnTouchListener{view, event->
when(event.action){
  MotionEvent.ACTION_DOWN -> {myhandler.post{myrunnableaction} true}
  MotionEvent.ACTION_UP -> { myhandler.removeCallbacks(myrunnableaction) true}
}
view.onTouchEvent(event) ?: true
}
 ``
</code>```

答: removeCallbacks method removes you Runnable from message queue, when your Runnable already launched you can't remove that with removeCallbacks method because already launched.

Body:
I tried to users while to pressed button, run handler, then release button, finish it. But MotionEvent.ACTION_UP could not work like this below code, then my runnable infinite loop continue. How can I triggered ?

myButton.setOnTouchListener{view, event->
when(event.action){
  MotionEvent.ACTION_DOWN -> {myhandler.post{myrunnableaction} true}
  MotionEvent.ACTION_UP -> { myhandler.removeCallbacks(myrunnableaction) true}
}
view.onTouchEvent(event) ?: true
}
 ``


问:
how to prevent system font-size changing effects to android application?
I recently finished developing my android application. I used sp (Scaled pixels) for all textSize. The problem is when i adjusted the system font-size, my application's font-sizes are changing. I can use dp (Device independent pixels) but it will take too long to maintain my application.

I referenced text size from this.

Is there a way to prevent system font-size changing effects to my application ?

答:
Tried answers about disabling fontScale in whole application. It's working, but I come to answer it's a terrible idea for only one reason:

You don't make your app better for visually impaired people.

Better way (I think) it's allow font scale but with restrictions only in some places, where you can't scale your text for it looks readable.

Realization (10.02.22)

After a day of thinking, I created Kotlin extension for TextView (also may use for EditText because it's a child):

```<code>fun TextView.removeFontScale() {
    val fontScale = resources.configuration.fontScale
    if (fontScale != 1f) {
        val scaledTextSize = textSize
        val newTextSize = scaledTextSize / fontScale / fontScale
        textSize = newTextSize
    }
}
</code>```

Need divide scaledTextSize twice because after setting a new textSize for TextView font scale will happen.

UPDATE / FIX (14.02.22)

Previous solution doesn't work on real devices, only emulator (vice versa it overwise increasing text size). So, I found another way:

```<code>val scaledTextSize = textSize
val newTextSize = scaledTextSize / fontScale
setTextSize(TypedValue.COMPLEX_UNIT_PX, newTextSize)
</code>```

Here new textSize for TextView after setting will not be scaled on fontScale value.

Use example:

```<code>titleText.removeFontScale()
subtitleText.removeFontScale()
</code>```

Logs of working, size in 1.3/1.5 scale become like in 1.0 scale:

Old realization (10.02.22):

```<code>fontScale: 1.0 | oldSize: 20
fontScale: 1.3 | oldSize: 26 | newSize: 20.0
</code>```

New realization (14.02.22):

```<code>fontScale: 1.5 | oldSize: 83.0 | newSize: 55.333332 | textSize: 55.333332
fontScale: 1.5 | oldSize: 58.0 | newSize: 38.666668 | textSize: 38.666668
</code>```

P.S. I notice that standard Toolbar didn't scale fonts and after that I understand that this practice is OK (disable scaling where it's really need).

Body:
Tried answers about disabling fontScale in whole application. It's working, but I come to answer it's a terrible idea for only one reason:

You don't make your app better for visually impaired people.

Better way (I think) it's allow font scale but with restrictions only in some places, where you can't scale your text for it looks readable.

Realization (10.02.22)

After a day of thinking, I created Kotlin extension for TextView (also may use for EditText because it's a child):

fun TextView.removeFontScale() {
    val fontScale = resources.configuration.fontScale
    if (fontScale != 1f) {
        val scaledTextSize = textSize
        val newTextSize = scaledTextSize / fontScale / fontScale
        textSize = newTextSize
    }
}

Need divide scaledTextSize twice because after setting a new textSize for TextView font scale will happen.

UPDATE / FIX (14.02.22)

Previous solution doesn't work on real devices, only emulator (vice versa it overwise increasing text size). So, I found another way:

val scaledTextSize = textSize
val newTextSize = scaledTextSize / fontScale
setTextSize(TypedValue.COMPLEX_UNIT_PX, newTextSize)

Here new textSize for TextView after setting will not be scaled on fontScale value.

Use example:

titleText.removeFontScale()
subtitleText.removeFontScale()

Logs of working, size in 1.3/1.5 scale become like in 1.0 scale:

Old realization (10.02.22):

fontScale: 1.0 | oldSize: 20
fontScale: 1.3 | oldSize: 26 | newSize: 20.0

New realization (14.02.22):

fontScale: 1.5 | oldSize: 83.0 | newSize: 55.333332 | textSize: 55.333332
fontScale: 1.5 | oldSize: 58.0 | newSize: 38.666668 | textSize: 38.666668

P.S. I notice that standard Toolbar didn't scale fonts and after that I understand that this practice is OK (disable scaling where it's really need).


问:
What is double exclamation mark in C#?
From https://source.dot.net/#System.Private.CoreLib/Hashtable.cs,475:

```<code>public virtual bool ContainsKey(object key!!)
</code>```

It looks like two null-forgiving operators. Is there a document about it?

答:
This is a null-parameter check syntax which was going to be introduced in C# 11. This proposal has since been rolled back following community feedback.

The proposal is here, and the PR doing a first roll-out to the runtime is here.

The syntax:

```<code>public void Foo(string bar!!)
{
}
</code>```

Is roughly equivalent to:

```<code>public void Foo(string bar)
{
    if (bar is null)
    {
        throw new ArgumentNullException(nameof(bar));
    }
}
</code>```

... although the actual implementation uses a throw helper, something like:

```<code>public void Foo(string bar)
{
    <PrivateImplementationDetails>.ThrowIfNull(bar, "bar");
}

[CompilerGenerated]
internal sealed class <PrivateImplementationDetails>
{
    internal static void Throw(string paramName)
    {
        throw new ArgumentNullException(paramName);
    }

    internal static void ThrowIfNull(object argument, string paramName)
    {
        if (argument == null)
        {
            Throw(paramName);
        }
    }
}
</code>```

See on SharpLab.

Methods containing throw statements are less likely to be inlined by the JIT, so using a throw helper makes it more likely that your method can be inlined, which might remove the null-check altogether! See on SharpLab.

Note that the use of !! is an implementation detail of your method: it just causes the compiler to insert code which you could have written yourself anyway. This means that moving from throw to !! (or vice versa) is not a breaking change.

There are a couple of places where !! will get the compiler to generate code which you can't (easily) write by hand, however.

One place where !! is particularly useful is in records with primary constructors. For example:

```<code>public record Person(string Name!!, int Age);
</code>```

In order to correctly null-check the Name parameter in previous versions of C#, you have to write this out longhand:

```<code>public record Person
{
    public string Name { get; init; }
    public int Age { get; init; }

    public Person(string name, int age)
    {
        if (name is null)
            throw new ArgumentNullException(nameof(name));
        (Name, Age) = (name, age);
    }

    public void Deconstruct(out string name, out int age) =>
        (name, age) = (Name, Age);
}
</code>```

Another place where !! does something which you can't write yourself is in chained constructor calls:

```<code>public class C
{
    public C(int i) { }
    public C(string s!!) : this(s.Length) { }
}
</code>```

This null-checks s before accessing s.Length, something like this (which isn't valid C#):

```<code>public C(string s)
{
    if (s is null)
        throw new ArgumentNullException(nameof(s));
    C(s.Length);
}
</code>```

See on SharpLab.

Another interesting aspect is that the null-checks are inserted before field assignments in constructors. For example:

```<code>public class C
{
    private readonly ExpensiveObject e = new ExpensiveObject();
    public C(string s!!) { }
}
</code>```

Is compiled as:

```<code>public class C
{
    private readonly ExpensiveObject e;
    public C(string s)
    {
        if (s is null)
            throw new ArgumentNullException(nameof(s));
        e = new ExpensiveObject();
    }
}
</code>```

That is, the null-check happens before the instantiation of ExpensiveObject. See on SharpLab.

Title: What is double exclamation mark in C#?

Body:
From https://source.dot.net/#System.Private.CoreLib/Hashtable.cs,475:

public virtual bool ContainsKey(object key!!)

It looks like two null-forgiving operators. Is there a document about it?

Body:
This is a null-parameter check syntax which was going to be introduced in C# 11. This proposal has since been rolled back following community feedback.

The proposal is here, and the PR doing a first roll-out to the runtime is here.

The syntax:

public void Foo(string bar!!)
{
}

Is roughly equivalent to:

public void Foo(string bar)
{
    if (bar is null)
    {
        throw new ArgumentNullException(nameof(bar));
    }
}

... although the actual implementation uses a throw helper, something like:

public void Foo(string bar)
{
    <PrivateImplementationDetails>.ThrowIfNull(bar, "bar");
}

[CompilerGenerated]
internal sealed class <PrivateImplementationDetails>
{
    internal static void Throw(string paramName)
    {
        throw new ArgumentNullException(paramName);
    }

    internal static void ThrowIfNull(object argument, string paramName)
    {
        if (argument == null)
        {
            Throw(paramName);
        }
    }
}

See on SharpLab.

Methods containing throw statements are less likely to be inlined by the JIT, so using a throw helper makes it more likely that your method can be inlined, which might remove the null-check altogether! See on SharpLab.

Note that the use of !! is an implementation detail of your method: it just causes the compiler to insert code which you could have written yourself anyway. This means that moving from throw to !! (or vice versa) is not a breaking change.

There are a couple of places where !! will get the compiler to generate code which you can't (easily) write by hand, however.

One place where !! is particularly useful is in records with primary constructors. For example:

public record Person(string Name!!, int Age);

In order to correctly null-check the Name parameter in previous versions of C#, you have to write this out longhand:

public record Person
{
    public string Name { get; init; }
    public int Age { get; init; }

    public Person(string name, int age)
    {
        if (name is null)
            throw new ArgumentNullException(nameof(name));
        (Name, Age) = (name, age);
    }

    public void Deconstruct(out string name, out int age) =>
        (name, age) = (Name, Age);
}

Another place where !! does something which you can't write yourself is in chained constructor calls:

public class C
{
    public C(int i) { }
    public C(string s!!) : this(s.Length) { }
}

This null-checks s before accessing s.Length, something like this (which isn't valid C#):

public C(string s)
{
    if (s is null)
        throw new ArgumentNullException(nameof(s));
    C(s.Length);
}

See on SharpLab.

Another interesting aspect is that the null-checks are inserted before field assignments in constructors. For example:

public class C
{
    private readonly ExpensiveObject e = new ExpensiveObject();
    public C(string s!!) { }
}

Is compiled as:

public class C
{
    private readonly ExpensiveObject e;
    public C(string s)
    {
        if (s is null)
            throw new ArgumentNullException(nameof(s));
        e = new ExpensiveObject();
    }
}

That is, the null-check happens before the instantiation of ExpensiveObject. See on SharpLab.


问:
PANDAS: int32 overflow? Can't bulid a pivot table
I use the pd.pivot_table() method to create a user-item matrix by pivoting the user-item activity data. However, the dataframe is so large that I got complain like this:

Unstacked DataFrame is too big, causing int32 overflow

Any suggestions on solving this problem? Thanks!

```<code>r_matrix = df.pivot_table(values='rating', index='userId', columns='movieId')
</code>```

答:
Converting the values column should resolve your issue:

df[‘ratings’] = df[‘ratings’].astype(‘int64’)

Body:
I use the pd.pivot_table() method to create a user-item matrix by pivoting the user-item activity data. However, the dataframe is so large that I got complain like this:

Unstacked DataFrame is too big, causing int32 overflow

Any suggestions on solving this problem? Thanks!

r_matrix = df.pivot_table(values='rating', index='userId', columns='movieId')


问:
Setting background color of a table view cell on iPhone
I want to achieve the effect where one cell of the table view will have blue background, the next one will have white, the next one will have blue again, and then white and so on... could you let me know how can I do that?

Thanks.

答:
When using the default table cell setting the following two properties will color both the cell's background and the background color of it's label, avoiding the need to create a custom label as a subview of the cell's contentView. </p>

```<code>cell.textLabel.backgroundColor = [UIColor redColor];
cell.contentView.backgroundColor = [UIColor redColor];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When using the default table cell setting the following two properties will color both the cell's background and the background color of it's label, avoiding the need to create a custom label as a subview of the cell's contentView.

cell.textLabel.backgroundColor = [UIColor redColor];
cell.contentView.backgroundColor = [UIColor redColor];


问:
gcloud pubsub subscriptions COMMAND "PURGE MESSAGES"
In GCP console you have the possibility to purge messages in a subscription.
It looks like "gcloud pubsub subscriptions" do not support a "PURGE MESSAGES" command.
What are the best alternatives are there any other libraries or API?</p>

答:
With gcloud tool this functionality is provided by the seek method. It effectively resets a subscription's backlog to a point in time or to a given snapshot. So, to purge all messages from a subscription you'd pass the current time via the --time flag, for example:

```<code>gcloud pubsub subscriptions seek my_subscription__name --time=2022-02-10T11:00:00Z
</code>```

Messages in the subscription that were published before this time are marked as acknowledged, and messages retained in the subscription that were published after this time are marked as unacknowledged.

The equivalent API endpoint for it is projects.subscriptions.seek.

Body:
With gcloud tool this functionality is provided by the seek method. It effectively resets a subscription's backlog to a point in time or to a given snapshot. So, to purge all messages from a subscription you'd pass the current time via the --time flag, for example:

gcloud pubsub subscriptions seek my_subscription__name --time=2022-02-10T11:00:00Z

Messages in the subscription that were published before this time are marked as acknowledged, and messages retained in the subscription that were published after this time are marked as unacknowledged.

The equivalent API endpoint for it is projects.subscriptions.seek.


问:
Returning cells as a Matrix VBA
I have a bunch of cells in a sheet that look like this:

Each rows has a gap of 3, and columns a gap of 5.

Id like to extract these values and copy it to some area:

How would I grab each cell and create a matrix like so. Im trying to use a VBA sub() for this, as the initial table size can vary but Im not sure how to do it. Any thoughts appreciated.

答:
The OP has asked for a VBA solution, so this answer may get down-voted!

However, as an alternative (if you have a recent Excel version) perhaps consider a spreadsheet function to do what you want:

In Sheet2, put this formula in a cell:

```<code>=LET(rngIn,Sheet1!A1:P10,x,MAX(rngIn)+1,rng,IF(LEN(rngIn)=0,x,rngIn),FILTER(FILTER(rng,INDEX(rng,1,,1)<>x),INDEX(rng,,1,1)<>x))
</code>```

Which has this result:

The formula essentially just filters out blanks: first by row and then by column. The input range can be any range, as long as the values are evenly spaced, with blank cells in between: so no need for specifying the gaps. This version works for numerical data, but can be modified if different types of data are used.

Using spreadsheet formulas can be a good alternative to VBA as they do not require the use of .xlsm macro-enabled workbooks.

Title: Returning cells as a Matrix VBA

Body:
The OP has asked for a VBA solution, so this answer may get down-voted!

However, as an alternative (if you have a recent Excel version) perhaps consider a spreadsheet function to do what you want:

In Sheet2, put this formula in a cell:

=LET(rngIn,Sheet1!A1:P10,x,MAX(rngIn)+1,rng,IF(LEN(rngIn)=0,x,rngIn),FILTER(FILTER(rng,INDEX(rng,1,,1)<>x),INDEX(rng,,1,1)<>x))

Which has this result:

The formula essentially just filters out blanks: first by row and then by column. The input range can be any range, as long as the values are evenly spaced, with blank cells in between: so no need for specifying the gaps. This version works for numerical data, but can be modified if different types of data are used.

Using spreadsheet formulas can be a good alternative to VBA as they do not require the use of .xlsm macro-enabled workbooks.


问:
first its coming the result after changes some code then its showing like Expected a value of type 'Map<dynamic, dynamic>', but got one of type Null
9:41 AM
{location: Berlin, flag: germany.png, time: 9:41 AM}
Restarted application in 4,422ms.

════════ Exception caught by widgets library ═══════════════════════════════════
The following TypeErrorImpl was thrown building Home(dirty, dependencies: [_ModalScopeStatus], state: _HomeState#b1e1d):
Expected a value of type 'Map<dynamic, dynamic>', but got one of type 'Null'

The relevant error-causing widget was
Home
lib\main.dart:14
When the exception was thrown, this was the stack
enter image description here

答:
Hope Coding Well Go fine...

In Flutter if we want to pass arguments between our Widgets we Because we are on Null safty so try to pass value as it data type such as..

For example here we are taking named Route.

for 1st Screen

Map value={....};

```<code>Navigator.PushNamed('Named of page' , argument : value!=null ? value : {'Key' : 'Value is null'} );
</code>```

Second Screen

```<code>final Map argument = ModalRoute.of(context)?.settings.arguments;
</code>```

NOTE: Try not to bind values as dynamic bind them as there datatype hope it will solve your issue..

Body:
Hope Coding Well Go fine...

In Flutter if we want to pass arguments between our Widgets we Because we are on Null safty so try to pass value as it data type such as..

For example here we are taking named Route.

for 1st Screen

Map value={....};

Navigator.PushNamed('Named of page' , argument : value!=null ? value : {'Key' : 'Value is null'} );

Second Screen

final Map argument = ModalRoute.of(context)?.settings.arguments;

NOTE: Try not to bind values as dynamic bind them as there datatype hope it will solve your issue..


问:
DataGrid without cell border after selection in MaterialDesign
I am using a datagrid in my WPF GUI where the user can make a double click on a row to see a page with details (this is working good):

Unfortunately, the border of a single cell would be visible after clicking (once) in a row, although I am already using selection unit FullRow. I was trying different options, colors etc. but everytime the border is showing. I was trying the steps from How to suppress DataGrid cell selection but it just changes the datagrid style.

```<code><DataGrid x:Name="DataGridMeasuringTasks" SelectionUnit="FullRow" Margin="20,145,0,44"
   RowDetailsVisibilityMode="VisibleWhenSelected" CanUserAddRows="False"
   CanUserDeleteRows="False" HorizontalAlignment="Left" Width="1612"
   SelectionMode="Single" IsReadOnly="True">

     <DataGrid.RowStyle>
         <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="#FFF0F0F0" />
         </Style>
     </DataGrid.RowStyle>

     <DataGrid.Background>
         <SolidColorBrush Color="#FFF0F0F0"/>
     </DataGrid.Background>
</DataGrid>
</code>```

How can I remove the border?

答:
The MaterialDesign style for data grid cells is defined here. You have to copy and adapt the style, because the trigger for the border brush will take precedence over local values. Remove this part.

```<code><Trigger Property="IsKeyboardFocusWithin" Value="True">
    <Setter Property="BorderBrush" Value="{DynamicResource MaterialDesignTextBoxBorder}" />
</Trigger>
</code>```

Then, assign the style as CellStyle to your specific DataGrid or move it to a resource dictionary in scope or even the application resources to automatically apply the style to all cells in scope.

```<code><DataGrid x:Name="DataGridMeasuringTasks" SelectionUnit="FullRow" Margin="20,145,0,44"
   RowDetailsVisibilityMode="VisibleWhenSelected" CanUserAddRows="False"
   CanUserDeleteRows="False" HorizontalAlignment="Left" Width="1612"
   SelectionMode="Single" IsReadOnly="True">

     <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Setter Property="Padding" Value="{Binding RelativeSource={RelativeSource Self}, Path=(materialDesign:DataGridAssist.CellPadding)}" />
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="BorderBrush" Value="Transparent" />
            <Setter Property="Validation.ErrorTemplate" Value="{x:Null}" />
            <Setter Property="Foreground" Value="{Binding Foreground, RelativeSource={RelativeSource AncestorType=DataGridRow}}" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid>
                            <Border
                                Background="{TemplateBinding Background}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                SnapsToDevicePixels="True" />
                            <ContentPresenter Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
               <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="True" />
                        <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=DataGridRow}}" Value="False" />
                    </MultiDataTrigger.Conditions>
                    <Setter Property="Background" Value="{DynamicResource MaterialDesignSelection}" />
                </MultiDataTrigger>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Opacity" Value=".56" />
                </Trigger>
            </Style.Triggers>
        </Style>
     </DataGrid.CellStyle>

     <DataGrid.RowStyle>
         <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="#FFF0F0F0" />
         </Style>
     </DataGrid.RowStyle>

     <DataGrid.Background>
         <SolidColorBrush Color="#FFF0F0F0"/>
     </DataGrid.Background>
</DataGrid>
</code>```

Body:
I am using a datagrid in my WPF GUI where the user can make a double click on a row to see a page with details (this is working good):

Unfortunately, the border of a single cell would be visible after clicking (once) in a row, although I am already using selection unit FullRow. I was trying different options, colors etc. but everytime the border is showing. I was trying the steps from How to suppress DataGrid cell selection but it just changes the datagrid style.

<DataGrid x:Name="DataGridMeasuringTasks" SelectionUnit="FullRow" Margin="20,145,0,44"
   RowDetailsVisibilityMode="VisibleWhenSelected" CanUserAddRows="False"
   CanUserDeleteRows="False" HorizontalAlignment="Left" Width="1612"
   SelectionMode="Single" IsReadOnly="True">

     <DataGrid.RowStyle>

     </DataGrid.RowStyle>

     <DataGrid.Background>
         <SolidColorBrush Color="#FFF0F0F0"/>
     </DataGrid.Background>
</DataGrid>

How can I remove the border?

Body:
The MaterialDesign style for data grid cells is defined here. You have to copy and adapt the style, because the trigger for the border brush will take precedence over local values. Remove this part.

<Trigger Property="IsKeyboardFocusWithin" Value="True">
    <Setter Property="BorderBrush" Value="{DynamicResource MaterialDesignTextBoxBorder}" />
</Trigger>

Then, assign the style as CellStyle to your specific DataGrid or move it to a resource dictionary in scope or even the application resources to automatically apply the style to all cells in scope.

<DataGrid x:Name="DataGridMeasuringTasks" SelectionUnit="FullRow" Margin="20,145,0,44"
   RowDetailsVisibilityMode="VisibleWhenSelected" CanUserAddRows="False"
   CanUserDeleteRows="False" HorizontalAlignment="Left" Width="1612"
   SelectionMode="Single" IsReadOnly="True">

     <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Setter Property="Padding" Value="{Binding RelativeSource={RelativeSource Self}, Path=(materialDesign:DataGridAssist.CellPadding)}" />
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="BorderBrush" Value="Transparent" />
            <Setter Property="Validation.ErrorTemplate" Value="{x:Null}" />
            <Setter Property="Foreground" Value="{Binding Foreground, RelativeSource={RelativeSource AncestorType=DataGridRow}}" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid>
                            <Border
                                Background="{TemplateBinding Background}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                SnapsToDevicePixels="True" />
                            <ContentPresenter Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
               <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="True" />
                        <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=DataGridRow}}" Value="False" />
                    </MultiDataTrigger.Conditions>
                    <Setter Property="Background" Value="{DynamicResource MaterialDesignSelection}" />
                </MultiDataTrigger>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Opacity" Value=".56" />
                </Trigger>
            </Style.Triggers>
        </Style>
     </DataGrid.CellStyle>

     <DataGrid.RowStyle>
         <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="#FFF0F0F0" />
         </Style>
     </DataGrid.RowStyle>

     <DataGrid.Background>
         <SolidColorBrush Color="#FFF0F0F0"/>
     </DataGrid.Background>
</DataGrid>


问:
Is it possible to clone a Google analytics account to another GA account
I have a google account from which my Admin access was removed, now the person is asking me to pay up for my data.
Is there a way for me to export all the data I have from my old account and import it to a new account.
currently I have "editor" access to the old account
If not is there any other way for me to get my account data</p>

答:
I have a google account from which my Admin access was removed, now the person is asking me to pay up for my data.

This is going to be your best options.

Is there a way for me to export all the data I have from my old account and import it to a new account.

You could use the google analytics api to extract your data but inserting new data will not be inserted using the old dates. Hits in Google analytics are recorded for the most part when they come in.  You can set an offset but its only a matter of hours. You wont be able to rebuild the entire system.

currently I have "editor" access to the old account If not is there any other way for me to get my account data

if you have a google analytics 360 account you could export it into big query.

There is really no other way to get your data back besides them giving you admin access.


问:
How to create different keys for ReordableListView, in async enviroment?
I am trying to create fake firebase, and i have problem with "key: ValueKey(index),". I am trying create elements in "ReorderableListView".

```<code>FutureBuilder<List<FirstListModel>>(
                  future: fakeFirebase.getList(),
                  builder: (context, snapshot) {
                    return snapshot.data != null
                        ? ReorderableListView.builder(
                            (some code)
                            itemCount: snapshot.data!.length,
                            itemBuilder: (context, index) {
                              if (snapshot.data != null) {
                                for (var item in snapshot.data!) {
                                  return buildPlate(index, item);
                                }
                              } else {
                                return const CircularProgressIndicator();
                              }
                              throw Exception("Error I am Empty");
                            },
                          )
                        : const CircularProgressIndicator();
                  },
                )
</code>```

i am creating items for that ReorderableListView in floatingActionButton which is in my Scaffold:

```<code>Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: _addWidget,
      ),
      (some code)
      body: Center(
          child: fakeFirebase.firstList.isNotEmpty
              ? FutureBuilder<List<FirstListModel>>(
</code>```

this code is in my floatingActionButton:

```<code>void _addWidget() {
    lol++;
    final item = FirstListModel(text: lol.toString(), id: lol.toString());
    setState(() {
      fakeFirebase.addElement(item);
    });
  }
</code>```

this place is my "key", which is creating my problems:

```<code>  Widget buildPlate(int index, FirstListModel oneElement) {
    return ListTile(
      key: ValueKey(index),
</code>```

this is my model:

```<code>class FirstListModel {
  String text;
  String id;
  FirstListModel({
    required this.text,
    required this.id,
  });
}
</code>```

right now i put in my "key" index, in hope it will not create an error, sadly when i press my floatingActionButton in order to add new elements it only shows meany times one element.
I want to create new elements that cen be edited and deleted, drag and droped, but i know this "key" is a reson that i am not able to do it, someon have a solution to my problem? if you need more code, i can provide it, i am creating this app to learn.

答:
if someon find this problem, i found a solution:

i had problem in here:

```<code> itemBuilder: (context, index) {
                              if (snapshot.data != null) {
                                for (var item in snapshot.data!) {
                                  return buildPlate(index, item);
                                }
                              }
</code>```

i needed to change this as follows:

```<code>itemBuilder: (context, index) {
                              if (snapshot.data?[index] != null) {
                                return buildPlate(index, snapshot.data![index]);
                              } else {
                                return const CircularProgressIndicator();
                              }
                              throw Exception("Error I am Empty");
                            },
</code>```

now I have still a problems, but it is running

Body:
I am trying to create fake firebase, and i have problem with "key: ValueKey(index),". I am trying create elements in "ReorderableListView".

FutureBuilder<List<FirstListModel>>(
                  future: fakeFirebase.getList(),
                  builder: (context, snapshot) {
                    return snapshot.data != null
                        ? ReorderableListView.builder(
                            (some code)
                            itemCount: snapshot.data!.length,
                            itemBuilder: (context, index) {
                              if (snapshot.data != null) {
                                for (var item in snapshot.data!) {
                                  return buildPlate(index, item);
                                }
                              } else {
                                return const CircularProgressIndicator();
                              }
                              throw Exception("Error I am Empty");
                            },
                          )
                        : const CircularProgressIndicator();
                  },
                )

i am creating items for that ReorderableListView in floatingActionButton which is in my Scaffold:

Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: _addWidget,
      ),
      (some code)
      body: Center(
          child: fakeFirebase.firstList.isNotEmpty
              ? FutureBuilder<List<FirstListModel>>(

this code is in my floatingActionButton:

void _addWidget() {
    lol++;
    final item = FirstListModel(text: lol.toString(), id: lol.toString());
    setState(() {
      fakeFirebase.addElement(item);
    });
  }

this place is my "key", which is creating my problems:

  Widget buildPlate(int index, FirstListModel oneElement) {
    return ListTile(
      key: ValueKey(index),

this is my model:

class FirstListModel {
  String text;
  String id;
  FirstListModel({
    required this.text,
    required this.id,
  });
}

right now i put in my "key" index, in hope it will not create an error, sadly when i press my floatingActionButton in order to add new elements it only shows meany times one element.
I want to create new elements that cen be edited and deleted, drag and droped, but i know this "key" is a reson that i am not able to do it, someon have a solution to my problem? if you need more code, i can provide it, i am creating this app to learn.

Body:
if someon find this problem, i found a solution:

i had problem in here:

 itemBuilder: (context, index) {
                              if (snapshot.data != null) {
                                for (var item in snapshot.data!) {
                                  return buildPlate(index, item);
                                }
                              }

i needed to change this as follows:

itemBuilder: (context, index) {
                              if (snapshot.data?[index] != null) {
                                return buildPlate(index, snapshot.data![index]);
                              } else {
                                return const CircularProgressIndicator();
                              }
                              throw Exception("Error I am Empty");
                            },

now I have still a problems, but it is running


问:
Why the print('\n', 'abc') in Python 3 is giving new line and an empty space?
I was just expecting a new line character and written below code.

```<code>>>> print('\n', 'abc')

 abc
>>>
</code>```

But it gave single space also in front of the string abc, may I know why it added that space?

I am using Python 3.9 in Windows 10

答: If given more than one argument, print joins them with spaces, so you are effectively doing print("\n abc").

Body:
I was just expecting a new line character and written below code.

>>> print('\n', 'abc')

 abc
>>>

But it gave single space also in front of the string abc, may I know why it added that space?

I am using Python 3.9 in Windows 10


问:
PHP not creating $_SESSION variable on session_start();
I have 3 pages in my set up here:

login.php: The login page that contains the username and password fields which submits to

checklogin.php: Which checks to see if the credentials are right which redirects to

login_successful.php: Which displays the user's name

login.php starts with

```<code><?php session_start(); ?>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <?php
        include 'content.php';
        echo $head;
    ?>
</head>
</code>```

Which should initialize a global $_SESSION variable right?

checklogin.php has some code which looks like this:

```<code>if (mysql_num_rows($result) < 1)
{
    /* Access denied */
    echo 'Sorry, your username or password was incorrect!';
}
else
{
    $_SESSION['username'] = $username;

    /* Log user in */
    header("location:login_successful.php");
}
</code>```

login_successful.php looks like this:

```<code><div id="title" style="margin:5px">
    <h2>Welcome back <?php echo $_SESSION['username']; ?>!</p>
</div>
</code>```

Unfortunately when I go through the login procedure and get to login_successful.php, I get this error "Notice: Undefined variable: _SESSION in C:\wamp\www\login_successful.php on line 15" even though I clearly started a session in login.php.

Why is it doing this?

答: You need to remember session_start() in checklogin.php</p>

Body:
I have 3 pages in my set up here:

login.php: The login page that contains the username and password fields which submits to

checklogin.php: Which checks to see if the credentials are right which redirects to

login_successful.php: Which displays the user's name

login.php starts with

<?php session_start(); ?>

    <?php
        include 'content.php';
        echo $head;
    ?>

Which should initialize a global $_SESSION variable right?

checklogin.php has some code which looks like this:

if (mysql_num_rows($result) < 1)
{
    /* Access denied */
    echo 'Sorry, your username or password was incorrect!';
}
else
{
    $_SESSION['username'] = $username;

    /* Log user in */
    header("location:login_successful.php");
}

login_successful.php looks like this:

Welcome back <?php echo $_SESSION['username']; ?>!

Unfortunately when I go through the login procedure and get to login_successful.php, I get this error "Notice: Undefined variable: _SESSION in C:\wamp\www\login_successful.php on line 15" even though I clearly started a session in login.php.

Why is it doing this?


问:
Why my flatlist is filtered for a second only
I am creating a restaurant app in which I am trying to filter my flatlist based on the category being selected. At the initial point when the app is open and no category is selected flatlist display all categories data but when I click on any category the flatlist displays the filtered data just for a second but then again it displays all categories data

```<code>import React, { useState } from "react";
import { View, Text, StyleSheet, SafeAreaView, TouchableOpacity, Image, FlatList } from "react-native";
import { COLORS, icons, SIZES, images, FONTS } from '../constants';
import { firebase } from '@react-native-firebase/database';

const Home = ({ navigation }) => {

const [menu, setMenu] = useState(null)

const reference = firebase
    .app()
    .database('https://bm-restaurant-default-rtdb.europe-west1.firebasedatabase.app/')
    .ref('/Menu/');

reference.on('value', snapshot => {
    setMenu(Object.values(snapshot.val()));
});

const categoryData = [
    {
        id: 1,
        name: "Rolls",
        icon: icons.ch_roll,
    },
    {
        id: 2,
        name: "Burgers",
        icon: icons.burgers,
    },
    {
        id: 3,
        name: "Bar B Q",
        icon: icons.barbq,
    },
    {
        id: 4,
        name: "CH\nHandi",
        icon: icons.ch_handi,
    },
    {
        id: 5,
        name: "CH\nKarhai",
        icon: icons.ch_karahi,
    },
    {
        id: 6,
        name: "Mutton",
        icon: icons.mutton_karahi,
    },
    {
        id: 7,
        name: "Fish",
        icon: icons.fish,
    },
    {
        id: 8,
        name: "Dal\nSabzi",
        icon: icons.dal,
    },
    {
        id: 9,
        name: "Paratha",
        icon: icons.paratha,
    },
    {
        id: 10,
        name: "Sand\nWiches",
        icon: icons.sandwich,
    },
    {
        id: 11,
        name: "French\nFries",
        icon: icons.french_fries,
    },
    {
        id: 12,
        name: "Drinks",
        icon: icons.cold_drinks,
    },

]

const [categories, setCategories] = useState(categoryData)
const [selectedCategory, setSelectedCategory] = useState(null)

function onSelectCategory(category) {
    //filter restaurant
    let menuList = menu.filter(menu => parseInt(menu.category) == (category.id))
    setMenu(menuList)
    setSelectedCategory(category)
}

function renderMainCategories() {
    const renderItem = ({ item }) => {
        return (
            <TouchableOpacity
                style={{
                    padding: SIZES.padding,
                    paddingBottom: SIZES.padding * 2,
                    backgroundColor: (selectedCategory?.id == item.id) ? COLORS.primary : COLORS.white,
                    justifyContent: 'center',
                    alignItems: 'center',
                    marginRight: SIZES.padding,
                    borderRadius: 40,
                    ...styles.shadow
                }}
                onPress={() => onSelectCategory(item)}>
                <View
                    style={{
                        width: 60,
                        height: 60,
                        borderRadius: 30,
                        alignItems: 'center',
                        justifyContent: 'center',
                        backgroundColor: (selectedCategory?.id == item.id) ? COLORS.white : COLORS.lightGray
                    }}>
                    <Image
                        source={item.icon}
                        resizeMode="contain"
                        style={{
                            height: 45,
                            width: 45
                        }} />
                </View>
                <Text
                    style={{
                        textAlign: 'center',
                        marginTop: SIZES.padding,
                        color: (selectedCategory?.id == item.id) ? COLORS.white : COLORS.black,
                        ...FONTS.body4
                    }}>{item.name}</Text>

            </TouchableOpacity>
        )

    }
    return (
        <View style={{ padding: SIZES.padding * 2 }}>
            <Text style={{ ...FONTS.h1 }}>Categories</Text>

            <FlatList
                data={categories}
                horizontal
                showsHorizontalScrollIndicator={false}
                keyExtractor={item => `${item.id}`}
                renderItem={renderItem}
                contentContainerStyle={{ paddingVertical: SIZES.padding * 2, paddingLeft: 2 }} />
        </View>
    )
}

function renderRestaurantList() {
    const renderItem = ({ item }) => {
        return (
            <TouchableOpacity
                style={{ margin: 8, width: (SIZES.width * 0.5 - 24), height: 200 }}
                onPress={() => navigation.navigate('Restaurant', {
                    item,
                    currentLocation
                })}>

                {/* Image */}
                <Image
                    source={icons.burgers}
                    style={{
                        width: '100%',
                        height: '100%',
                        borderRadius: SIZES.radius
                    }}
                />
                <View
                    style={{
                        padding: SIZES.padding,
                        position: 'absolute',
                        bottom: 0,
                        height: 60,
                        backgroundColor: COLORS.white,
                        width: '100%',
                        borderRadius: 25,
                        justifyContent: 'center',
                        alignItems: 'center',
                        ...styles.shadow
                    }}>
                    <Text style={{ ...FONTS.body4, color: COLORS.black, textAlign: 'center' }}>{item.name}</Text>
                    <Text style={{ ...FONTS.body3, color: COLORS.primary }}>Rs. {item.price}</Text>

                </View>
            </TouchableOpacity>

        )

    }
    return (
        <FlatList
            data={menu}
            numColumns={2}
            keyExtractor={item => `${item.name}`}
            min-height={4}
            renderItem={renderItem}
            contentContainerStyle={{
                paddingLeft: 8,
                paddingRight: 8

            }} />

    )
}

return (
    <SafeAreaView style={styles.container}>
        {renderMainCategories()}
        {renderRestaurantList()}
    </SafeAreaView>
)

}
</code>```

initial state ss

category selected ss

after 1 second ss

答:
You are not re-rendering the flatlist that's why its happening.

Flatlists are pure components and they need a way to know if it needs to re-render. Luckily we have extraData prop for flatlist, pass your data state to it and it will re-render.

Body:
I am creating a restaurant app in which I am trying to filter my flatlist based on the category being selected. At the initial point when the app is open and no category is selected flatlist display all categories data but when I click on any category the flatlist displays the filtered data just for a second but then again it displays all categories data

import React, { useState } from "react";
import { View, Text, StyleSheet, SafeAreaView, TouchableOpacity, Image, FlatList } from "react-native";
import { COLORS, icons, SIZES, images, FONTS } from '../constants';
import { firebase } from '@react-native-firebase/database';

const Home = ({ navigation }) => {

const [menu, setMenu] = useState(null)

const reference = firebase
    .app()
    .database('https://bm-restaurant-default-rtdb.europe-west1.firebasedatabase.app/')
    .ref('/Menu/');

reference.on('value', snapshot => {
    setMenu(Object.values(snapshot.val()));
});

const categoryData = [
    {
        id: 1,
        name: "Rolls",
        icon: icons.ch_roll,
    },
    {
        id: 2,
        name: "Burgers",
        icon: icons.burgers,
    },
    {
        id: 3,
        name: "Bar B Q",
        icon: icons.barbq,
    },
    {
        id: 4,
        name: "CH\nHandi",
        icon: icons.ch_handi,
    },
    {
        id: 5,
        name: "CH\nKarhai",
        icon: icons.ch_karahi,
    },
    {
        id: 6,
        name: "Mutton",
        icon: icons.mutton_karahi,
    },
    {
        id: 7,
        name: "Fish",
        icon: icons.fish,
    },
    {
        id: 8,
        name: "Dal\nSabzi",
        icon: icons.dal,
    },
    {
        id: 9,
        name: "Paratha",
        icon: icons.paratha,
    },
    {
        id: 10,
        name: "Sand\nWiches",
        icon: icons.sandwich,
    },
    {
        id: 11,
        name: "French\nFries",
        icon: icons.french_fries,
    },
    {
        id: 12,
        name: "Drinks",
        icon: icons.cold_drinks,
    },

]

const [categories, setCategories] = useState(categoryData)
const [selectedCategory, setSelectedCategory] = useState(null)

function onSelectCategory(category) {
    //filter restaurant
    let menuList = menu.filter(menu => parseInt(menu.category) == (category.id))
    setMenu(menuList)
    setSelectedCategory(category)
}

function renderMainCategories() {
    const renderItem = ({ item }) => {
        return (
            <TouchableOpacity
                style={{
                    padding: SIZES.padding,
                    paddingBottom: SIZES.padding * 2,
                    backgroundColor: (selectedCategory?.id == item.id) ? COLORS.primary : COLORS.white,
                    justifyContent: 'center',
                    alignItems: 'center',
                    marginRight: SIZES.padding,
                    borderRadius: 40,
                    ...styles.shadow
                }}
                onPress={() => onSelectCategory(item)}>
                <View
                    style={{
                        width: 60,
                        height: 60,
                        borderRadius: 30,
                        alignItems: 'center',
                        justifyContent: 'center',
                        backgroundColor: (selectedCategory?.id == item.id) ? COLORS.white : COLORS.lightGray
                    }}>
                    <Image
                        source={item.icon}
                        resizeMode="contain"
                        style={{
                            height: 45,
                            width: 45
                        }} />
                </View>
                <Text
                    style={{
                        textAlign: 'center',
                        marginTop: SIZES.padding,
                        color: (selectedCategory?.id == item.id) ? COLORS.white : COLORS.black,
                        ...FONTS.body4
                    }}>{item.name}</Text>

            </TouchableOpacity>
        )

    }
    return (
        <View style={{ padding: SIZES.padding * 2 }}>
            <Text style={{ ...FONTS.h1 }}>Categories</Text>

            <FlatList
                data={categories}
                horizontal
                showsHorizontalScrollIndicator={false}
                keyExtractor={item => `${item.id}`}
                renderItem={renderItem}
                contentContainerStyle={{ paddingVertical: SIZES.padding * 2, paddingLeft: 2 }} />
        </View>
    )
}

function renderRestaurantList() {
    const renderItem = ({ item }) => {
        return (
            <TouchableOpacity
                style={{ margin: 8, width: (SIZES.width * 0.5 - 24), height: 200 }}
                onPress={() => navigation.navigate('Restaurant', {
                    item,
                    currentLocation
                })}>

                {/* Image */}
                <Image
                    source={icons.burgers}
                    style={{
                        width: '100%',
                        height: '100%',
                        borderRadius: SIZES.radius
                    }}
                />
                <View
                    style={{
                        padding: SIZES.padding,
                        position: 'absolute',
                        bottom: 0,
                        height: 60,
                        backgroundColor: COLORS.white,
                        width: '100%',
                        borderRadius: 25,
                        justifyContent: 'center',
                        alignItems: 'center',
                        ...styles.shadow
                    }}>
                    <Text style={{ ...FONTS.body4, color: COLORS.black, textAlign: 'center' }}>{item.name}</Text>
                    <Text style={{ ...FONTS.body3, color: COLORS.primary }}>Rs. {item.price}</Text>

                </View>
            </TouchableOpacity>

        )

    }
    return (
        <FlatList
            data={menu}
            numColumns={2}
            keyExtractor={item => `${item.name}`}
            min-height={4}
            renderItem={renderItem}
            contentContainerStyle={{
                paddingLeft: 8,
                paddingRight: 8

            }} />

    )
}

return (
    <SafeAreaView style={styles.container}>
        {renderMainCategories()}
        {renderRestaurantList()}
    </SafeAreaView>
)

}

initial state ss

category selected ss

after 1 second ss


问:
Why is the asterisk before the variable name, rather than after the type?
Why do most C programmers name variables like this:

```<code>int *myVariable;
</code>```

rather than like this:

```<code>int* myVariable;
</code>```

Both are valid. It seems to me that the asterisk is a part of the type, not a part of the variable name. Can anyone explain this logic?

答:
When you initialize and assign a variable in one statement, e.g.

```<code>int *a = xyz;
</code>```

you assign the value of xyz to a, not to *a. This makes

```<code>int* a = xyz;
</code>```

a more consistent notation.

OwnerDisplayName: WBlasko

Body:
Why do most C programmers name variables like this:

int *myVariable;

rather than like this:

int* myVariable;

Both are valid. It seems to me that the asterisk is a part of the type, not a part of the variable name. Can anyone explain this logic?

LastEditorDisplayName: WBlasko

Body:
When you initialize and assign a variable in one statement, e.g.

int *a = xyz;

you assign the value of xyz to a, not to *a. This makes

int* a = xyz;

a more consistent notation.


答:
You need to use

/^(?![0.]+$)(?:\d{1,2}(?:\.\d{1,10})?|100(?:\.0{1,10})?)$/
```

See the regex demo.

Details:

^ - start of string

(?![0.]+$) - no only 0 and/or . chars till end of string are allowed

(?: - either of

\d{1,2}(?:\.\d{1,10})? - one or two digits and then an optional occurrence of a . and one to ten digits

| - or

100(?:\.0{1,10})? - 100 and then an optional occurrence of a . and one to ten 0 chars

) - end of the group

$ - end of string.

Title: Regex - Validation of numeric with up to 10 decimal places (0.01 - 100.0000000000)

Body:
I am just curious if this regex expression will be able to be shorten. it should allow ten digits.

/^(?!0+(?:\.0+)?$)(\d{1,2}\.\d{1,10}|\d{1,2}|(100)|(100\\.00)|(100\\.0000000000)|(100\\.000000000)|(100\\.00000000)|(100\\.0000000)|(100\\.000000)|(100\\.00000)|(100\\.0000)|(100\\.0000)|(100\\.000)|(100\\.0))$/

Body:
You need to use

/^(?![0.]+$)(?:\d{1,2}(?:\.\d{1,10})?|100(?:\.0{1,10})?)$/

See the regex demo.

Details:

^ - start of string

(?![0.]+$) - no only 0 and/or . chars till end of string are allowed

(?: - either of

\d{1,2}(?:\.\d{1,10})? - one or two digits and then an optional occurrence of a . and one to ten digits

| - or

100(?:\.0{1,10})? - 100 and then an optional occurrence of a . and one to ten 0 chars

) - end of the group

$ - end of string.


问:
How to filter a data frame
I have a data frame and tried to select only the observations I'm interested in by this:

```<code>data[data["Var1"]>10]
</code>```

Unfortunately, this command destroys the data.frame structure and returns a long vector.

What I want to get is the data.frame shortened by the observations that don't match my criteria.

Title: How to filter a data frame

Body:
I have a data frame and tried to select only the observations I'm interested in by this:

data[data["Var1"]>10]

Unfortunately, this command destroys the data.frame structure and returns a long vector.

What I want to get is the data.frame shortened by the observations that don't match my criteria.

Body:
You are missing a comma in your statement.

Try this:

data[data[, "Var1"]>10, ]

Or:

data[data$Var1>10, ]

Or:

subset(data, Var1>10)

As an example, try it on the built-in dataset, mtcars

data(mtcars)

mtcars[mtcars[, "mpg"]>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

mtcars[mtcars$mpg>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

subset(mtcars, mpg>25)

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2


问:
glVertex3fv giving error in when i read a data using ifstream in OpenGL C++
I am making an OpenGL program using C++ on Visual Studio. I have read the CSV file data for the coordinates using a code available on Stackoverflow OpenGL - Plotting Points from external file. But now I am getting errors on the object with ifstream. You can consult the link to get a better understanding (OpenGL - Plotting Points from external file).

```<code>// CSV File Loader and 3D Rendering Class

#include "CSV.h"
#include <iostream>
#include<string>
#include<sstream>
#include <fstream>
#include <vector>
#include "C:\Users\srcco\Desktop\Track Viewer\glut-3.7\include\GL\glut.h"
using namespace std;
CSV::CSV(string Fname) {
    class CSV {
    public:
        CSV() {
            ifstream csvdata("demo.csv");
            string line;
            while (getline(csvdata,line))
            {
                stringstream lineStream(line);
                string cell;
                vector<float> parsedRow;
                while (std::getline(lineStream, cell, ','))
                {
                    parsedRow.push_back(stof(cell));
                }
                if (parsedRow.size() == 3)
                {
                    glBegin(GL_POINTS);
                    glColor3f(0.0f, 1.0f, 1.0f);
                    glVertex3fv(parsedRow.csvdata());
                    glEnd();
                }
            }
        }
    };
}
</code>```

I am getting error in glVertex3fv(parsedRow.csvdata());
Error is E0135 class "std::vector<float, std::allocator<float>>" has no member "csvdata"   Main

答:
There is non member csvdata().

I guess you want data() instead?

Body:
I am making an OpenGL program using C++ on Visual Studio. I have read the CSV file data for the coordinates using a code available on Stackoverflow OpenGL - Plotting Points from external file. But now I am getting errors on the object with ifstream. You can consult the link to get a better understanding (OpenGL - Plotting Points from external file).

// CSV File Loader and 3D Rendering Class

#include "CSV.h"
#include <iostream>
#include<string>
#include<sstream>
#include <fstream>
#include <vector>
#include "C:\Users\srcco\Desktop\Track Viewer\glut-3.7\include\GL\glut.h"
using namespace std;
CSV::CSV(string Fname) {
    class CSV {
    public:
        CSV() {
            ifstream csvdata("demo.csv");
            string line;
            while (getline(csvdata,line))
            {
                stringstream lineStream(line);
                string cell;
                vector<float> parsedRow;
                while (std::getline(lineStream, cell, ','))
                {
                    parsedRow.push_back(stof(cell));
                }
                if (parsedRow.size() == 3)
                {
                    glBegin(GL_POINTS);
                    glColor3f(0.0f, 1.0f, 1.0f);
                    glVertex3fv(parsedRow.csvdata());
                    glEnd();
                }
            }
        }
    };
}

I am getting error in glVertex3fv(parsedRow.csvdata());
Error is E0135 class "std::vector<float, std::allocator<float>>" has no member "csvdata"   Main


问:
Accessing local files via jupyter notebook on remote AWS server
I just setup ubuntu deep learning instance on AWS and would like to run my existing jupyter notebook there. Im working on creating CNN model on new images dataset.
Im stuck at reading my huge image files on my local drive from this remote server.
How can i read the files/folders on my local drive via this jupyter notebook on the instance?
Is there other solution than uploading the dataset?</p>

答: Im not familiar yet with awscli, instead i transfer my dataset to the instance using winSCP. So far, it worked well. But i do appreciate for any advice, suggestion for any other methods that can be used besides winscp.</p>


问:
Entity Framework - Cannot convert lambda expression to type 'string' because it is not a delegate type
I am using Entity Framework in my C# based code.  I am running into an unexpected weirdness and am looking for suggestions.

Case 1, 2, 3, 4...
Projects:

RivWorks.dll

RivWorks.Service.dll

RivWorks.Alpha.dll

Samples (all of these work):

RivWorks.Alpha.dll:

```<code>public static bool EndNegotitation(long ProductID)
{
    var product = (from a in _dbFeed.AutoWithImage
                   where a.AutoID == ProductID select a).FirstOrDefault();
...
}
</code>```

RivWorks.Service.dll

```<code>public static RivWorks.Model.NegotiationAutos.AutoWithImage
    GetProductById(long productId)
{
    var myProduct = from a in _dbFeed.AutoWithImage
                    where a.AutoID == productId select a;

    return myProduct.FirstOrDefault();
}
public static List<RivWorks.Model.NegotiationAutos.AutoWithImage>
    GetProductByCompany(Guid companyId)
{
    var myProduct = from a in _dbFeed.AutoWithImage
                    where a.CompanyID == companyId select a;

    return myProduct.ToList();
}
</code>```

etc

Case "weirdness":

RivWorks.Web.Service.dll (WCF project)

Contains the same references as the other projects.

```<code>public NegotiateSetup GetSetup(string method, string jsonInput)
{
    ...
    long.TryParse(ProductID, out result);
    var product = (from a in _dbFeed.AutoWithImage
                   where a.AutoID == result select a).FirstOrDefault();
    ...
}
</code>```

I am getting this compile time error (the word "where" is highlighted in my editor):

Cannot convert lambda expression to type 'string' because it is not a delegate type

Any ideas what would cause this?

答:
If you got this issue from the auto-generated database context class that was generated after reverse engineer EF, then you have to check your Microsoft.EntityFrameworkCore.SqlServer version. some versions are not supported entity.HasIndex(). Update your Nuget package of

Microsoft.EntityFrameworkCore.SqlServer to 5.0.8

Microsoft.EntityFrameworkCore.Tools to 5.0.8

Body:
I am using Entity Framework in my C# based code.  I am running into an unexpected weirdness and am looking for suggestions.

Case 1, 2, 3, 4...
Projects:

RivWorks.dll

RivWorks.Service.dll

RivWorks.Alpha.dll

Samples (all of these work):

RivWorks.Alpha.dll:

public static bool EndNegotitation(long ProductID)
{
    var product = (from a in _dbFeed.AutoWithImage
                   where a.AutoID == ProductID select a).FirstOrDefault();
...
}

RivWorks.Service.dll

public static RivWorks.Model.NegotiationAutos.AutoWithImage
    GetProductById(long productId)
{
    var myProduct = from a in _dbFeed.AutoWithImage
                    where a.AutoID == productId select a;

    return myProduct.FirstOrDefault();
}
public static List<RivWorks.Model.NegotiationAutos.AutoWithImage>
    GetProductByCompany(Guid companyId)
{
    var myProduct = from a in _dbFeed.AutoWithImage
                    where a.CompanyID == companyId select a;

    return myProduct.ToList();
}

etc

Case "weirdness":

RivWorks.Web.Service.dll (WCF project)

Contains the same references as the other projects.

public NegotiateSetup GetSetup(string method, string jsonInput)
{
    ...
    long.TryParse(ProductID, out result);
    var product = (from a in _dbFeed.AutoWithImage
                   where a.AutoID == result select a).FirstOrDefault();
    ...
}

I am getting this compile time error (the word "where" is highlighted in my editor):

Cannot convert lambda expression to type 'string' because it is not a delegate type

Any ideas what would cause this?


答:
you in you HTML you have to change it like this:

  {{  record.fields?.name  }}

```

and there is a problem with your observable type, this is correct: public communes$: Observable<any>;

because the response is an object and not an array of objects

Title: Get value Inside Observable in a nested Array of objects

Body:
I consume an Api.

I get well data but I'm completely  lost to display informations.

I made a Stackblitz to explain the problem.

I just want to access to 'records' => 'fields' => 'name' values of each 'records'.

{
    "nhits": 38,
    "parameters": {
        "dataset": "communes-de-la-province-de-namur",
        "rows": 1,
        "start": 0,
        "format": "json",
        "timezone": "UTC"
    },
    "records": [
        {
            "datasetid": "communes-de-la-province-de-namur",
            "recordid": "5f50799324d15038c9708e48c6a32c907922d00a",
            "fields": {
                "nsi": "93088",
                "geo_shape": {
                    "coordinates": [
                        [
                            [
                                4.516330595797285,
                                50.315159737224334
                            ],
                            [
                                4.516580864937829,
                                50.31404658899336
                            ],
                            [
                                4.516687125130969,
                                50.313425631678086
                            ],
                            [
                                4.516773208694129,
                                50.312758726847896
                            ],
                            [
                                4.51683388309065,
                                50.31199699971867
                            ],
                            [
                                4.511136348481946,
                                50.28826153347796
                            ],
                            [
                                4.5113662847970755,
                                50.28794282863673
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "geo_point_2d": [
                    50.26709679846407,
                    4.433557385138468
                ],
                "name": "Walcourt"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    4.433557385138468,
                    50.26709679846407
                ]
            },
            "record_timestamp": "2019-02-13T15:00:55.334000+00:00"
        }
    ]
}

I'm very new to Angular, so any suggestions is helpfull.

Thank you!

Body:
you in you HTML you have to change it like this:

<div *ngFor="let record of (communes$ | async).records">
  {{  record.fields?.name  }}
</div>

and there is a problem with your observable type, this is correct: public communes$: Observable<any>;

because the response is an object and not an array of objects


问:
How to download image using jQuery AJAX in Laravel 8
I am trying to download images using jQuery/AJAX in Laravel 8. I get the image in the response, but it is not downloading. Please help me to download the image.

Controller

```<code>public function senddata(Request $req)
{
    $stamp = new Stamp();
    $stamp->company_name = $req->company_name;
    $stamp->reg_no = $req->reg_no;
    $stamp->color = $req->color;
    $stamp->fullname = $req->fullname;
    $stamp->email = $req->email;
    $stamp->save();
    // return Storage::download(public_path('images/Screenshot_1.png'));
    $filepath = public_path('images/')."Screenshot_1.png";
        return Response::download($filepath);
}
</code>```

jQuery/AJAX Code

```<code>$('#acceptform').submit(function () {
    if ($('#acceptform').valid()) {
        var company_name = $('#company_name').val();
        var reg_no = $('#reg_number').val();
        var color = $('input[name="stamp_color"]:checked').val();
        var fullname = $('#fullname').val();
        var email = $('#email').val();

        $.ajax({
            type: 'POST',
            url: "{{ route('senddata') }}",
            data: {company_name: company_name, reg_no: reg_no,
                color: color, fullname: fullname, email: email},
            xhrFields: {
                responseType: 'blob'
            },
            success: function (res) {
                const data = res;
                const link = document.createElement('a');
                link.setAttribute('href', data);
                link.setAttribute('download', 'Screenshot_1.png');
                link.click();
            }
        });
    }
});
</code>```

答: Why would you use Ajax to download a file, why no simple get request with file id?</p>

Body:
I am trying to download images using jQuery/AJAX in Laravel 8. I get the image in the response, but it is not downloading. Please help me to download the image.

Controller

public function senddata(Request $req)
{
    $stamp = new Stamp();
    $stamp->company_name = $req->company_name;
    $stamp->reg_no = $req->reg_no;
    $stamp->color = $req->color;
    $stamp->fullname = $req->fullname;
    $stamp->email = $req->email;
    $stamp->save();
    // return Storage::download(public_path('images/Screenshot_1.png'));
    $filepath = public_path('images/')."Screenshot_1.png";
        return Response::download($filepath);
}

jQuery/AJAX Code

$('#acceptform').submit(function () {
    if ($('#acceptform').valid()) {
        var company_name = $('#company_name').val();
        var reg_no = $('#reg_number').val();
        var color = $('input[name="stamp_color"]:checked').val();
        var fullname = $('#fullname').val();
        var email = $('#email').val();

        $.ajax({
            type: 'POST',
            url: "{{ route('senddata') }}",
            data: {company_name: company_name, reg_no: reg_no,
                color: color, fullname: fullname, email: email},
            xhrFields: {
                responseType: 'blob'
            },
            success: function (res) {
                const data = res;
                const link = document.createElement('a');
                link.setAttribute('href', data);
                link.setAttribute('download', 'Screenshot_1.png');
                link.click();
            }
        });
    }
});


问:
str.contains function AND does not contain
I'm iterating over all values in columns that contain 'Applicant Age' and adding them into a new column.

```<code>for i in range(17):
    rule_col = f'rule{i}_evaluationstring'
    matches = df_merged[rule_col].astype(str).str.contains('Applicant Age', na=False)
    df_merged.loc[matches, 'applicant_age'] = df_merged.loc[matches, rule_col]
</code>```

This works properly, but there are some entries that have an 'Applicant Age = 200' that I would like to omit.

How do I add an additional function that omits all values that contain 200 while keeping the functionality of the above?

答:
You can use the bitwise operators & (and) and ~ (not) in combination.
The syntax looks like df.loc[(condition_A) & (~condition_B)]

An example relevant for your question would be:

```<code>df = df_merged

selected = df.loc[
    (df[rule_col].astype(str).str.contains('Applicant Age', na=False)) &
    (~df[rule_col].astype(str).str.contains('200', na=False))
]
</code>```

Body:
I'm iterating over all values in columns that contain 'Applicant Age' and adding them into a new column.

for i in range(17):
    rule_col = f'rule{i}_evaluationstring'
    matches = df_merged[rule_col].astype(str).str.contains('Applicant Age', na=False)
    df_merged.loc[matches, 'applicant_age'] = df_merged.loc[matches, rule_col]

This works properly, but there are some entries that have an 'Applicant Age = 200' that I would like to omit.

How do I add an additional function that omits all values that contain 200 while keeping the functionality of the above?

Body:
You can use the bitwise operators & (and) and ~ (not) in combination.
The syntax looks like df.loc[(condition_A) & (~condition_B)]

An example relevant for your question would be:

df = df_merged

selected = df.loc[
    (df[rule_col].astype(str).str.contains('Applicant Age', na=False)) &
    (~df[rule_col].astype(str).str.contains('200', na=False))
]


问:
getting the third highest salary in MYSQL (your SQL syntax)
I want to find the third highest salary in tables in MySQl

```<code>select *
from
(
    select ename, sal, dense_rank() over(order by sal desc) rank
    from emp
)
 where rank =3;
</code>```

but I get this error message

You have an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near '(order by salary desc)

答:
In SQL every derived table requires an alias so it can be uniquely identified, so</p>
```<code>select *
from
(
    select ename, sal, dense_rank() over(order by sal desc) `rank`
    from emp
) as t
where `rank` = 3;
</code>```

Body:
I want to find the third highest salary in tables in MySQl

select *
from
(
    select ename, sal, dense_rank() over(order by sal desc) rank
    from emp
)
 where rank =3;

but I get this error message

You have an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near '(order by salary desc)

Body:
In SQL every derived table requires an alias so it can be uniquely identified, so

select *
from
(
    select ename, sal, dense_rank() over(order by sal desc) `rank`
    from emp
) as t
where `rank` = 3;


问:
Type mismatch when serializing data class
I'm following this example to serialize a data class. When I do so, I get this build error:

```<code>Type mismatch: inferred type is Data but SerializationStrategy<TypeVariable(T)> was expected
</code>```

Here's my code:

```<code>import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable

@Serializable
data class Data(val a: Int, val str: String = "str")

fun main() {
    println(Json.encodeToString(Data(42)))
}
</code>```

Since I am using the @Serializable annotation, shouldn't I have the right data type? How can I serialize the data class?

答:
Please check the imports.
The ones below come from kotlin serialization and needs just the string and the object respectively.</p>
```<code>import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
</code>```

Body:
I'm following this example to serialize a data class. When I do so, I get this build error:

Type mismatch: inferred type is Data but SerializationStrategy<TypeVariable(T)> was expected

Here's my code:

import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable

@Serializable
data class Data(val a: Int, val str: String = "str")

fun main() {
    println(Json.encodeToString(Data(42)))
}

Since I am using the @Serializable annotation, shouldn't I have the right data type? How can I serialize the data class?

Body:
Please check the imports.
The ones below come from kotlin serialization and needs just the string and the object respectively.

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString


问:
How to manage Camel K routes via API(or other alternative ways)?
I have a Camel K application which contains multiple routes(each route is a Java file). my goal is to manage the routes status, for instance start certain routes and stop other running routes.

Currently I start and close the routes manually using kamel run XXX.java --pod-template pod_template.yaml --property=file:logging.properties ..., I am wondering what is the best way to achieve managing routes status via API?

My goal is achieving below using API:

start a route

stop a route

list available routes

I have asked the question under apache/camel-k but still confused about the Integration CRD mentioned in the answer.

I have found that Camel K has API Camel K API unfortunately I haven't figure out how to call the APIs if it is possible?

Can someone share knowledge and help me on this? Thanks!

答:
You an use the kamel CLI to start and list the Integrations available, ie:

```<code>$ kamel run Sample.java
Integration "sample" created
$ kamel get
NAME    PHASE   KIT
sample  Running default/kit-c82emh1c11s7ki7ijq0g
</code>```

The above will use Kubernetes Custom Resource to create an Integration and list the Integration accordingly

There is no direct way to pause/stop/resume a route. The best thing I can suggest is to have a route per Integration and stop it via kamel delete CLI or equivalent Kubernetes API

Body:
You an use the kamel CLI to start and list the Integrations available, ie:

$ kamel run Sample.java
Integration "sample" created
$ kamel get
NAME    PHASE   KIT
sample  Running default/kit-c82emh1c11s7ki7ijq0g

The above will use Kubernetes Custom Resource to create an Integration and list the Integration accordingly

There is no direct way to pause/stop/resume a route. The best thing I can suggest is to have a route per Integration and stop it via kamel delete CLI or equivalent Kubernetes API


问:
Removing sequential repeating items from List in Kotlin?
I'm looking for a way in Kotlin to prevent repeating items in a list but still preserve the order. For example

```<code>  val list = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
        ObjectMock(4,"a"), ObjectMock(4,"c"), ObjectMock(4,"c"), ObjectMock(1,"a")
        , ObjectMock(1,"c"), ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
        , ObjectMock(2,"b") )
</code>```

should become

```<code>result = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
            ObjectMock(4,"a"), ObjectMock(1,"a") , ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
            , ObjectMock(2,"b") )
</code>```

I'm using a for loop and check next item then add it to different list but Is there a more elegant way to do this?

答:
this is another way to do it</p>
```<code>val list = listOf(1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4 )
val result = list.fold(emptyList<Int>()){acc, i ->
    if (acc.lastOrNull() != i) acc + i else acc
}
</code>```

Body:
I'm looking for a way in Kotlin to prevent repeating items in a list but still preserve the order. For example

  val list = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
        ObjectMock(4,"a"), ObjectMock(4,"c"), ObjectMock(4,"c"), ObjectMock(1,"a")
        , ObjectMock(1,"c"), ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
        , ObjectMock(2,"b") )

should become

result = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
            ObjectMock(4,"a"), ObjectMock(1,"a") , ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
            , ObjectMock(2,"b") )

I'm using a for loop and check next item then add it to different list but Is there a more elegant way to do this?

Body:
this is another way to do it

val list = listOf(1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4 )
val result = list.fold(emptyList<Int>()){acc, i ->
    if (acc.lastOrNull() != i) acc + i else acc
}


问:
App not launching on the simulator
I am unable to install my app on the simulator. I always get the following error on the console,

"Failed to launch simulated application: Unknown error."

Please help !

答:
Check info of your project whether Simulator is selected or Device. If it is Device change it to Simulator. Also check the base SDK version.
I too had the same problem, fixed it with above checks. :)</p>

Title: App not launching on the simulator