问:
Reverse a string without strtok in C
Working on a program that uses RPN (Reverse Polish Notation).

I have a function that reverses all the words of string without using strtok or triggering printf (unlike all the solutions found online and here).

The function actually works partially as it prints all the words of a given string except the last one and I need help figuring out what's going on.

```<code>char *extract(char s[]) {
    if (s[0] == '\0')
        return NULL;
    int i = 0;
    char *p = NULL;
    while (s[i] != '\0') {
        if (s[i] == ' ')
            p = s + i;
        i++;
    }
    if (p != NULL) {
        *p = '\0';
        return p + 1;
    }
}

</code>```

And then it's called in main like this:

```<code>char s[MAX] = "5 60 +";
while(s != NULL){
    printf("%s\n", extract(s));
}
</code>```

The output is + 60 with the cursor endessly waiting for something
but the expected output should be + 60 5

答:
A standard approach is to reverse each word within a string and then to reverse the whole string.

Here you are.

```<code>#include <stdio.h>
#include <string.h>

static char * reverse( char *s, size_t n )
{
    for ( size_t i = 0; i < n / 2; i++ )
    {
        char c = s[ i ];
        s[ i ] = s[ n - i - 1 ];
        s[ n - i - 1 ] = c;
    }

    return s;
}

char * reverse_by_words( char *s )
{
    const char *delim = " \t";

    char *p = s;

    while ( *p )
    {
        p += strspn( p, delim );

        if ( *p )
        {
            char *q = p;

            p += strcspn( p, delim );

            reverse( q, p - q );
        }
    }

    return reverse( s, p - s );
}

int main(void)
{
    char s[] = "5 60 +";

    puts( s );

    puts( reverse_by_words( s ) );

    return 0;
}
</code>```

The program output is

```<code>5 60 +
+ 60 5
</code>```

If you want to keep leading and trailing spaces as they were in the original string then the functions can look the following way

```<code>#include <stdio.h>
#include <string.h>

static char *reverse( char *s, size_t n )
{
    for ( size_t i = 0; i < n / 2; i++ )
    {
        char c = s[i];
        s[i] = s[n - i -1 ];
        s[n - i - 1] = c;
    }

    return s;
}

char * reverse_by_words( char *s )
{
    const char *delim = " \t";

    char *first = s, *last = s;

    for ( char *p = s;  *p; )
    {
        p += strspn( p, delim );

        if ( last == s ) first = last = p;

        if ( *p )
        {
            char *q = p;

            p += strcspn( p, delim );

            last = p;

            reverse( q, p - q );
        }
    }

    reverse( first, last - first );

    return s;
}

int main(void)
{
    char s[] = "\t\t\t5 60 +";

    printf( "\"%s\"\n", s );

    printf( "\"%s\"\n", reverse_by_words( s ) );

    return 0;
}
</code>```

The program output is

```<code>"           5 60 +"
"           + 60 5"
</code>```

Title: Reverse a string without strtok in C

Body:
Working on a program that uses RPN (Reverse Polish Notation).

I have a function that reverses all the words of string without using strtok or triggering printf (unlike all the solutions found online and here).

The function actually works partially as it prints all the words of a given string except the last one and I need help figuring out what's going on.

char *extract(char s[]) {
    if (s[0] == '\0')
        return NULL;
    int i = 0;
    char *p = NULL;
    while (s[i] != '\0') {
        if (s[i] == ' ')
            p = s + i;
        i++;
    }
    if (p != NULL) {
        *p = '\0';
        return p + 1;
    }
}

And then it's called in main like this:

char s[MAX] = "5 60 +";
while(s != NULL){
    printf("%s\n", extract(s));
}

The output is + 60 with the cursor endessly waiting for something
but the expected output should be + 60 5

Body:
A standard approach is to reverse each word within a string and then to reverse the whole string.

Here you are.

#include <stdio.h>
#include <string.h>

static char * reverse( char *s, size_t n )
{
    for ( size_t i = 0; i < n / 2; i++ )
    {
        char c = s[ i ];
        s[ i ] = s[ n - i - 1 ];
        s[ n - i - 1 ] = c;
    }

    return s;
}

char * reverse_by_words( char *s )
{
    const char *delim = " \t";

    char *p = s;

    while ( *p )
    {
        p += strspn( p, delim );

        if ( *p )
        {
            char *q = p;

            p += strcspn( p, delim );

            reverse( q, p - q );
        }
    }

    return reverse( s, p - s );
}

int main(void)
{
    char s[] = "5 60 +";

    puts( s );

    puts( reverse_by_words( s ) );

    return 0;
}

The program output is

5 60 +
+ 60 5

If you want to keep leading and trailing spaces as they were in the original string then the functions can look the following way

#include <stdio.h>
#include <string.h>

static char *reverse( char *s, size_t n )
{
    for ( size_t i = 0; i < n / 2; i++ )
    {
        char c = s[i];
        s[i] = s[n - i -1 ];
        s[n - i - 1] = c;
    }

    return s;
}

char * reverse_by_words( char *s )
{
    const char *delim = " \t";

    char *first = s, *last = s;

    for ( char *p = s;  *p; )
    {
        p += strspn( p, delim );

        if ( last == s ) first = last = p;

        if ( *p )
        {
            char *q = p;

            p += strcspn( p, delim );

            last = p;

            reverse( q, p - q );
        }
    }

    reverse( first, last - first );

    return s;
}

int main(void)
{
    char s[] = "\t\t\t5 60 +";

    printf( "\"%s\"\n", s );

    printf( "\"%s\"\n", reverse_by_words( s ) );

    return 0;
}

The program output is

"           5 60 +"
"           + 60 5"


来源: stackexchange

问:
Comparing doubles to double literals?

Possible Duplicate:

  How should I do floating point comparison?

Is it not recommended to compare for equality a double and a double literal in C++, because I guess it is compiler dependent?

To be more precise it is not OK to compare a double which is hard-coded (a literal in the source code) and a double which should be computed, as the last number of the resultant of the calculation can vary from one compiler to another. Is this not standardized?

I heard this is mentioned in Knuth's TeXbook, is that right?

If this is all true, what is the solution?

答:
You've misunderstood the advice a bit. The point is that floating-point computations aren't exact. Rounding errors occur, and precision is gradually lost. Take something as simple as 1.0/10.0. The result should be 0.1, but it isn't, because 0.1 cannot be represented exactly in floating-point format. So the actual result will be slightly different. The same is true for countless other operations, so the point has nothing to do with const doubles. It has to do with not expecting the result to be exact. If you perform some computation where the result should be 1.0, then you should not test it for equality against 1.0, because rounding errors might mean that it actually came out 0.9999999997 instead.

So the usual solution is to test if the result is sufficiently close to 1.0. If it is close, then we assume "it's good enough", and act as if the result had been 1.0.

The bottom line is that strict equality is rarely used for floating-point values. Instead, you should test if the difference between the two values is less than some small value (typically called the epsilon)

ContentLicense: CC BY-SA 3.0

Title: Comparing doubles to double literals?


问:
Replace All Special Characters Expect Language Specific
Remove everything from the string expect the language-specific special signs and characters etc.
I've been using this method:

```<code>$string = preg_replace('/[^A-Za-z0-9\-]/', ' ', $string);
</code>```

Now it's obvious that it's not working with the following languages:
1. Arabic
2. Hindi
3. With Spanish characters.
And all the languages outside English.
Now my question is simple, what will be the best way to remove all the special characters from the string.

答:
Try this:

```<code>$string = "abcßöäü #.,}* हिंदी عربى";
$string = preg_replace('/[^\w0-9 \-]/u', '', $string);

var_dump($string);
//string(28) "abcßöäü हद عربى"
</code>```

Whether \w works depends on the system configuration.

ContentLicense: CC BY-SA 4.0

Body:
Remove everything from the string expect the language-specific special signs and characters etc.
I've been using this method:

$string = preg_replace('/[^A-Za-z0-9\-]/', ' ', $string);

Now it's obvious that it's not working with the following languages:
1. Arabic
2. Hindi
3. With Spanish characters.
And all the languages outside English.
Now my question is simple, what will be the best way to remove all the special characters from the string.

Body:
Try this:

$string = "abcßöäü #.,}* हिंदी عربى";
$string = preg_replace('/[^\w0-9 \-]/u', '', $string);

var_dump($string);
//string(28) "abcßöäü हद عربى"

Whether \w works depends on the system configuration.


问:
Convert argb to string
Which method allows convert ARGB to string as 'int, int, int'? Example. The $Main background color is set as a string '0, 100, 200'. Return $Main.BackColor gives ARGB but not string '0, 100, 200':

```<code>$Main  = [System.Windows.Forms.Form] @{
    BackColor = '0, 100, 200'
}

$Main.BackColor
--------------
R             : 0
G             : 100
B             : 200
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff0064c8
</code>```

The To.String() method returns the result Color [A=255, R=0, G=100, B=200]
. This is not what is expected.

At the moment I am doing this:

```<code> ('R', 'G', 'B').ForEach({ $Main.BackColor.$_ }) -join ', '

--------------
0, 100, 200
</code>```

However, I hope that there are special methods for converting as ARGB to string, as string to ARGB. What are these methods? Thanks

答:
However, I hope that there are special methods for converting as argb to string, as string to argb. What are these methods?

You'd think so, but to my knowledge there isn't a builtin two-way convertion for this, unfortunately.

Here are a couple of things you can do instead:

Create your own ConvertFrom-Color function:

```<code>function ConvertFrom-Color
{
    param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [System.Drawing.Color[]]$InputColor
    )

    process {
        foreach($color in $InputColor){
            $color.R,$color.G,$color.B -join ', '
        }
    }
}
</code>```

And use when needed:

```<code>PS C:\> $colorString = $Main.BackColor |ConvertFrom-Color
PS C:\> $colorString
0, 100, 200
</code>```

Use an [int]

An ARGB color consists of 4 1-byte channels, which fits perfectly into a 32-bit integer. If you need to communicate a distinct color using a single argument, this is already supported:

```<code>PS C:\> $color = [System.Drawing.Color]'0,100,100'
PS C:\> $color.ToArgb()
-16751516
PS C:\> $argbValue = $color.ToArgb()
PS C:\> [System.Drawing.Color]::FromArgb($argbValue)

R             : 0
G             : 100
B             : 100
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff006464
</code>```

Just like with your initial string representation, it's worth highlighting that converting from the [int] representation works both with explicit casts and implicit conversions when assigning to typed properties:

```<code>$argbValue = -16751516
# This works just fine
[System.Drawing.Color]$argbValue
# As does this
[System.Windows.Forms.Form]@{ BackColor = $argbValue }
</code>```

Override Color.ToString()

Since you're interested in changing the behavior of the default string representation of System.Drawing.Color, you might as well override the ToString() method implementation:

```<code>Update-TypeData -TypeName System.Drawing.Color -MemberType ScriptMethod -MemberName ToString -Value {
    $this.psobject.Properties['R','G','B'].Value -join ', '
} -Force
</code>```

Now all instances of [System.Drawing.Color] will use your custom ToString() method when converted to a string:

```<code>PS C:\> "$($Main.BackColor)"
0, 100, 200
</code>```

Title: Convert argb to string

Body:
Which method allows convert ARGB to string as 'int, int, int'? Example. The $Main background color is set as a string '0, 100, 200'. Return $Main.BackColor gives ARGB but not string '0, 100, 200':

$Main  = [System.Windows.Forms.Form] @{
    BackColor = '0, 100, 200'
}

$Main.BackColor
--------------
R             : 0
G             : 100
B             : 200
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff0064c8

The To.String() method returns the result Color [A=255, R=0, G=100, B=200]
. This is not what is expected.

At the moment I am doing this:

 ('R', 'G', 'B').ForEach({ $Main.BackColor.$_ }) -join ', '

--------------
0, 100, 200

However, I hope that there are special methods for converting as ARGB to string, as string to ARGB. What are these methods? Thanks

Body:
However, I hope that there are special methods for converting as argb to string, as string to argb. What are these methods?

You'd think so, but to my knowledge there isn't a builtin two-way convertion for this, unfortunately.

Here are a couple of things you can do instead:

Create your own ConvertFrom-Color function:

function ConvertFrom-Color
{
    param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [System.Drawing.Color[]]$InputColor
    )

    process {
        foreach($color in $InputColor){
            $color.R,$color.G,$color.B -join ', '
        }
    }
}

And use when needed:

PS C:\> $colorString = $Main.BackColor |ConvertFrom-Color
PS C:\> $colorString
0, 100, 200

Use an [int]

An ARGB color consists of 4 1-byte channels, which fits perfectly into a 32-bit integer. If you need to communicate a distinct color using a single argument, this is already supported:

PS C:\> $color = [System.Drawing.Color]'0,100,100'
PS C:\> $color.ToArgb()
-16751516
PS C:\> $argbValue = $color.ToArgb()
PS C:\> [System.Drawing.Color]::FromArgb($argbValue)

R             : 0
G             : 100
B             : 100
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff006464

Just like with your initial string representation, it's worth highlighting that converting from the [int] representation works both with explicit casts and implicit conversions when assigning to typed properties:

$argbValue = -16751516
# This works just fine
[System.Drawing.Color]$argbValue
# As does this
[System.Windows.Forms.Form]@{ BackColor = $argbValue }

Override Color.ToString()

Since you're interested in changing the behavior of the default string representation of System.Drawing.Color, you might as well override the ToString() method implementation:

Update-TypeData -TypeName System.Drawing.Color -MemberType ScriptMethod -MemberName ToString -Value {
    $this.psobject.Properties['R','G','B'].Value -join ', '
} -Force

Now all instances of [System.Drawing.Color] will use your custom ToString() method when converted to a string:

PS C:\> "$($Main.BackColor)"
0, 100, 200


问:
IIS 8.5 low minBytesPerSecond not working against slow HTTP POST
I have an ASP.NET site running under IIS 8.5 on Windows 2012 R2.

I'm trying to use the MinBytesPerSecond configuration setting (in applicationHost\WebLimits) as part of a strategy to mitigate slow HTTP POST attacks but can't seem to get IIS to respect the value. I've tried with default 240 bytes/sec plus much higher values.

I'm using OWASP/ProactiveRISK's SwitchBlade to trickle a POST body at 1 byte/sec to the server but cannot get it to drop the connection.

The use of MinBytesPerSecond is recommended in a number of articles on the web relating to slow DOS attacks and so I am surprised I am having difficulty. I have restarted IIS after each setting change just in case.

Could this setting be monitored by another process which might not be running?

Any ideas, things to consider or alternatives greatly appreciated.

EDIT:

Just noted this in the IIS config reference here, minBytesPerSecond...

Specifies the minimum throughput rate, in bytes, that HTTP.sys enforces when it sends a response to the client. The minBytesPerSecond attribute prevents malicious or malfunctioning software clients from using resources by holding a connection open with minimal data. If the throughput rate is lower than the minBytesPerSecond setting, the connection is terminated.

Does this mean that this setting only applies to the rate at which the response is returned i.e. could only be used against slow reads - does anyone have any knowledge or experience of minBytesPerSecond working for them?

Thanks.

答:
I was brought here by the exact same issue. Your last paragraph nails it. I've run a test using Postman in conjunction with NetLimiter to simulate both slow upload and slow download rates. I can confirm that the minBytesPerSecond setting applies to sending data back to the client i.e. the response and not the request.

I can only imagine this setting has been widely misinterpreted in relation to protecting against slow HTTP post attacks, as I can't see how this would be of any use in mitigating such attacks. To be fair, the documentation is misleading in my opinion.


问:
How would I add a new ViewController if and only if the screen is rotated into landscape mode in swift
I am starting on first project in swift and I need to add a new ViewController when the screen is rotated in landscape mode. And if rotated back to portrait mode it will return to original screen. I am a  beginner in swift so please make explanation as clear as possible. Thank you in advance!</p>

答:
It seems that you should definitely check out SplitViewControllers. It allows you (for iPads and iPhone Pluses) have sort of a split screen with two views simultaneously (for other devices it will be just like navigation controller).

Below couple of screenshots of a dummy SplitView I just did

This is in a Landscape mode

This is in a Portrait mode

You can also make it collapsable by tracking the orientation of the device or gestures. By default, you can show or collapse detail view by left/right swipe gesture.

Here you can check out a decent tutorial on SplitViewController

Good luck!


问:
Can I specify my explicit type comparator inline?
So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ.  Sometimes, I need to compare user-defined types that don't have a built-in comparison operator.  In many cases, the comparison is really simple -- something like foo1.key ?= foo2.key.  Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions?  Something like:

```<code>var f1 = ...,
    f2 = ...;
var f3 = f1.Except(
           f2, new IEqualityComparer(
             (Foo a, Foo b) => a.key.CompareTo(b.key)
           ) );
</code>```

I'm pretty sure the above doesn't actually work.  I just don't want to have to make something as "heavy" as a whole class just to tell the program how to compare apples to apples.

答:
So I know this is a workaround to your question, but when I find that I've run into the situation you have here (Combining a list and filtering duplicates), and Distinct needs an IEquityComparer that I don't have, I usually go with a Concat -> Group -> Select.

Original

```<code>var f1 = ...,
    f2 = ...;
var f3 = f1.Except(
           f2, new IEqualityComparer(
             (Foo a, Foo b) => a.key.CompareTo(b.key)
           ) );
</code>```

New

```<code>var f1 = ...,
    f2 = ...;
var distinctF = f1
    .Concat(f2)                       // Combine the lists
    .GroupBy(x => x.key)              // Group them up by our equity comparison key
    .Select(x => x.FirstOrDefault()); // Just grab one of them.
</code>```

Note that in the GroupBy() you have the opportunity to add logic to create hybrid keys like:

```<code>.GroupBy(f => new Uri(f.Url).PathAndQuery)
</code>```

As well as in the Select() if you want to want to specify which list the resulting item comes from you can say:

```<code>.Select(x => x.FirstOrDefault(y => f1.Contains(y))
</code>```

Hope that helps!

OwnerDisplayName: Coderer

ContentLicense: CC BY-SA 2.5

Body:
So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ.  Sometimes, I need to compare user-defined types that don't have a built-in comparison operator.  In many cases, the comparison is really simple -- something like foo1.key ?= foo2.key.  Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions?  Something like:

var f1 = ...,
    f2 = ...;
var f3 = f1.Except(
           f2, new IEqualityComparer(
             (Foo a, Foo b) => a.key.CompareTo(b.key)
           ) );

I'm pretty sure the above doesn't actually work.  I just don't want to have to make something as "heavy" as a whole class just to tell the program how to compare apples to apples.

Body:
So I know this is a workaround to your question, but when I find that I've run into the situation you have here (Combining a list and filtering duplicates), and Distinct needs an IEquityComparer that I don't have, I usually go with a Concat -> Group -> Select.

Original

var f1 = ...,
    f2 = ...;
var f3 = f1.Except(
           f2, new IEqualityComparer(
             (Foo a, Foo b) => a.key.CompareTo(b.key)
           ) );

New

var f1 = ...,
    f2 = ...;
var distinctF = f1
    .Concat(f2)                       // Combine the lists
    .GroupBy(x => x.key)              // Group them up by our equity comparison key
    .Select(x => x.FirstOrDefault()); // Just grab one of them.

Note that in the GroupBy() you have the opportunity to add logic to create hybrid keys like:

.GroupBy(f => new Uri(f.Url).PathAndQuery)

As well as in the Select() if you want to want to specify which list the resulting item comes from you can say:

.Select(x => x.FirstOrDefault(y => f1.Contains(y))

Hope that helps!


问:
Focusing a Tab after it has been reloaded via window.open?
In my webapp I work with new Tabs I open with window.open. Sometimes, a tab with the target-name is already open in the background and the window.open(..., "sametarget") only reloads it, which is fine - but the Tab stays in the background after reloading, which is not. Is there any way (JavaScript? window.open parameter?) to get it to the foreground after reloading? Or is this prohibited by browser security?
I am trying this in IE7 / IE8.</p>

答:
Does window.focus() solve your problem?

EDIT

Possibly not: Possible to set tab focus in IE7 from JavaScript


问:
In Camunda , What is the correct way of optimised coding among two options?

Retrieving userTasks first and then from task, retrive the processInstanceId.

First retrieving ProcessInstances and then iterate it with a loop and find usertasks in each process instance.

Please give reason too.

答:
If you want to build a task list you should use the task queries, as you can do the right queries and filters there easily. Process instance id's are part of the result.
But it would indeed be interesting to understand the use case, what exactly you need the process instance id for.</p>


问:
Custom.css isnt overwriting bootstrap.min.css
When I include css/bootstrap.min.css it overwrites some elements of my site such as 'a' tags, my .nav bar and font used on site.
Load order:

```<code><link href="css/bootstrap.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="custom.css">
    <link rel = "stylesheet" href = "styl.css" type = "text/css" />
    <link href="css/fontello.css" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com/css?family=Oswald:400,600&display=swap&subset=latin-ext" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</code>```

html :

```<code><div class="wrppr">
        <div class="header">
            <div class="logo">
                <img src="LOGO.png" style="vertical-align:middle;height: 250px; width: 250px; float: left">
                <span style="vertical-align:middle;"></br>Voodoo Doll Ink Studio</span>
                <div style="clear:both"></div>
            </div>
        </div>
        <div class="nav">
            <ul>
                list here
        </div>
        <div class="image">
            <img src="tatofront.jpg" style="opacity: 0.6"/>
        </div>

        <div id="opis">
        <p></p>
        </div>
        <div style="clear:both"></div>

        <div id="option2">
            <a href="#">
                <div id="ig">
                    <i class="icon-instagram"></i>
                </div>
                <div class="txt">Sprawdź naszego Instagrama!</div>
        </a>

    <script src="https://snapwidget.com/js/snapwidget.js"></script>
    <iframe src="https://snapwidget.com/embed/786091" class="snapwidget-widget" allowtransparency="true" frameborder="0" scrolling="no" style="border:none; overflow:hidden;  width:100%; "></iframe>
        </div>
        <div style="clear:both"></div>
            <div id ="option3">
                <div class="logobot">
                    <img src="duda.jpg" style="height: 300px; width: 300px;">
                </div>
                Tu opis o pierciengu i cennik
            </div>
        <div style="clear:both"></div>
        <div id ="option4">
                <div class="logobot">
                    <img src="duda.jpg" style="height: 300px; width: 300px; float:right;">
                </div>
                Tu opis o dreadach i dreadlockach
            </div>
        <div id="option5">
            <div class="logobot">
                <img src="LOGO.png" style="height: 300px; width: 300px;">
        </div>
        <div style="clear:both"></div>
        <div class="footer">
            VOODOO DOLL INK
        </div>

    </div>
</code>```

Mostly everything is good though few things are overwritten:
a tag is unedited,
logo changes text alignement,
text in nav goes lower and its not centered
Elements which are overwritten by bootstrap.min.css in custom.css:

```<code>a {
  color: white;
  text-decoration: none;
  display: block;
}
.logo
{
    font-weight: bold;
    vertical-align:middle;
    width: 1000px;
    font-size: 72px;
    text-align: middle;
    margin-left:auto;
    margin-right:auto;
}
.nav
{
    padding: 10px;
    width:auto;
    border-top: 1px solid rgb(38, 38, 38);
    border-bottom: 1px solid rgb(38, 38, 38);
    top: 0px;
    z-index: 100;
    height: 40px;
    margin-left: auto;
    margin-right: auto;
    font-size: 20px;
    text-align: center;
    background-color:#0a0a0a;
}

</code>```

Its my first time making responsive site || using bootstrap.

答:
If your CSS files are in public/css, you should write:

<link rel="stylesheet" href="css/custom.css">

When you write the href, the start folder is public. Read more about it here.

Also, you are missing an e on the 3rd line:

<link rel="stylesheet" href="styl.css"> -> <link rel="stylesheet" href="style.css">

Body:
When I include css/bootstrap.min.css it overwrites some elements of my site such as 'a' tags, my .nav bar and font used on site.
Load order:

<link href="css/bootstrap.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="custom.css">
    <link rel = "stylesheet" href = "styl.css" type = "text/css" />
    <link href="css/fontello.css" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com/css?family=Oswald:400,600&display=swap&subset=latin-ext" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

html :

Voodoo Doll Ink Studio

                list here

Sprawdź naszego Instagrama!

                Tu opis o pierciengu i cennik

                Tu opis o dreadach i dreadlockach

            VOODOO DOLL INK

Mostly everything is good though few things are overwritten:
a tag is unedited,
logo changes text alignement,
text in nav goes lower and its not centered
Elements which are overwritten by bootstrap.min.css in custom.css:

a {
  color: white;
  text-decoration: none;
  display: block;
}
.logo
{
    font-weight: bold;
    vertical-align:middle;
    width: 1000px;
    font-size: 72px;
    text-align: middle;
    margin-left:auto;
    margin-right:auto;
}
.nav
{
    padding: 10px;
    width:auto;
    border-top: 1px solid rgb(38, 38, 38);
    border-bottom: 1px solid rgb(38, 38, 38);
    top: 0px;
    z-index: 100;
    height: 40px;
    margin-left: auto;
    margin-right: auto;
    font-size: 20px;
    text-align: center;
    background-color:#0a0a0a;
}

Its my first time making responsive site || using bootstrap.


问:
IP address on GKE for egress to GAE appliction is 0.0.0.0, not IPv4 wth Cloud NAT
Long time passed after I posted a related issue.
Link

Now, the issue has changed.
With same procedure to make a cluster and NAT setting, GAE application shows 0.0.0.0 , not IPv6 address.

※GAE application is using a customized-domain.

In case that the egress communication is with on-prem server, the server shows a static IP address, as set by NAT.

Is there any change in a Google Internal networking?
I would like to know how to avoid this issue, when I want an exact static IP address.

```<code>1.create a VPC

gcloud compute networks create ${vpc_name}\
--project=${project_id}\
--bgp-routing-mode=regional\
--subnet-mode=custom
2. create a subnet

gcloud compute networks subnets create ${subnet_name}\
--project=${project_id}\
--region=${region}\
--network=${vpc_name}\
--range=192.168.0.0/16
3. create an external static IP

gcloud compute addresses create ${external_ip_name}\
--region=${region}
4. create a route

gcloud compute routers create ${router_name}\
--region=${region}\
--network=${vpc_name}\
--asn=65001
5. create a nat

gcloud compute routers nats create ${nat_name}\
--region=${region}\
--router=${router_name}\
--nat-external-ip-pool="${external_ip}"\
--nat-all-subnet-ip-ranges

6. make a cluster

gcloud container clusters create ${gke_cluster_name}\
--project=${project_id}\
--zone=${zone}\
--network=${vpc_name}\
--subnetwork=${subnet_name}\
--enable-ip-alias\
--enable-private-nodes\
--master-ipv4-cidr=172.16.0.0/28\
--enable-master-authorized-networks\
--master-authorized-networks=0.0.0.0/0\
--no-enable-legacy-authorization\
--no-enable-basic-auth\
--no-issue-client-certificate\
--num-nodes=${NUM_NODE}\
--enable-autoscaling --max-nodes=${MAX_NUM} --min-nodes=${MIN_NUM}\
--scopes="cloud-platform"

7. deploy an application to the cluster and confirm the IP
</code>```

Make a https-connection from the application to an other gcp-project's application.
And detect the IP address of origin-request as 'REMOTE_ADDR'.

答:
Thanks for your clarification. So basically this is what we have:

Private GKE -> Cloud NAT -> External GAE load balancer -> GAE

and the App in GAE is seeing an ipv6 address

When you use Cloud NAT, Google Private Access is enabled by default and so requests from your VPC to GAE will use Private Access.

Private Access will use the Google internal network to route the request to ensure the public internet is not used. To properly route this, we use IPv6.

To explain the IPv6 address:

Google uses a set NAT64 prefix: fda3:e722:ac3:10::/64. This value is constant across all GCP VPC networks. The last 32 bits are converted directly from the internal IP address of the host making the request. This is converted from binary to hex (ie 10.132.0.5 in decimal -> 0x0a840005 in hex).

The middle part between the NAT64 prefix and the last 32 bits is a unique identifier for your VPC. This identifier is unique to each VPC network, thus you can have more than 1 per project.

Currently, there is no way to predict this identifier beforehand. The best way to get this information is by sending a request to GAE through Private Access and take note of the IPv6 listed as the source. The IPv6 address is available in the response from the server, and in the Stackdriver Logs.

Using this information, you should be able to adequately maintain your whitelist for your GAE hosted applications.

All that being said, if you are seeing The IPv4 addresses from the GKE pods show up as 0.0.0.0 in the GAE application. I encourage you to report this using this link

Body:
Long time passed after I posted a related issue.
Link

Now, the issue has changed.
With same procedure to make a cluster and NAT setting, GAE application shows 0.0.0.0 , not IPv6 address.

※GAE application is using a customized-domain.

In case that the egress communication is with on-prem server, the server shows a static IP address, as set by NAT.

Is there any change in a Google Internal networking?
I would like to know how to avoid this issue, when I want an exact static IP address.

1.create a VPC

gcloud compute networks create ${vpc_name}\
--project=${project_id}\
--bgp-routing-mode=regional\
--subnet-mode=custom
2. create a subnet

gcloud compute networks subnets create ${subnet_name}\
--project=${project_id}\
--region=${region}\
--network=${vpc_name}\
--range=192.168.0.0/16
3. create an external static IP

gcloud compute addresses create ${external_ip_name}\
--region=${region}
4. create a route

gcloud compute routers create ${router_name}\
--region=${region}\
--network=${vpc_name}\
--asn=65001
5. create a nat

gcloud compute routers nats create ${nat_name}\
--region=${region}\
--router=${router_name}\
--nat-external-ip-pool="${external_ip}"\
--nat-all-subnet-ip-ranges

6. make a cluster

gcloud container clusters create ${gke_cluster_name}\
--project=${project_id}\
--zone=${zone}\
--network=${vpc_name}\
--subnetwork=${subnet_name}\
--enable-ip-alias\
--enable-private-nodes\
--master-ipv4-cidr=172.16.0.0/28\
--enable-master-authorized-networks\
--master-authorized-networks=0.0.0.0/0\
--no-enable-legacy-authorization\
--no-enable-basic-auth\
--no-issue-client-certificate\
--num-nodes=${NUM_NODE}\
--enable-autoscaling --max-nodes=${MAX_NUM} --min-nodes=${MIN_NUM}\
--scopes="cloud-platform"

7. deploy an application to the cluster and confirm the IP

Make a https-connection from the application to an other gcp-project's application.
And detect the IP address of origin-request as 'REMOTE_ADDR'.


问:
How to fetch the input elements value by class name in jquery
I want to fetch input elements value, they have class "features". I can access all of them

alert($('.features').length);

Correct me if I am wrong, $('.features') is an array of html input elements.But I tried

Array.isArray($('.features')) // returned false

I want to access the value of each element . How to achieve this
I tried to do one and below is the code snippet

function maintest() {

 for(i = 0 ; i < 5 ; i ++ ) {
  $("<input>").attr({"class":"features"}).appendTo("#mainDiv").val("input"+i);
  $("

").appendTo("#mainDiv");
 }

  $("<button> Click me! </button>").click(function() {
  let inputArray = [];
  inputArray = $('.features');
  alert(inputArray.length);
    //alert( inputArray[0].val());
    //what must be put here to see the data value
  }).appendTo("#mainDiv");
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<body onload="maintest()">
  <div id="mainDiv"></div>
</body></code>```

答:
You could loop over the input array using jQuery $.each method.

Example:

function maintest() {
  for (i = 0; i < 5; i++) {
$("<input>")
  .attr({ class: "features" })
  .appendTo("#mainDiv")
  .val("input" + i);
$("

").appendTo("#mainDiv");
  }

  $("<button> Click me! </button>")
.click(function() {
  let inputArray = [];
  inputArray = $(".features");
  $.each(inputArray, function(index, input) {
    console.log(input.value);
  });
})
.appendTo("#mainDiv");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="maintest()">
  <div id="mainDiv"></div>
</body></code>```

Body:
You could loop over the input array using jQuery $.each method.

Example:

function maintest() {
  for (i = 0; i < 5; i++) {
$("<input>")
  .attr({ class: "features" })
  .appendTo("#mainDiv")
  .val("input" + i);
$("<br/><br/>").appendTo("#mainDiv");
  }

  $("<button> Click me! </button>")
.click(function() {
  let inputArray = [];
  inputArray = $(".features");
  $.each(inputArray, function(index, input) {
    console.log(input.value);
  });
})
.appendTo("#mainDiv");
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="maintest()">
  <div id="mainDiv"></div>
</body>


问:
Check if service exists in bash (CentOS and Ubuntu)
What is the best way in bash to check if a service is installed? It should work across both Red Hat (CentOS) and Ubuntu?

Thinking:

```<code>service="mysqld"
if [ -f "/etc/init.d/$service" ]; then
    # mysqld service exists
fi
</code>```

Could also use the service command and check the return code.

```<code>service mysqld status
if [ $? = 0 ]; then
    # mysqld service exists
fi
</code>```

What is the best solution?

答:
```<code>var=$(service --status-all | grep -w "$Service")
if [ "output" != "" ]; then
    #executes if service exists
else
    #executes if service does not exist
fi
</code>```

$Service is the name of the service you want to know if exists.
var will contain something like

```<code>[+]    apache2
</code>```

if the service does exist

Body:
What is the best way in bash to check if a service is installed? It should work across both Red Hat (CentOS) and Ubuntu?

Thinking:

service="mysqld"
if [ -f "/etc/init.d/$service" ]; then
    # mysqld service exists
fi

Could also use the service command and check the return code.

service mysqld status
if [ $? = 0 ]; then
    # mysqld service exists
fi

What is the best solution?

Body:
var=$(service --status-all | grep -w "$Service")
if [ "output" != "" ]; then
    #executes if service exists
else
    #executes if service does not exist
fi

$Service is the name of the service you want to know if exists.
var will contain something like

[+]    apache2

if the service does exist


问:
Dropdownlist databind using another class?
The Dropdownlist data binding using throw common function. In this have a problem in passing dropdownlist.

Error: Object cannot be set an instance of object

The code is below

Aspx Page Code:

```<code><asp:DropDownList ID="ddlagent1" CssClass="ParameterTextBox" runat="server" AutoPostBack="false"></asp:DropDownList>

Protected Sub chkcity_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkcity.CheckedChanged
 ldstOption = //fill values here
 lobjGeneral.loadComboBox1(Me.ddlagent1, ldstOption.Tables(0), "No Data found")
End Sub
</code>```

General Class:

```<code>Public Sub loadComboBox1(ByVal cbo As DropDownList, ByVal dset As DataTable, ByVal msgstr As String, _
                Optional ByVal visible As Boolean = True, _
                Optional ByVal enabled As Boolean = True, _
                Optional ByVal tno As Integer = 0, _
                Optional ByVal dmem As Integer = 2, _
                Optional ByVal vmem As Integer = 1)

        Try
            If (dset.Rows.Count > 0) Then
                cbo.DataSource = dset
                cbo.DataTextField = dset.Columns(dmem).Caption
                cbo.DataValueField = dset.Columns(vmem).Caption
                cbo.DataBind()
                cbo.SelectedIndex = 0
                cbo.Visible = visible
                cbo.Enabled = enabled
            Else
                dset = Nothing
                cbo.Text = msgstr
            End If
        Catch ex As Exception
            'Call CreateErrorLogFile("General", "loadComboBox", Err.Description)
        End Try
    End Sub
</code>```

答:
Your method should have to get Dropdownlist reference</p>

```<code>Public Sub loadComboBox1(ByRef cbo As DropDownList, ......
</code>```

Body:
The Dropdownlist data binding using throw common function. In this have a problem in passing dropdownlist.

Error: Object cannot be set an instance of object

The code is below

Aspx Page Code:

<asp:DropDownList ID="ddlagent1" CssClass="ParameterTextBox" runat="server" AutoPostBack="false"></asp:DropDownList>

Protected Sub chkcity_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkcity.CheckedChanged
 ldstOption = //fill values here
 lobjGeneral.loadComboBox1(Me.ddlagent1, ldstOption.Tables(0), "No Data found")
End Sub

General Class:

Public Sub loadComboBox1(ByVal cbo As DropDownList, ByVal dset As DataTable, ByVal msgstr As String, _
                Optional ByVal visible As Boolean = True, _
                Optional ByVal enabled As Boolean = True, _
                Optional ByVal tno As Integer = 0, _
                Optional ByVal dmem As Integer = 2, _
                Optional ByVal vmem As Integer = 1)

        Try
            If (dset.Rows.Count > 0) Then
                cbo.DataSource = dset
                cbo.DataTextField = dset.Columns(dmem).Caption
                cbo.DataValueField = dset.Columns(vmem).Caption
                cbo.DataBind()
                cbo.SelectedIndex = 0
                cbo.Visible = visible
                cbo.Enabled = enabled
            Else
                dset = Nothing
                cbo.Text = msgstr
            End If
        Catch ex As Exception
            'Call CreateErrorLogFile("General", "loadComboBox", Err.Description)
        End Try
    End Sub

Body:
Your method should have to get Dropdownlist reference

Public Sub loadComboBox1(ByRef cbo As DropDownList, ......


问:
On click loads a different website but still within my website - like Facebook
On Facebook, via mobile, If you go to a profile page and click on a link to a person website it loads the website up in front of the Facebook website so when they press the X in the top left-hand corner it then deletes the webpage and the Facebook is still there.

On my desktop computer, I have used a different tap to load up but can't find out how I can do it this way for mobile and tablet?

I'm sure its quite simple but I have not got a clue what to look for sadly

Hope you can help, please.

Many Thanks

Tim

答:
The picture you give appears to be the native mobile app for Facebook and not a webpage.

It just uses an embedded browser in the mobile app. How you do that depends on which platform you are developing for. For iOS it would be something along the lines of the UIWebView class.


问:
Issue with handling json api response in Python
I am using the Censys api in python to programmatically look through host and grab information about them. Censys website says it returns Json formatted data and it looks like Json formatted data but, I cant seem to figure out how to tun the api response into a json object. However, if i write the json response to a json file and load it. It works fine Any ideas?

Update: Figured out issue is with nested json that the api returns. Looking for libraries to flatten it.

Main.py

```<code>c = censys.ipv4.CensysIPv4(api_id=UID, api_secret=SECRET)
for result in c.search("autonomous_system.asn:15169 AND tags.raw:iot", max_records=1):

 hostIPS.append(result["ip"]);

for host in hostIPS:

  for details in c.view(host):
    # test = json.dumps(details)
    # test = json.load(test)
    # data = json.load(details)
    data = json.loads(details)
    print(data)
</code>```

答: You don't need to convert it to an object, it's already json.loaded. See the implementation here: https://github.com/censys/censys-python/blob/master/censys/base.py

Body:
I am using the Censys api in python to programmatically look through host and grab information about them. Censys website says it returns Json formatted data and it looks like Json formatted data but, I cant seem to figure out how to tun the api response into a json object. However, if i write the json response to a json file and load it. It works fine Any ideas?

Update: Figured out issue is with nested json that the api returns. Looking for libraries to flatten it.

Main.py

c = censys.ipv4.CensysIPv4(api_id=UID, api_secret=SECRET)
for result in c.search("autonomous_system.asn:15169 AND tags.raw:iot", max_records=1):

 hostIPS.append(result["ip"]);

for host in hostIPS:

  for details in c.view(host):
    # test = json.dumps(details)
    # test = json.load(test)
    # data = json.load(details)
    data = json.loads(details)
    print(data)


问:
String Arrays in Ada
I have a program in Ada95, in which I have to create an array of strings. This array can contain strings of variable length.

Example:
I have declared the array in which all the indexes can store strings of size 50. When I assign a smaller string to the above array, I get "Constraint Error".

Code:

```<code>procedure anyname is
    input_array : array(1..5) of String(1..50);
begin
    input_array(1):="12345";
end anyname;
</code>```

I have tried to create the array of Unbounded_Strings. But that doesn't work either. Can anyone tell me how to store this "12345" in the above string array?

答:
Strings in Ada are arrays of characters of fixed length. In order to use strings of variable length (which may often be the case when arrays of strings are needed, e.g. arrays of names, each name being of variable length), each individual string may be declared as an Unbounded_String. The only caveat is that this allocates from the heap memory. Below is a complete example of an array of strings in Ada.

```<code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Text_IO; use Ada.Strings.Unbounded.Text_IO;

procedure arrayAda is
type DaysArray is array(1..7) of Unbounded_String;
days: DaysArray;
begin
    days(1):=To_Unbounded_String("Sunday");
    days(2):=To_Unbounded_String("Monday");
    days(3):=To_Unbounded_String("Tuesday");
    days(4):=To_Unbounded_String("Wednesday");
    days(5):=To_Unbounded_String("Thursday");
    days(6):=To_Unbounded_String("Friday");
    days(7):=To_Unbounded_String("Saturday");
    for index in 1..7 loop
        Put(days(index));
        Put("   ");
    end loop;
end arrayAda;
</code>```

This produces the following output:

```<code>$ ./arrayAda
Sunday   Monday   Tuesday   Wednesday   Thursday   Friday   Saturday
</code>```

Title: String Arrays in Ada

Body:
I have a program in Ada95, in which I have to create an array of strings. This array can contain strings of variable length.

Example:
I have declared the array in which all the indexes can store strings of size 50. When I assign a smaller string to the above array, I get "Constraint Error".

Code:

procedure anyname is
    input_array : array(1..5) of String(1..50);
begin
    input_array(1):="12345";
end anyname;

I have tried to create the array of Unbounded_Strings. But that doesn't work either. Can anyone tell me how to store this "12345" in the above string array?

Body:
Strings in Ada are arrays of characters of fixed length. In order to use strings of variable length (which may often be the case when arrays of strings are needed, e.g. arrays of names, each name being of variable length), each individual string may be declared as an Unbounded_String. The only caveat is that this allocates from the heap memory. Below is a complete example of an array of strings in Ada.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Text_IO; use Ada.Strings.Unbounded.Text_IO;

procedure arrayAda is
type DaysArray is array(1..7) of Unbounded_String;
days: DaysArray;
begin
    days(1):=To_Unbounded_String("Sunday");
    days(2):=To_Unbounded_String("Monday");
    days(3):=To_Unbounded_String("Tuesday");
    days(4):=To_Unbounded_String("Wednesday");
    days(5):=To_Unbounded_String("Thursday");
    days(6):=To_Unbounded_String("Friday");
    days(7):=To_Unbounded_String("Saturday");
    for index in 1..7 loop
        Put(days(index));
        Put("   ");
    end loop;
end arrayAda;

This produces the following output:

$ ./arrayAda
Sunday   Monday   Tuesday   Wednesday   Thursday   Friday   Saturday


问:
Text responsive with the d3.js treemap tiles
I am working with the d3.js treemap layout . In the tiles the font size is too small . How to display in a bigger font for big tiles and smaller for small tiles or display the label text at the center of each tiles. Find my code link here https://codesandbox.io/s/loving-mccarthy-wfbtg. The label can be centered and the font size can be increased for better view. Also the title contains the total which I dont want to show how to remove the count in the breadcrumb title alone.

Logic is here

```<code>createTreeChart = () => {
    const width = 550;
    const height = 600;
    const padding = 60;
    const format = d3.format(",d");
    const name = d =>
      d
        .ancestors()
        .reverse()
        .map(d => d.data.name)
        .join("/");
    function tile(node, x0, y0, x1, y1) {
      d3.treemapBinary(node, 0, 0, width, height);
      for (const child of node.children) {
        child.x0 = x0 + (child.x0 / width) * (x1 - x0);
        child.x1 = x0 + (child.x1 / width) * (x1 - x0);
        child.y0 = y0 + (child.y0 / height) * (y1 - y0);
        child.y1 = y0 + (child.y1 / height) * (y1 - y0);
      }
    }
    const treemap = data =>
      d3.treemap().tile(tile)(
        d3
          .hierarchy(data)
          .sum(d => d.value)
          .sort((a, b) => b.value - a.value)
      );
    const svg = d3
      .select("#chart")
      .append("svg")
      .attr("viewBox", [0.5, -30.5, width, height + 30])
      .style("font", "10px sans-serif");

    const x = d3.scaleLinear().rangeRound([0, width]);
    const y = d3.scaleLinear().rangeRound([0, height]);

    // const svg = d3
    //   .create("svg")
    //   .select("#chart")
    //   .append("svg")
    //   .attr("viewBox", [0.5, -30.5, width, height + 30])
    //   .style("font", "10px sans-serif");

    let group = svg.append("g").call(render, treemap(data));

    function render(group, root) {
      const node = group
        .selectAll("g")
        .data(root.children.concat(root))
        .join("g");

      node
        .filter(d => (d === root ? d.parent : d.children))
        .attr("cursor", "pointer")
        .on("click", d => (d === root ? zoomout(root) : zoomin(d)));

      node.append("title").text(d => `${name(d)}\n${format(d.value)}`);

      node
        .append("rect")
        .attr("id", d => (d.leafUid = "leaf"))
        .attr("fill", d => (d === root ? "#fff" : d.children ? "#ccc" : "#ddd"))
        .attr("stroke", "#fff");

      node
        .append("clipPath")
        .attr("id", d => (d.clipUid = "clip"))
        .append("use")
        .attr("xlink:href", d => d.leafUid.href);

      node
        .append("text")
        .attr("clip-path", d => d.clipUid)
        .attr("font-weight", d => (d === root ? "bold" : null))
        .selectAll("tspan")
        .data(d =>
          (d === root ? name(d) : d.data.name)
            .split(/(?=[A-Z][^A-Z])/g)
            .concat(format(d.value))
        )
        .join("tspan")
        .attr("x", 3)
        .attr(
          "y",
          (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + 1.1 + i * 0.9}em`
        )
        .attr("fill-opacity", (d, i, nodes) =>
          i === nodes.length - 1 ? 0.7 : null
        )
        .attr("font-weight", (d, i, nodes) =>
          i === nodes.length - 1 ? "normal" : null
        )
        .text(d => d);

      group.call(position, root);
    }

    function position(group, root) {
      group
        .selectAll("g")
        .attr("transform", d =>
          d === root ? `translate(0,-30)` : `translate(${x(d.x0)},${y(d.y0)})`
        )
        .select("rect")
        .attr("width", d => (d === root ? width : x(d.x1) - x(d.x0)))
        .attr("height", d => (d === root ? 30 : y(d.y1) - y(d.y0)));
    }

    // When zooming in, draw the new nodes on top, and fade them in.
    function zoomin(d) {
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.append("g").call(render, d));

      x.domain([d.x0, d.x1]);
      y.domain([d.y0, d.y1]);

      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .call(position, d.parent)
        )
        .call(t =>
          group1
            .transition(t)
            .attrTween("opacity", () => d3.interpolate(0, 1))
            .call(position, d)
        );
    }

    // When zooming out, draw the old nodes on top, and fade them out.
    function zoomout(d) {
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.insert("g", "*").call(render, d.parent));

      x.domain([d.parent.x0, d.parent.x1]);
      y.domain([d.parent.y0, d.parent.y1]);

      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .attrTween("opacity", () => d3.interpolate(1, 0))
            .call(position, d)
        )
        .call(t => group1.transition(t).call(position, d.parent));
    }

    return svg.node();
  };
</code>```

答:
Change the font-size attribute of the text nodes. Add .attr("font-size", ...) as the following.

node
    .append("text")
    .attr("clip-path", d => d.clipUid)
    .attr("font-weight", d => (d === root ? "bold" : null))
    .attr("font-size", d => {
          if (d === root) return "1em";
          const width = x(d.x1) - x(d.x0), height = y(d.y1) - y(d.y0);
          return Math.max(Math.min(width/5, height/2, Math.sqrt((width*width + height*height))/10), 9)
        })
    .selectAll("tspan")
    ...

```

<p>This sets the <code>font-size</code> to 10% of the diagonal of each rect.
In case the text becomes too small to read, <code>font-size</code> is set to the minimum of 9. The texts might become too big for rects that are vertically long, so the maximum set to one fifth of the width of the rect or half of the height of the rect, whichever is bigger.</p>

<p>The font-size doesn't scale correctly after zooming because <code>x</code> and <code>y</code> scales' domains are updated only after <code>render</code>. Update the domains before calling <code>render</code> in <code>zoomin</code> and <code>zoomout</code> functions.</p>

<pre class="lang-js prettyprint-override"><code>function zoomin(d) {
      x.domain([d.x0, d.x1]);
      y.domain([d.y0, d.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.append("g").call(render, d));
      ...
    }

function zoomout(d) {
      x.domain([d.parent.x0, d.parent.x1]);
      y.domain([d.parent.y0, d.parent.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.insert("g", "*").call(render, d.parent));
      ...
    }

</code>```

Breadcrumb fix. When you set the rectangles' tspans' x and y, you are also setting the x and y of the tspans in the breadcrumb with the same logic. The easiest way to solve this is simply to make the breadcrumb one tspan. This, however, limits the styling of the breadcrumb. Instead, style the breadcrumb text separately at the end of the render function.

...
        .text(d => d);

      node.selectAll('text').filter(d => d === root)
        .selectAll("tspan").attr("y", '1.1em').attr("x", undefined);

      group.call(position, root);
```

<p>And the regex for the breadcrumb text doesn't look like it's working out. It's separating the text at odd places. Change <code>name(d).split(/(?=[A-Z][^A-Z])/g)</code> to <code>name(d).split(/(?=\/)/g)</code>.</p>

<p>Text centering. There's a lot to be done. Text anchor is set to middle, and <code>transform: translate</code> text boxes by half of width/height.</p>

```        .attr("text-anchor", d => d === root ? null : "middle")
        .attr("transform", d=> d === root ? null :
          `translate(${(x(d.x1) - x(d.x0))/2}, ${(y(d.y1) - y(d.y0))/2})`)
        .selectAll("tspan")
```

<p>And change <code>tspan</code>s' <code>y</code> to center them vertically.</p>

```        .attr("x", 3)
        .attr(
          "y",
          (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + (i - nodes.length/2) * 0.9}em`
        )
```

Body:
I am working with the d3.js treemap layout . In the tiles the font size is too small . How to display in a bigger font for big tiles and smaller for small tiles or display the label text at the center of each tiles. Find my code link here https://codesandbox.io/s/loving-mccarthy-wfbtg. The label can be centered and the font size can be increased for better view. Also the title contains the total which I dont want to show how to remove the count in the breadcrumb title alone.

Logic is here

createTreeChart = () => {
    const width = 550;
    const height = 600;
    const padding = 60;
    const format = d3.format(",d");
    const name = d =>
      d
        .ancestors()
        .reverse()
        .map(d => d.data.name)
        .join("/");
    function tile(node, x0, y0, x1, y1) {
      d3.treemapBinary(node, 0, 0, width, height);
      for (const child of node.children) {
        child.x0 = x0 + (child.x0 / width) * (x1 - x0);
        child.x1 = x0 + (child.x1 / width) * (x1 - x0);
        child.y0 = y0 + (child.y0 / height) * (y1 - y0);
        child.y1 = y0 + (child.y1 / height) * (y1 - y0);
      }
    }
    const treemap = data =>
      d3.treemap().tile(tile)(
        d3
          .hierarchy(data)
          .sum(d => d.value)
          .sort((a, b) => b.value - a.value)
      );
    const svg = d3
      .select("#chart")
      .append("svg")
      .attr("viewBox", [0.5, -30.5, width, height + 30])
      .style("font", "10px sans-serif");

    const x = d3.scaleLinear().rangeRound([0, width]);
    const y = d3.scaleLinear().rangeRound([0, height]);

    // const svg = d3
    //   .create("svg")
    //   .select("#chart")
    //   .append("svg")
    //   .attr("viewBox", [0.5, -30.5, width, height + 30])
    //   .style("font", "10px sans-serif");

    let group = svg.append("g").call(render, treemap(data));

    function render(group, root) {
      const node = group
        .selectAll("g")
        .data(root.children.concat(root))
        .join("g");

      node
        .filter(d => (d === root ? d.parent : d.children))
        .attr("cursor", "pointer")
        .on("click", d => (d === root ? zoomout(root) : zoomin(d)));

      node.append("title").text(d => `${name(d)}\n${format(d.value)}`);

      node
        .append("rect")
        .attr("id", d => (d.leafUid = "leaf"))
        .attr("fill", d => (d === root ? "#fff" : d.children ? "#ccc" : "#ddd"))
        .attr("stroke", "#fff");

      node
        .append("clipPath")
        .attr("id", d => (d.clipUid = "clip"))
        .append("use")
        .attr("xlink:href", d => d.leafUid.href);

      node
        .append("text")
        .attr("clip-path", d => d.clipUid)
        .attr("font-weight", d => (d === root ? "bold" : null))
        .selectAll("tspan")
        .data(d =>
          (d === root ? name(d) : d.data.name)
            .split(/(?=[A-Z][^A-Z])/g)
            .concat(format(d.value))
        )
        .join("tspan")
        .attr("x", 3)
        .attr(
          "y",
          (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + 1.1 + i * 0.9}em`
        )
        .attr("fill-opacity", (d, i, nodes) =>
          i === nodes.length - 1 ? 0.7 : null
        )
        .attr("font-weight", (d, i, nodes) =>
          i === nodes.length - 1 ? "normal" : null
        )
        .text(d => d);

      group.call(position, root);
    }

    function position(group, root) {
      group
        .selectAll("g")
        .attr("transform", d =>
          d === root ? `translate(0,-30)` : `translate(${x(d.x0)},${y(d.y0)})`
        )
        .select("rect")
        .attr("width", d => (d === root ? width : x(d.x1) - x(d.x0)))
        .attr("height", d => (d === root ? 30 : y(d.y1) - y(d.y0)));
    }

    // When zooming in, draw the new nodes on top, and fade them in.
    function zoomin(d) {
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.append("g").call(render, d));

      x.domain([d.x0, d.x1]);
      y.domain([d.y0, d.y1]);

      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .call(position, d.parent)
        )
        .call(t =>
          group1
            .transition(t)
            .attrTween("opacity", () => d3.interpolate(0, 1))
            .call(position, d)
        );
    }

    // When zooming out, draw the old nodes on top, and fade them out.
    function zoomout(d) {
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.insert("g", "*").call(render, d.parent));

      x.domain([d.parent.x0, d.parent.x1]);
      y.domain([d.parent.y0, d.parent.y1]);

      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .attrTween("opacity", () => d3.interpolate(1, 0))
            .call(position, d)
        )
        .call(t => group1.transition(t).call(position, d.parent));
    }

    return svg.node();
  };

Body:
Change the font-size attribute of the text nodes. Add .attr("font-size", ...) as the following.

node
    .append("text")
    .attr("clip-path", d => d.clipUid)
    .attr("font-weight", d => (d === root ? "bold" : null))
    .attr("font-size", d => {
          if (d === root) return "1em";
          const width = x(d.x1) - x(d.x0), height = y(d.y1) - y(d.y0);
          return Math.max(Math.min(width/5, height/2, Math.sqrt((width*width + height*height))/10), 9)
        })
    .selectAll("tspan")
    ...

This sets the font-size to 10% of the diagonal of each rect.
In case the text becomes too small to read, font-size is set to the minimum of 9. The texts might become too big for rects that are vertically long, so the maximum set to one fifth of the width of the rect or half of the height of the rect, whichever is bigger.

The font-size doesn't scale correctly after zooming because x and y scales' domains are updated only after render. Update the domains before calling render in zoomin and zoomout functions.

function zoomin(d) {
      x.domain([d.x0, d.x1]);
      y.domain([d.y0, d.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.append("g").call(render, d));
      ...
    }

function zoomout(d) {
      x.domain([d.parent.x0, d.parent.x1]);
      y.domain([d.parent.y0, d.parent.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.insert("g", "*").call(render, d.parent));
      ...
    }

Breadcrumb fix. When you set the rectangles' tspans' x and y, you are also setting the x and y of the tspans in the breadcrumb with the same logic. The easiest way to solve this is simply to make the breadcrumb one tspan. This, however, limits the styling of the breadcrumb. Instead, style the breadcrumb text separately at the end of the render function.

...
        .text(d => d);

      node.selectAll('text').filter(d => d === root)
        .selectAll("tspan").attr("y", '1.1em').attr("x", undefined);

      group.call(position, root);

And the regex for the breadcrumb text doesn't look like it's working out. It's separating the text at odd places. Change name(d).split(/(?=[A-Z][^A-Z])/g) to name(d).split(/(?=\/)/g).

Text centering. There's a lot to be done. Text anchor is set to middle, and transform: translate text boxes by half of width/height.

        .attr("text-anchor", d => d === root ? null : "middle")
        .attr("transform", d=> d === root ? null :
          `translate(${(x(d.x1) - x(d.x0))/2}, ${(y(d.y1) - y(d.y0))/2})`)
        .selectAll("tspan")

And change tspans' y to center them vertically.

        .attr("x", 3)
        .attr(
          "y",
          (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + (i - nodes.length/2) * 0.9}em`
        )


问:
How to intercept a function in angularJs
I have a directive called "my-dir" that I can't modified inside my project

```<code><div ng-controller="MyCtrl">
  <my-dir>
    <button ng-click="doSomething()">Click it</button>
  </my-dir>
</div>
</code>```

I need to do some checks before invoking doSomething function. I can't modified anything inside my-dir directive. Is there a way to intercept into MyCtrl the ng-click on the button?

答:
If I understand correctly,

```<code><div ng-controller="MyCtrl">
    <div ng-if = "[Function or variable] -> This can be an option to hide the button">
        <my-dir>
            <button ng-click="doSomething()">Click it</button>
        </my-dir>
    </div>
</code>```

or you can override the directive but it is gonna be a bit more complex. You can check the following link, there is also a demo which can be helpful if you choose this way. AngularJS override directive controller function

Body:
I have a directive called "my-dir" that I can't modified inside my project

  <my-dir>
    <button ng-click="doSomething()">Click it</button>
  </my-dir>

I need to do some checks before invoking doSomething function. I can't modified anything inside my-dir directive. Is there a way to intercept into MyCtrl the ng-click on the button?

Body:
If I understand correctly,

<div ng-controller="MyCtrl">
    <div ng-if = "[Function or variable] -> This can be an option to hide the button">
        <my-dir>
            <button ng-click="doSomething()">Click it</button>
        </my-dir>
    </div>

or you can override the directive but it is gonna be a bit more complex. You can check the following link, there is also a demo which can be helpful if you choose this way. AngularJS override directive controller function


问:
Get list of certificates from the certificate store in C#
For a secure application I need to select a certificate in a dialog.
How can I access certificate store or a part of it (e.g. storeLocation="Local Machine" and storeName="My") using C# and get a collection of all certificates from there?

答:
```<code>X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certificate in store.Certificates){
    //TODO's
}
</code>```

OwnerDisplayName: Kottan


问:
VSC command palette (too narrow)
Is there any possibility to make command palette wider?

When looking for symbol (e.g. same functions with different set of arguments) to less characters are shown to choose proper definition.

Is there any possibility to mitigate this problem?

答: Using standard VS Code settings looks like you can't do this, which I agree should be possible. The strange thing is that I can't find an extension too that does this, so there may be a specific reason why this can't be done at the moment. By the way you can open an Issue on the VSCode Github and ask the developers themself to add this feature or why seems to be missing at the moment</p>

Title: VSC command palette (too narrow)


问:
Error for style.css in angular application
I'm working on an application using angular 7. The application throws this error:

Refused to apply style from 'http://localhost:4200/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

What I tried and didn't work is setting it in angular.json inside the style tag, didn't work. Now i have this but it still not working:

Here's my index.html:

```<code><html lang="en">

<head>
  <meta charset="utf-8">
  <title>NTT Hotline Manager</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.png">
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>

<body>
  <app-root></app-root>
</body>

</html>
</code>```

My style.css file:

```<code>@import "../node_modules/@angular/material/prebuilt-themes/indigo-pink.css";
@import 'https://fonts.googleapis.com/icon?family=Material+Icons';
@import "../src/app/css/all.css";
</code>```

I have imported the css from my all.css file

My folder structure:

```<code>myProject
`-- Webcontent
    `-- src
        |-- app
        |   |-- components
        |   `-- css
        |       `-- all.css
        `-- styles.css
</code>```

But for some reason it's not working and throws the error above. What can be the problem?

答:
I think the problem is because you are adding the all.css file in a wrong path and is not finding all.css. Try to change the path to @import "./app/css/all.css"; and remove from index.html <link rel="stylesheet" type="text/css" href: '../Webcontent/src/styles.css'>. In your angular.json you must have this structure too.

```<code>"styles": [
   "Webcontent/src/styles.scss"
],
</code>```

Body:
I'm working on an application using angular 7. The application throws this error:

Refused to apply style from 'http://localhost:4200/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

What I tried and didn't work is setting it in angular.json inside the style tag, didn't work. Now i have this but it still not working:

Here's my index.html:

  <meta charset="utf-8">
  <title>NTT Hotline Manager</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.png">
  <link rel="stylesheet" type="text/css" href="styles.css">

  <app-root></app-root>

My style.css file:

@import "../node_modules/@angular/material/prebuilt-themes/indigo-pink.css";
@import 'https://fonts.googleapis.com/icon?family=Material+Icons';
@import "../src/app/css/all.css";

I have imported the css from my all.css file

My folder structure:

myProject
`-- Webcontent
    `-- src
        |-- app
        |   |-- components
        |   `-- css
        |       `-- all.css
        `-- styles.css

But for some reason it's not working and throws the error above. What can be the problem?

Body:
I think the problem is because you are adding the all.css file in a wrong path and is not finding all.css. Try to change the path to @import "./app/css/all.css"; and remove from index.html <link rel="stylesheet" type="text/css" href: '../Webcontent/src/styles.css'>. In your angular.json you must have this structure too.

"styles": [
   "Webcontent/src/styles.scss"
],


问:
Splitting an array of points into multiple arrays that have a specific distance from each other
I have an array of points that look like this (x,y):

```<code>6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25
18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25
</code>```

This array represents a two, separate, series of points that are on a 1.25" offset from each other.  There is two series, but there can be [n] series, and I need to split them up into the appropriate number of arrays based on the specific offset like this:

```<code>6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25

18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25
</code>```

The offset can be in the X or the Y, but not both.  I have been working on it for a little while now and am kind of stuck.

Edit

What I have tried so far, is to get a point in the array, and search for all points that are on the interval specified (getDist calculates the distance from one point to another):

```<code>foreach(Point firstPoint in points){
    foreach(Point nextPoint in points){
        if(isSame(firstPoint, nextPoint)
            continue;

        if(getDist(firstPoint, nextPoint) % 1.25 == 0){
            // add to new array
        }
    }
}

double getDist(Point p1, Point p2) => Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));

bool isSame(Point p1, Point p2) => p1.X == p2.X && p1.Y == p2.Y;
</code>```

The problem I run into is that this looks at all the points, then looks at them each one again creating a huge set of arrays.

答:
Here's another implementation:</p>

```<code>static void Main(string[] args)
{
    List<PointF> points = new List<PointF>()
    {
        new PointF(6, 12),
        new PointF(6, 13.25f),
        new PointF(6, 14.5f),
        new PointF(6, 15.75f),
        new PointF(6, 17),
        new PointF(6, 18.25f),
        new PointF(18, 12),
        new PointF(18, 13.25f),
        new PointF(18, 14.5f),
        new PointF(18, 15.75f),
        new PointF(18, 17),
        new PointF(18, 18.25f)
    };

    var result = new List<List<PointF>>();
    int i, j = 0;

    for (i = 1; i < points.Count; i++)
    {
        if (!IsInRange(points[i], points[i - 1]))
        {
            result.Add(points.GetRange(j, i - j));
            j = i;
        }
    }
    result.Add(points.GetRange(j, i - j));
}

static bool IsInRange(PointF a, PointF b) => Math.Abs(a.X + a.Y - b.X - b.Y) <= 1.25f;
</code>```

Body:
I have an array of points that look like this (x,y):

6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25
18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25

This array represents a two, separate, series of points that are on a 1.25" offset from each other.  There is two series, but there can be [n] series, and I need to split them up into the appropriate number of arrays based on the specific offset like this:

6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25

18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25

The offset can be in the X or the Y, but not both.  I have been working on it for a little while now and am kind of stuck.

Edit

What I have tried so far, is to get a point in the array, and search for all points that are on the interval specified (getDist calculates the distance from one point to another):

foreach(Point firstPoint in points){
    foreach(Point nextPoint in points){
        if(isSame(firstPoint, nextPoint)
            continue;

        if(getDist(firstPoint, nextPoint) % 1.25 == 0){
            // add to new array
        }
    }
}

double getDist(Point p1, Point p2) => Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));

bool isSame(Point p1, Point p2) => p1.X == p2.X && p1.Y == p2.Y;

The problem I run into is that this looks at all the points, then looks at them each one again creating a huge set of arrays.

Body:
Here's another implementation:

static void Main(string[] args)
{
    List<PointF> points = new List<PointF>()
    {
        new PointF(6, 12),
        new PointF(6, 13.25f),
        new PointF(6, 14.5f),
        new PointF(6, 15.75f),
        new PointF(6, 17),
        new PointF(6, 18.25f),
        new PointF(18, 12),
        new PointF(18, 13.25f),
        new PointF(18, 14.5f),
        new PointF(18, 15.75f),
        new PointF(18, 17),
        new PointF(18, 18.25f)
    };

    var result = new List<List<PointF>>();
    int i, j = 0;

    for (i = 1; i < points.Count; i++)
    {
        if (!IsInRange(points[i], points[i - 1]))
        {
            result.Add(points.GetRange(j, i - j));
            j = i;
        }
    }
    result.Add(points.GetRange(j, i - j));
}

static bool IsInRange(PointF a, PointF b) => Math.Abs(a.X + a.Y - b.X - b.Y) <= 1.25f;


问:
How to sum data from multiple rows, based on a condition in Teradata?
I am trying to sum the data, based on two columns, where the values in 2 of the rows are equal.
This is the table I have:

```<code>Country   | System     | Money
 AAA      | A          | 10
 AAA      | A          | 200
 AAA      | B          | 60
 BBB      | B          | 600
 BBB      | A          | 150
 BBB      | B          | 140
</code>```

This is what I want to achieve:

```<code>Country   | System     | Money  | SystemSum
 AAA      | A          | 10     |  210
 AAA      | A          | 200    |  210
 AAA      | B          | 60     |  60
 BBB      | B          | 600    |  740
 BBB      | A          | 150    |  150
 BBB      | B          | 140    |  740
</code>```

This is what I have tried:

```<code>SUM(Money) OVER (ORDER BY Country, System ROWS UNBOUNDED PRECEDING)
</code>```

but it returns the values cumulatively. How to do it correctly?

答:
You can use over partition by clause for your purposes. </p>

```<code>WITH TBL(COUNTRY,SYSTEM,MONEY) AS (
 SELECT 'AAA' AS COUNTRY,'A' AS SYSTEM ,10  AS MONEY FROM DUAL UNION ALL
SELECT 'AAA' AS COUNTRY,'A' AS SYSTEM ,200 AS MONEY FROM DUAL UNION ALL
SELECT 'AAA' AS COUNTRY,'B' AS SYSTEM ,60  AS MONEY FROM DUAL UNION ALL
SELECT 'BBB' AS COUNTRY,'B' AS SYSTEM ,600 AS MONEY FROM DUAL UNION ALL
SELECT 'BBB' AS COUNTRY,'A' AS SYSTEM ,150 AS MONEY FROM DUAL UNION ALL
SELECT 'BBB' AS COUNTRY,'B' AS SYSTEM ,140 AS MONEY FROM DUAL )
SELECT COUNTRY,SYSTEM,MONEY,SUM(MONEY)OVER(PARTITION BY COUNTRY,SYSTEM) AS SUMALL FROM TBL
</code>```

Body:
I am trying to sum the data, based on two columns, where the values in 2 of the rows are equal.
This is the table I have:

Country   | System     | Money
 AAA      | A          | 10
 AAA      | A          | 200
 AAA      | B          | 60
 BBB      | B          | 600
 BBB      | A          | 150
 BBB      | B          | 140

This is what I want to achieve:

Country   | System     | Money  | SystemSum
 AAA      | A          | 10     |  210
 AAA      | A          | 200    |  210
 AAA      | B          | 60     |  60
 BBB      | B          | 600    |  740
 BBB      | A          | 150    |  150
 BBB      | B          | 140    |  740

This is what I have tried:

SUM(Money) OVER (ORDER BY Country, System ROWS UNBOUNDED PRECEDING)

but it returns the values cumulatively. How to do it correctly?

Body:
You can use over partition by clause for your purposes.

WITH TBL(COUNTRY,SYSTEM,MONEY) AS (
 SELECT 'AAA' AS COUNTRY,'A' AS SYSTEM ,10  AS MONEY FROM DUAL UNION ALL
SELECT 'AAA' AS COUNTRY,'A' AS SYSTEM ,200 AS MONEY FROM DUAL UNION ALL
SELECT 'AAA' AS COUNTRY,'B' AS SYSTEM ,60  AS MONEY FROM DUAL UNION ALL
SELECT 'BBB' AS COUNTRY,'B' AS SYSTEM ,600 AS MONEY FROM DUAL UNION ALL
SELECT 'BBB' AS COUNTRY,'A' AS SYSTEM ,150 AS MONEY FROM DUAL UNION ALL
SELECT 'BBB' AS COUNTRY,'B' AS SYSTEM ,140 AS MONEY FROM DUAL )
SELECT COUNTRY,SYSTEM,MONEY,SUM(MONEY)OVER(PARTITION BY COUNTRY,SYSTEM) AS SUMALL FROM TBL


问:
how can manipulate the different kind of array (string, int, char) as same format such as string in C#?
I have a collection of objects that each object would contains a different kind of array (string[],int[],char[]) or even single value as different types.

I want to get the values of each array as single format such as string  and convert it to a comma text value.

here is the code that manipulates an object of collection as "UInt16[]"

```<code>UInt16[] arrCapabilities = (UInt16[])(queryObj["Capabilities"]);
foreach (UInt16 arrValue in arrCapabilities)
{
    Console.WriteLine("Capabilities: {0}", arrValue);
}
</code>```

答:
You can use LINQ to convert your array of whatever into an IEnumerable of string:</p>

```<code>var myStrings = from c in arrCapabilities select c.ToString();
</code>```

Body:
I have a collection of objects that each object would contains a different kind of array (string[],int[],char[]) or even single value as different types.

I want to get the values of each array as single format such as string  and convert it to a comma text value.

here is the code that manipulates an object of collection as "UInt16[]"

UInt16[] arrCapabilities = (UInt16[])(queryObj["Capabilities"]);
foreach (UInt16 arrValue in arrCapabilities)
{
    Console.WriteLine("Capabilities: {0}", arrValue);
}

Body:
You can use LINQ to convert your array of whatever into an IEnumerable of string:

var myStrings = from c in arrCapabilities select c.ToString();


问:
extracting data from JSON object with python
I am trying to get data into SAMPLES and LABELS variables from JSON objects which looks like this.

```<code>{
"samples": [
    [
        28,
        25,
        95
    ],
    [
        21,
        13,
        70
    ],
    [
        13,
        21,
        70
    ]
],
"labels": [
    1,
    2,
    3
  ]
 }
</code>```

the code I am using

```<code>with open(data, 'r') as d:
complete_data = json.load(d)
for a in complete_data:
    samples = a['samples']
    lables = a['lables']
</code>```

but its says

samples = a['samples']

TypeError: string indices must be integers

答:
To get data from 'samples' and 'labels' You don't need to use loop. Try this:

```<code>import json

with open('data.json', 'r') as d:
    complete_data = json.load(d)

samples = complete_data['samples']
labels = complete_data['labels']

print(samples)
print(labels)
</code>```

Output:

```<code>[[28, 25, 95], [21, 13, 70], [13, 21, 70]]
[1, 2, 3]
</code>```

Body:
I am trying to get data into SAMPLES and LABELS variables from JSON objects which looks like this.

{
"samples": [
    [
        28,
        25,
        95
    ],
    [
        21,
        13,
        70
    ],
    [
        13,
        21,
        70
    ]
],
"labels": [
    1,
    2,
    3
  ]
 }

the code I am using

with open(data, 'r') as d:
complete_data = json.load(d)
for a in complete_data:
    samples = a['samples']
    lables = a['lables']

but its says

samples = a['samples']

TypeError: string indices must be integers

Body:
To get data from 'samples' and 'labels' You don't need to use loop. Try this:

import json

with open('data.json', 'r') as d:
    complete_data = json.load(d)

samples = complete_data['samples']
labels = complete_data['labels']

print(samples)
print(labels)

Output:

[[28, 25, 95], [21, 13, 70], [13, 21, 70]]
[1, 2, 3]


问:
Path mapping in tsconfig is interpreted as an external module
(context : angular 8, node 12.15.0)

EDIT : It seems to be a bug so I opened an issue here

I am building a library. I defined the path @env in tsconfig.json :

```<code>{
  "compilerOptions": {
    [...]
    "paths": {
      "@env/*": [
        "projects/mylib/src/environments/*"
      ]
    }
}
</code>```

And in the code, I reference the environment like this :

```<code>import { environment } from '@env/environment';
</code>```

But it seems that the compiler is misled because when I try to build (ng build my-lib), I get the following warning :

WARNING: No name was provided for external module '@env/environment' in output.globals – guessing 'environment'

Also, importing the module in a project generates this error message at compilation :

```<code>ERROR in The target entry-point "my-lib" has missing dependencies:
 - @env/environment
</code>```

It seems that @env/environment is interpreted as an external module. How can I avoid that ?

Steps to reproduce :

Note : I made a ready-to-use SSCCE here

Create a new project (ng new acme) with simplest options : no routing, plain old CSS for style.

In the project, create a library (ng g generate library my-lib)

under projects/my-lib/src, create a folder environments with 2 files: environment.ts and environments.prod.ts

Configure projects/my-lib/tsconfig.lib.json like this (I just added the paths block):

```<code>{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/lib",
    "target": "es2015",
    "declaration": true,
    "inlineSources": true,
    "types": [],
    "lib": [
      "dom",
      "es2018"
    ],
    "paths": {
      "baseUrl": [ "./" ],
      "@env/*": [ "projects/my-lib/src/environments/*" ]
    }
  },
  "angularCompilerOptions": {
    "skipTemplateCodegen": true,
    "strictMetadataEmit": true,
    "enableResourceInlining": true
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ],
}

</code>```

Project should look like this :

```<code>.
├── angular.json
├── browserslist
├── e2e
│   ├── protractor.conf.js
│   ├── src
│   │   ├── app.e2e-spec.ts
│   │   └── app.po.ts
│   └── tsconfig.json
├── karma.conf.js
├── package.json
├── package-lock.json
├── projects
│   └── my-lib
│       ├── karma.conf.js
│       ├── ng-package.json
│       ├── package.json
│       ├── README.md
│       ├── src
│       │   ├── environments
│       │   │   ├── environment.prod.ts
│       │   │   └── environment.ts
│       │   ├── lib
│       │   │   ├── my-lib.component.spec.ts
│       │   │   ├── my-lib.component.ts
│       │   │   ├── my-lib.module.ts
│       │   │   ├── my-lib.service.spec.ts
│       │   │   └── my-lib.service.ts
│       │   ├── public-api.ts
│       │   └── test.ts
│       ├── tsconfig.lib.json
│       ├── tsconfig.lib.prod.json
│       ├── tsconfig.spec.json
│       └── tslint.json
├── README.md
├── src
│   ├── app
│   │   ├── app.component.css
│   │   ├── app.component.html
│   │   ├── app.component.spec.ts
│   │   ├── app.component.ts
│   │   └── app.module.ts
│   ├── assets
│   ├── environments
│   │   ├── environment.prod.ts
│   │   └── environment.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── polyfills.ts
│   ├── styles.css
│   └── test.ts
├── tsconfig.app.json
├── tsconfig.json
├── tsconfig.spec.json
└── tslint.json
</code>```

Now,

to reproduce the warning, build the library : ng build my-lib

to reproduce the error, import MyLibModule in the main project and build it : ng build

答:
This is the response I got from the angular maintainers here :

Its not recommended to use path mappings for libraries.

And also :

path mappings in a library were never supported, and shouldn’t have ever worked and in your case it seems that they worked because of ts configuration leaking from the library to your application.

So, the conclusion is : DO NOT use path mappings in libraries.

Body:
(context : angular 8, node 12.15.0)

EDIT : It seems to be a bug so I opened an issue here

I am building a library. I defined the path @env in tsconfig.json :

{
  "compilerOptions": {
    [...]
    "paths": {
      "@env/*": [
        "projects/mylib/src/environments/*"
      ]
    }
}

And in the code, I reference the environment like this :

import { environment } from '@env/environment';

But it seems that the compiler is misled because when I try to build (ng build my-lib), I get the following warning :

WARNING: No name was provided for external module '@env/environment' in output.globals – guessing 'environment'

Also, importing the module in a project generates this error message at compilation :

ERROR in The target entry-point "my-lib" has missing dependencies:
 - @env/environment

It seems that @env/environment is interpreted as an external module. How can I avoid that ?

Steps to reproduce :

Note : I made a ready-to-use SSCCE here

Create a new project (ng new acme) with simplest options : no routing, plain old CSS for style.

In the project, create a library (ng g generate library my-lib)

under projects/my-lib/src, create a folder environments with 2 files: environment.ts and environments.prod.ts

Configure projects/my-lib/tsconfig.lib.json like this (I just added the paths block):

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/lib",
    "target": "es2015",
    "declaration": true,
    "inlineSources": true,
    "types": [],
    "lib": [
      "dom",
      "es2018"
    ],
    "paths": {
      "baseUrl": [ "./" ],
      "@env/*": [ "projects/my-lib/src/environments/*" ]
    }
  },
  "angularCompilerOptions": {
    "skipTemplateCodegen": true,
    "strictMetadataEmit": true,
    "enableResourceInlining": true
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ],
}

Project should look like this :

.
├── angular.json
├── browserslist
├── e2e
│   ├── protractor.conf.js
│   ├── src
│   │   ├── app.e2e-spec.ts
│   │   └── app.po.ts
│   └── tsconfig.json
├── karma.conf.js
├── package.json
├── package-lock.json
├── projects
│   └── my-lib
│       ├── karma.conf.js
│       ├── ng-package.json
│       ├── package.json
│       ├── README.md
│       ├── src
│       │   ├── environments
│       │   │   ├── environment.prod.ts
│       │   │   └── environment.ts
│       │   ├── lib
│       │   │   ├── my-lib.component.spec.ts
│       │   │   ├── my-lib.component.ts
│       │   │   ├── my-lib.module.ts
│       │   │   ├── my-lib.service.spec.ts
│       │   │   └── my-lib.service.ts
│       │   ├── public-api.ts
│       │   └── test.ts
│       ├── tsconfig.lib.json
│       ├── tsconfig.lib.prod.json
│       ├── tsconfig.spec.json
│       └── tslint.json
├── README.md
├── src
│   ├── app
│   │   ├── app.component.css
│   │   ├── app.component.html
│   │   ├── app.component.spec.ts
│   │   ├── app.component.ts
│   │   └── app.module.ts
│   ├── assets
│   ├── environments
│   │   ├── environment.prod.ts
│   │   └── environment.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── polyfills.ts
│   ├── styles.css
│   └── test.ts
├── tsconfig.app.json
├── tsconfig.json
├── tsconfig.spec.json
└── tslint.json

Now,

to reproduce the warning, build the library : ng build my-lib

to reproduce the error, import MyLibModule in the main project and build it : ng build


问:
linking error2005 visual studio 2008 c++
I had struct errorStruct & a queue errQueue definition in yacc.y , then moved it to separate .h file

but it gives me linking error that the definition is found in both yacc.obj and node.obj !!

tried creating new solution but still gives the same error

```<code>Error   9   error LNK2005: "class std::queue<struct errorStruct,class std::deque<struct

errorStruct,class std::allocator<struct errorStruct> > > errQueue" (?errQueue@@3V?$queue@UerrorStruct@@V?

$deque@UerrorStruct@@V?$allocator@UerrorStruct@@@std@@@std@@@std@@A) already defined in Node.obj    yacc.obj
</code>```

update

first :

Node.h // for node class

yacc.y // rules + errorStruct + queue errQueue + class ErrList : includes "Node.h" & < queue>

then:

Node.h // for node class + errorStruct + queue errQueue + class ErrList : includes < queue>

yacc.y // rules : includes "Node.h"

update

in Node.h

```<code>struct errorStruct{
            int errLineNum;
            int errColNum ;
            char * errMessage;
    };

class ErrList{

public:
void pushError(int line,int col,char * message);
void popError();
void printErrors();
int getSize();

private :
queue <errorStruct> errQueue;

};
externErrList * se = new ErrList ();
</code>```

the rest of Node.h has nothing to do with this class

in yacc.y just using

se->pushError(...);

and as no declaration of class ErrList or errQueue

答:
opss! I forgot to post the answer .. sorry ..

got it with the help of @Peter K.'s reference  :

go to VS : project ->  property page -> configuration properties -> linker ->command line

and add /FORCE:MULTIPLE in additional options box

Body:
I had struct errorStruct & a queue errQueue definition in yacc.y , then moved it to separate .h file

but it gives me linking error that the definition is found in both yacc.obj and node.obj !!

tried creating new solution but still gives the same error

Error   9   error LNK2005: "class std::queue<struct errorStruct,class std::deque<struct

errorStruct,class std::allocator<struct errorStruct> > > errQueue" (?errQueue@@3V?$queue@UerrorStruct@@V?

$deque@UerrorStruct@@V?$allocator@UerrorStruct@@@std@@@std@@@std@@A) already defined in Node.obj    yacc.obj

update

first :

Node.h // for node class

yacc.y // rules + errorStruct + queue errQueue + class ErrList : includes "Node.h" & < queue>

then:

Node.h // for node class + errorStruct + queue errQueue + class ErrList : includes < queue>

yacc.y // rules : includes "Node.h"

update

in Node.h

struct errorStruct{
            int errLineNum;
            int errColNum ;
            char * errMessage;
    };

class ErrList{

public:
void pushError(int line,int col,char * message);
void popError();
void printErrors();
int getSize();

private :
queue <errorStruct> errQueue;

};
externErrList * se = new ErrList ();

the rest of Node.h has nothing to do with this class

in yacc.y just using

se->pushError(...);

and as no declaration of class ErrList or errQueue


问:
Is there a need to reboot Cloud VPS
I am running a web application on DigitalOcean VPS(CentOS 7) from almost 7-8 months and has never rebooted the VPS. I haven't seen any problem in the working or web application or database or mail server. Do I really need to reboot it?  </p>

答: you need to reboot your server after kernel upgrades or some security patches but generally you will never need to reboot any linux distribution.</p>

Title: Is there a need to reboot Cloud VPS


问:
Install pyspark for beginner
I am currently doing pyspark courses in data camp, and now would like to start trying to build some of my own projects on my own computer using pyspark. However, I am becoming massively confused with the installation of spark/pysaprk itself and how to run it in jypter notebook.

I have looked vids on youtube with regards to install, like edurkea which seems to give an installation by creating a vm machine and connecting it to another which I do not want all I want is to install pysaprk on my laptop locally.

I have also followed the installation instructions from this link :

https://medium.com/@brajendragouda/installing-apache-spark-on-ubuntu-pyspark-on-juputer-ca8e40e8e655

And when I run the command pyspark in my terminal I get the no command response.

I have looked at the documentation on the spark site, which I find not very newbie friendly and was wondering if anyone has a link to an easy to follow guide for this install.

My current OS is ubuntu the latest version, I am just learning at the moment about using shell and bash scripts at the present but it all very new and a lot of the stuff I been looking at is starting to confuse me.

Any links, advice would be much appreactied.

答:
I've tried installing pyspark in several ways, but the easiest way to install was using conda.

If you have anaconda (miniconda) installed on your laptop, try installing as below.

```<code>conda install pyspark
conda install -c anaconda openjdk
#anaconda channel has v.8 and it works best, and do not install from conda-forge for it's version 11 and it crashes
</code>```

Add SPARK_HOME variable : Modify this and copy paste it into .bashrc file.

export SPARK_HOME="/Users/YOUR_USER_NAME/miniconda3/lib/python3.7/site-packages/pyspark"

This worked for me. You probably want to install findspark which can be found in conda easily.

Title: Install pyspark for beginner

Body:
I've tried installing pyspark in several ways, but the easiest way to install was using conda.

If you have anaconda (miniconda) installed on your laptop, try installing as below.

conda install pyspark
conda install -c anaconda openjdk
#anaconda channel has v.8 and it works best, and do not install from conda-forge for it's version 11 and it crashes

Add SPARK_HOME variable : Modify this and copy paste it into .bashrc file.

export SPARK_HOME="/Users/YOUR_USER_NAME/miniconda3/lib/python3.7/site-packages/pyspark"

This worked for me. You probably want to install findspark which can be found in conda easily.