问:
Cannot connect to SQL Server remotely or locally after reboot
After some network maintenance last weekend, we had some trouble with our development server which led to us restart it. Some updates were installed during the restart, which may or may not have been a factor. Since then, we have been unable to connect to SQL Server 2005, even locally via Management Studio. Depending on the protocol used for the connection attempt, we get one of the following two errors:

When you try to connect to the instance by using the named pipes protocol or the shared memory protocol, you receive the following error message:

No process is on the other end of the pipe.

When you try to connect to the instance by using the TCP/IP protocol, you receive the following error message:

An existing connection was forcibly closed by the remote host.

The aforementioned protocols are all enabled, and the SQL services are all running happily (apart from the SQL Server Agent, which cannot connect to SQL Server either). We also checked the Surface Area Configuration tool to ensure it accepts connections.

It's not a certificates problem (as seen online) as we don't use encrypted connections.

Any suggestions? Otherwise we will probably resort to a full reinstall.

** UPDATE **

Further clues:

We can connect to Integration Services, but nothing else

We can connect to the instance of SQL Server Embedded Edition running on the same server

答:
When I said "It's not a certificates problem (as seen online) as we don't use encrypted connections", I was wrong.

Apparently, some old SSL certificates we had on the server were causing these problems, even though we didn't appear to use them. I still don't know why, but deleting them (and then uninstalling them from IIS) fixed our problem.

Thanks very much for everyone's help!

OwnerDisplayName: dev

LastEditorDisplayName: Jarrod Dixon

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
Multiple vertex types in JUNG
I need to make a graph that will support multiple vertex types (3 to be exact) and I've been trying to find an example that does this with JUNG except I can seem to find one.  Does anyone know of any examples that do this that I can look at?  And anything that places the different vertices using different mouse clicks would be awesome as well (ie left click to place a vertex of type 1, shift left click to place a vertex of type 2, etc).  Thanks.</p>

答:
You've basically got two options:

(1)

```<code>Graph<V extends YourVertexSuperClass, E>
</code>```

In this case I'm assuming you've got something like

```<code>public interface YourVertexSuperClass { ... }
public class Car implements YourVertexSuperClass { ... }
public class Person implements YourVertexSuperClass { ... }
</code>```

etc.

(The interface could be an abstract class, of course.)

This probably only really makes sense if your vertex types have something in common.

(2)

```<code>Graph<? extends Object, E>
</code>```

In this case you can put anything in, i.e., no type restrictions.

ContentLicense: CC BY-SA 3.0

Title: Multiple vertex types in JUNG

Body:
You've basically got two options:

(1)

Graph<V extends YourVertexSuperClass, E>

In this case I'm assuming you've got something like

public interface YourVertexSuperClass { ... }
public class Car implements YourVertexSuperClass { ... }
public class Person implements YourVertexSuperClass { ... }

etc.

(The interface could be an abstract class, of course.)

This probably only really makes sense if your vertex types have something in common.

(2)

Graph<? extends Object, E>

In this case you can put anything in, i.e., no type restrictions.


问:
Same class in multiple files
Just for some practice, I'm looking at the different ways classes can be used within C++.

I've created the following project, which all I want to do is simply just ensure the same 'instance' of a class is being used across the project.

For example, I have main.cpp which has basic functionality which allows the user to set their health value. In path_one.cpp, I want to call the same class and display the same value as it does in main.cpp.

Here is the code for each file;

main.cpp

```<code>#include <iostream>
#include "player_class.h"
#include "path_one.h"
using namespace std;

int main()
{
    int set_health;
    Player player;
    cout << "Your Health is: " << player.health;

    cout << "\nSet your health:  ";
    cin >> set_health;
    player.health = set_health;
    cout << "Your Health is now: " << player.health;

    path_one();

    return 0;
}

</code>```

player_class.h

```<code>#pragma once

class Player
{
public:
    int health;
    int attack;
    int strength;
    int defence;

    Player()
    {
        health = 0;
        attack = 0;
        strength = 0;
        defence = 0;
    }
};
</code>```

path_one.cpp

```<code>#include <iostream>
#include "player_class.h"
#include "path_one.h"
using namespace std;

void path_one()
{
    Player player;

    printf("\n\nYour Health is: %d", player.health);
}
</code>```

path_one.h

```<code>#pragma once
#include "player_class.h"
#include "player_class.h"

void path_one();
</code>```

Once the 'Health' is set, and then goes into the path_one();, is to have it display the same value for health, rather than 'redefine' the class and display 0.

答:
Tow different objects of the type Player with the automatic storage duration are created in the function main and path_one.

Objects of the same class can share their static data members.

So if the data member health would be declared with the storage specifier static

```<code>static int health;
</code>```

then you would get the expected result that the both functions deal with the same object health.

Do not forget to defined the static data member outside the class in some cpp file. For example

```<code>int Player::helth;
</code>```

Otherwise you need one object with the external linkage that will be accessed in main and path_one.

For example in the header you could declare

```<code>extern Player player;
</code>```

and then in one of cpp files define it

```<code>Player player;
</code>```

If the compiler supports C++ 17 then you could in the header just write

```<code>inline Player player;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Same class in multiple files

Body:
Just for some practice, I'm looking at the different ways classes can be used within C++.

I've created the following project, which all I want to do is simply just ensure the same 'instance' of a class is being used across the project.

For example, I have main.cpp which has basic functionality which allows the user to set their health value. In path_one.cpp, I want to call the same class and display the same value as it does in main.cpp.

Here is the code for each file;

main.cpp

#include <iostream>
#include "player_class.h"
#include "path_one.h"
using namespace std;

int main()
{
    int set_health;
    Player player;
    cout << "Your Health is: " << player.health;

    cout << "\nSet your health:  ";
    cin >> set_health;
    player.health = set_health;
    cout << "Your Health is now: " << player.health;

    path_one();

    return 0;
}

player_class.h

#pragma once

class Player
{
public:
    int health;
    int attack;
    int strength;
    int defence;

    Player()
    {
        health = 0;
        attack = 0;
        strength = 0;
        defence = 0;
    }
};

path_one.cpp

#include <iostream>
#include "player_class.h"
#include "path_one.h"
using namespace std;

void path_one()
{
    Player player;

    printf("\n\nYour Health is: %d", player.health);
}

path_one.h

#pragma once
#include "player_class.h"
#include "player_class.h"

void path_one();

Once the 'Health' is set, and then goes into the path_one();, is to have it display the same value for health, rather than 'redefine' the class and display 0.

Body:
Tow different objects of the type Player with the automatic storage duration are created in the function main and path_one.

Objects of the same class can share their static data members.

So if the data member health would be declared with the storage specifier static

static int health;

then you would get the expected result that the both functions deal with the same object health.

Do not forget to defined the static data member outside the class in some cpp file. For example

int Player::helth;

Otherwise you need one object with the external linkage that will be accessed in main and path_one.

For example in the header you could declare

extern Player player;

and then in one of cpp files define it

Player player;

If the compiler supports C++ 17 then you could in the header just write

inline Player player;


问:
Typescript: Pick only one of union
I have this Query type with getBankAccounts property:

export type Query = {
  getBankAccounts: GetBankAccountsResponseOrUserInputRequest,
};
```

But it returns either a GetAccountsResponse or a UserInputRequest:

export type GetBankAccountsResponseOrUserInputRequest = GetAccountsResponse | UserInputRequest;

I'm looking to Pick<Query, "getBankAccounts"> only the response type of: GetAccountsResponse.

Your help is very much appreciated.

答:
```<code>type BankAccountQuery = Pick<Query, Exclude<keyof Query, 'getBankAccounts'>> & { getBankAccounts: GetAccountsResponse }
</code>```

Or you can use an Overwrite helper:

```<code>type Overwrite<T, U extends { [K in keyof T]?: any }> = U & Pick<T, Exclude<keyof T, keyof U>>;
type BankAccountQuery = Overwrite<Query, {getBankAccounts: GetAccountsResponse }>;
</code>```

Note that this will pick any additional field of Query type (if there's any). If you only want to pick exactly one field maybe you can simply declare another type?

```<code>type BankAccountQuery = {
  getBankAccounts: GetAccountsResponse;
}
</code>```

Typescript Playground

Title: Typescript: Pick only one of union

Body:
I have this Query type with getBankAccounts property:

export type Query = {
  getBankAccounts: GetBankAccountsResponseOrUserInputRequest,
};

But it returns either a GetAccountsResponse or a UserInputRequest:

export type GetBankAccountsResponseOrUserInputRequest = GetAccountsResponse | UserInputRequest;

I'm looking to Pick<Query, "getBankAccounts"> only the response type of: GetAccountsResponse.

Your help is very much appreciated.

Body:
type BankAccountQuery = Pick<Query, Exclude<keyof Query, 'getBankAccounts'>> & { getBankAccounts: GetAccountsResponse }

Or you can use an Overwrite helper:

type Overwrite<T, U extends { [K in keyof T]?: any }> = U & Pick<T, Exclude<keyof T, keyof U>>;
type BankAccountQuery = Overwrite<Query, {getBankAccounts: GetAccountsResponse }>;

Note that this will pick any additional field of Query type (if there's any). If you only want to pick exactly one field maybe you can simply declare another type?

type BankAccountQuery = {
  getBankAccounts: GetAccountsResponse;
}

<a href="https://www.typescriptlang.org/play/#code/C4TwDgpgBA4hwEEDGSD2BXAdsAzgJQhzFUx2gF4oBvAKCnqgGsBLTAEwC4oByORFDNnyFipCNwDcdBgCcRXHMBmsA5lIC+NGqEhQAqmRkBJTGHTACAR3SFgUSrQZNWnHgYjHT5qzcWTp9HKWCkqqGlo60HwAQgCGmIzIaFi4BEQkZADyMu6eZhYQ1rb2sPBJgqkiGdAAPvqGJvk+tlLa4NAAijYyICWODCrwcQnlKThcMfGJAmNpolk5DV4FRYpSTnJEAMKobBBcmOgAtgBGHuE0APSXUADuzMAAFhh2mQBuHrfKwBBtusPTZLYLoeEAARhKAAVmEhGAAeEE9AA0UAAogAPJAAG3QezhjAgIFQADMoIiQCjuINgADRkJuAA+BlQABk1Cg1NpMyEEzK3Mq6TEUE0NDQpDsbFiwFiYK4XKBwHJEIcASgmzAOz2XDBACYAMxI1WcqZ03BcfpOegsdhcXh8hXCQVkbiGy2yeQ8AAqtm4qs0Iuudwejyg70+31+kVDHxkXweEDhnpReigEHRP3YOHZAG0ANJQVhMQkkqCegC6AH4uPFeupmZQU2zobDEyiMdjcQmCUTSUmiz39EypFH5RVyTqSmHYxGEd0KezjSN+eNSvwHXNqsKGa0xYooJLpTq5Sb+eO+qr1Zr9lBdQajUMTw7zaqnNbXHa1xVHfNxK63WqPW4b0-D9GgRSAA" rel="nofollow noreferrer">Typescript Playground


问:
A cumulative sum of consecutive workdays that resets to 1 when consecutive days = 0, per ID
I have 3 columns:

Employee ID(numerical)

Day of work(a date yyyy-mm-dd when employee had a shift)

is_consecutive_work_day (1 if days of work are consecutive, else 0)

I need a 4th: Consecutive_work_days (a cumulative sum of is_consecutive_work_day, which resets to 1 when is_consecutive_work_day = 0). So this will go to a maximum of 5 for any employee id. Some will have 1,2,3 others 1,2...etc.

What am failing to figure out is how to write the 4th column (consecutive_work_days). Not how to write a consecutive sum per employee id, but specifically how to reset to 1 when is_consecutive_work_day = 0 per employee id.

May I ask for your help regarding this 4th column please? Thanks.

答:
You can use window functions. lag() lets you access the previous day_of_work for the same employee, which you can compare to the current day_of_work: if there is a one day difference, then you can set is_consecutive_work_day to 1.

```<code>select
    employee_id,
    day_of_work,
    case
        when day_of_work
            = lag(day_of_work) over(partition by employee_id order by day_of_work)
                + interval 1 day
        then 1
        else 0
    end is_consecutive_work_day
from mytable
</code>```

To compute the cumulative sum, it is a bit more complicated. We can use some gaps-and-island technique to put each record in the group it belongs to: basically, everytime is_consecutive_work_day of 0 is met, a new group starts; we can then do a window sum() over each group:

```<code>select
    employee_id,
    day_of_work,
    is_consecutive_work_day,
    sum(is_consecutive_work_day)
        over(partition by employee_id, grp order by day_of_work)
        consecutive_work_days
from (
    select
        t.*,
        sum(1 - is_consecutive_work_day) over(partition by employee_id order by day_of_work)  grp
    from (
        select
            t.*,
            case
                when day_of_work
                    = lag(day_of_work) over(partition by employee_id order by day_of_work)
                        + interval 1 day
                then 1
                else 0
            end is_consecutive_work_day
        from mytable t
    ) t
) t
</code>```

Body:
You can use window functions. lag() lets you access the previous day_of_work for the same employee, which you can compare to the current day_of_work: if there is a one day difference, then you can set is_consecutive_work_day to 1.

select
    employee_id,
    day_of_work,
    case
        when day_of_work
            = lag(day_of_work) over(partition by employee_id order by day_of_work)
                + interval 1 day
        then 1
        else 0
    end is_consecutive_work_day
from mytable

To compute the cumulative sum, it is a bit more complicated. We can use some gaps-and-island technique to put each record in the group it belongs to: basically, everytime is_consecutive_work_day of 0 is met, a new group starts; we can then do a window sum() over each group:

select
    employee_id,
    day_of_work,
    is_consecutive_work_day,
    sum(is_consecutive_work_day)
        over(partition by employee_id, grp order by day_of_work)
        consecutive_work_days
from (
    select
        t.*,
        sum(1 - is_consecutive_work_day) over(partition by employee_id order by day_of_work)  grp
    from (
        select
            t.*,
            case
                when day_of_work
                    = lag(day_of_work) over(partition by employee_id order by day_of_work)
                        + interval 1 day
                then 1
                else 0
            end is_consecutive_work_day
        from mytable t
    ) t
) t


问:
Is there a non-recursive solution to get a list of all possible concatenations of array of strings?
I receive as an input an array of strings.

I have to create a list of strings that are a concatenation of all the strings of the input array, appearing once and only once for each string.

For example if the input array is ["aa","bb","cc"] the resulting list of strings will be "aabbcc",aaccbb","bbaacc","bbccaa",ccaabb","ccbbaa"

The length of the input array is not known, it can be any number.

The length of all the substrings in the array is the same.

I see this Java: get all concatenations of List<List<String>> question.

But are there any non-recursive solution for this?

答:
I just wrote an example which does the same with integer numbers: Get all combinations for arbitrary number of elements

You can simply replace int[] by String[] there.

A complete interactive example:

```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

class Main
{

    /**
     * Return all possible combination of n Strings
     * @param n Number of parts to combine in each row
     * @param set Array of Strings to combine
     */
    static List<String[]> getAll(int n, String[] set)
    {
        List<String[]> combinations = new ArrayList<>();

        // First step (0)
        // Create initial combinations, filled with the first String.
        for (int number = 0; number < set.length; number++)
        {
            String[] array = new String[n]; // the final size of each array is already known
            array[0] = set[number]; // fill the first Part
            combinations.add(array);
        }

        // In each following step, we add one number to each combination
        for (int step = 1; step < n; step++)
        {
            // Backup the size because we do not want to process
            // the new items that are added by the following loop itself.
            int size = combinations.size();

            // Add one number to the existing combinations
            for (int combination = 0; combination < size; combination++)
            {
                // Add one part to the existing array
                String[] array = combinations.get(combination);
                array[step] = set[0];

                // For all additional Strings, create a copy of the array
                for (int number = 1; number < set.length; number++)
                {
                    String[] copy = Arrays.copyOf(array, array.length);
                    copy[step] = set[number];
                    combinations.add(copy);
                }
            }
        }

        return combinations;
    }

    public static void main(String[] args)
    {
        System.out.println("Enter some Strings, delimited by space");
        Scanner in=new Scanner(System.in);
        String line=in.nextLine();
        String[] set=line.split("\\s+");

        // Calculate all possible combinations
        List<String[]> combinations = getAll(set.length, set);

        // Print the result
        for (String[] combination : combinations)
        {
            System.out.println(Arrays.toString(combination));
        }
    }
}
</code>```

Outputs:

```<code>Enter some Strings, delimited by space
aa bb cc
[aa, aa, aa]
[bb, aa, aa]
[cc, aa, aa]
[aa, bb, aa]
[aa, cc, aa]
[bb, bb, aa]
[bb, cc, aa]
[cc, bb, aa]
[cc, cc, aa]
[aa, aa, bb]
[aa, aa, cc]
[bb, aa, bb]
[bb, aa, cc]
[cc, aa, bb]
[cc, aa, cc]
[aa, bb, bb]
[aa, bb, cc]
[aa, cc, bb]
[aa, cc, cc]
[bb, bb, bb]
[bb, bb, cc]
[bb, cc, bb]
[bb, cc, cc]
[cc, bb, bb]
[cc, bb, cc]
[cc, cc, bb]
[cc, cc, cc]
</code>```

To change the output format, you may use:

```<code>        // Print the result
        for (String[] combination : combinations)
        {
            String s=String.join("",combination); // Concatenate the parts of each combination
            System.out.println(s);
        }
</code>```

The the output format is:

```<code>aaaaaa
bbaaaa
ccaaaa
aabbaa
...
</code>```

Please take a look at the linked topic to find the explanation how it works.

Body:
I just wrote an example which does the same with integer numbers: Get all combinations for arbitrary number of elements

You can simply replace int[] by String[] there.

A complete interactive example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

class Main
{

    /**
     * Return all possible combination of n Strings
     * @param n Number of parts to combine in each row
     * @param set Array of Strings to combine
     */
    static List<String[]> getAll(int n, String[] set)
    {
        List<String[]> combinations = new ArrayList<>();

        // First step (0)
        // Create initial combinations, filled with the first String.
        for (int number = 0; number < set.length; number++)
        {
            String[] array = new String[n]; // the final size of each array is already known
            array[0] = set[number]; // fill the first Part
            combinations.add(array);
        }

        // In each following step, we add one number to each combination
        for (int step = 1; step < n; step++)
        {
            // Backup the size because we do not want to process
            // the new items that are added by the following loop itself.
            int size = combinations.size();

            // Add one number to the existing combinations
            for (int combination = 0; combination < size; combination++)
            {
                // Add one part to the existing array
                String[] array = combinations.get(combination);
                array[step] = set[0];

                // For all additional Strings, create a copy of the array
                for (int number = 1; number < set.length; number++)
                {
                    String[] copy = Arrays.copyOf(array, array.length);
                    copy[step] = set[number];
                    combinations.add(copy);
                }
            }
        }

        return combinations;
    }

    public static void main(String[] args)
    {
        System.out.println("Enter some Strings, delimited by space");
        Scanner in=new Scanner(System.in);
        String line=in.nextLine();
        String[] set=line.split("\\s+");

        // Calculate all possible combinations
        List<String[]> combinations = getAll(set.length, set);

        // Print the result
        for (String[] combination : combinations)
        {
            System.out.println(Arrays.toString(combination));
        }
    }
}

Outputs:

Enter some Strings, delimited by space
aa bb cc
[aa, aa, aa]
[bb, aa, aa]
[cc, aa, aa]
[aa, bb, aa]
[aa, cc, aa]
[bb, bb, aa]
[bb, cc, aa]
[cc, bb, aa]
[cc, cc, aa]
[aa, aa, bb]
[aa, aa, cc]
[bb, aa, bb]
[bb, aa, cc]
[cc, aa, bb]
[cc, aa, cc]
[aa, bb, bb]
[aa, bb, cc]
[aa, cc, bb]
[aa, cc, cc]
[bb, bb, bb]
[bb, bb, cc]
[bb, cc, bb]
[bb, cc, cc]
[cc, bb, bb]
[cc, bb, cc]
[cc, cc, bb]
[cc, cc, cc]

To change the output format, you may use:

        // Print the result
        for (String[] combination : combinations)
        {
            String s=String.join("",combination); // Concatenate the parts of each combination
            System.out.println(s);
        }

The the output format is:

aaaaaa
bbaaaa
ccaaaa
aabbaa
...

Please take a look at the linked topic to find the explanation how it works.


问:
How to expand access modifiers for virtual members in a derived class?
I learned Java before I learned C#, and I've typically found C# to give me more freedom as a programmer than Java does, and that's why I really like it. I'm a bit baffled though by a problem I'm currently running into concerning access modifiers. Say I have a class.

public class Foo
{
    public virtual int SomeProperty { get; protected set; }
}
```

<p>And another derived class.</p>

<pre class="lang-cs prettyprint-override"><code>public class Bar : Foo
{
    public override int SomeProperty { get; set; }
}

</code>```

The compiler throws an error saying

CS0507 'Bar.SomeProperty.set': cannot change access modifiers when overriding 'protected' inherited member 'Foo.SomeProperty.set'

Why is this a thing? In Java, I am allowed to expand access to base members by overriding them in derived classes, just not the other way around. (Read: You cannot restrict base members further in derived classes) Am I missing something here or doing something stupid I don't know about?

I know I could declare public new SomeProperty { get; set; }, but that's not what I want. I want polymorphism here.

Please enlighten me. Thank you.

答:
You could hide the base class property and provide a setter there. In essence, the signature of the class will become exactly how you want it to be, albeit as a sort of workaround.</p>

```<code>public class Bar : Foo
{
    public new int SomeProperty
    {
        get => base.SomeProperty;
        set => base.SomeProperty = value;
    }
}
</code>```

Body:
I learned Java before I learned C#, and I've typically found C# to give me more freedom as a programmer than Java does, and that's why I really like it. I'm a bit baffled though by a problem I'm currently running into concerning access modifiers. Say I have a class.

public class Foo
{
    public virtual int SomeProperty { get; protected set; }
}

And another derived class.

public class Bar : Foo
{
    public override int SomeProperty { get; set; }
}

The compiler throws an error saying

CS0507 'Bar.SomeProperty.set': cannot change access modifiers when overriding 'protected' inherited member 'Foo.SomeProperty.set'

Why is this a thing? In Java, I am allowed to expand access to base members by overriding them in derived classes, just not the other way around. (Read: You cannot restrict base members further in derived classes) Am I missing something here or doing something stupid I don't know about?

I know I could declare public new SomeProperty { get; set; }, but that's not what I want. I want polymorphism here.

Please enlighten me. Thank you.

Body:
You could hide the base class property and provide a setter there. In essence, the signature of the class will become exactly how you want it to be, albeit as a sort of workaround.

public class Bar : Foo
{
    public new int SomeProperty
    {
        get => base.SomeProperty;
        set => base.SomeProperty = value;
    }
}


问:
Learning WPF without success
Hello developers and designers,

I am very willing to learn WPF in which i use C# as the logic code.
Or i 'try' to anyway.

I have written a 2-page long code-behind in Forms-style though, so i know some syntaxes.
But that was a really cumbersome way of doing it.

The problem is that i am still lingering around the area of understanding at least the basic concept of object oriented programming. But 9 out of 10 times i am not getting the example-codes entirely because of that '1 little thing of which i don't even know what it's called'.
How do you even know if there is a command for the function you want to express and more importantly.... how it's called and where it located in what namespace?

Even the best video-examples aren't doing it for me, because when any code is typed, they never explain how the code exactly works. And most of the times it just doesn't even add up to what i know of logic code (of course i'm wrong).

In the early days i learned the Commodore64's Basic no problem.
Learning and writing Actionscript (Flash), within 2 months creating a 2D-shoot'em up
Learning and writing CMD, within 3 months writing 5000+ lines of code for all sorts of functions.

Why in Merlin's beard is WPF so hard?
Watching the "simplest" tutorial-video's are becoming more and more de-motivational.

Anyone recognizes this?

Thanks for reading,
Danny

答:
MVVM: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Learn it then use it.

Title: Learning WPF without success


问:
Observing System Volume Changes OSX - Swift
I'm trying to execute a method when the system volume changes.

I've tried using
DistributedNotificationCenter.default().addObserver(self,selector: #selector(volumeChanged(_:)),name: NSNotification.Name(rawValue: "com.apple.sound.settingsChangedNotification"),object: nil) but it didn't work.

Well, it does work. But only if the System Preferences app is open.

What's the right way to accomplish this task?

Ps: note that it's on MacOS, not iOS

答:
After trying countless ways I found a nice workaround: instead of searching for a probably non-existent notification, I try to get the physical key-press event.
As the media keys are not sending a normal CGEvent I came up with this solution: Capture OSX media control buttons in Swift

Note that the TouchBar simulates such a key event, so any app that you'll write using this method will also work for those MacBook models which have the TouchBar.

It's probably not the ideal solution, but it works. If anyone knows a better way please let me know.


问:
How to programmatically create symlinks in ddev?
A site (no composer, else I'd do it there) has a few symlinks inside the container that are required for it to work.
How do I tell ddev to create those symlinks on ddev start?

I'm sure it's right before my eyes, but I don't find it. Google gives me nothing, maybe the answer is too obvious? Do a ln -s on first run?

答:
First,  I would probably create the symlink in my repo and check it into git. This would have problems on Windows (but symlinks in general are risky on Windows).

You'll want to use relative symlinks so that the relative path can be followed either inside the container or on the host.

So, use a post-start hook with exec (to do it inside the web container) if you have to:

```<code>hooks:
  post-start:
  - exec: ln -sf ../vendor/bin/behat behat
</code>```

Or (especially if you're not on Windows) you could also do it on the host with either a pre-start or post-start hook:

```<code>hooks:
  pre-start:
  - exec-host: ln -sf ../vendor/bin/behat behat
</code>```

Beware that the default directory for exec in the web container is not necessarily the project root, it may be the docroot (as it is with Drupal).

Body:
First,  I would probably create the symlink in my repo and check it into git. This would have problems on Windows (but symlinks in general are risky on Windows).

You'll want to use relative symlinks so that the relative path can be followed either inside the container or on the host.

So, use a post-start hook with exec (to do it inside the web container) if you have to:

hooks:
  post-start:
  - exec: ln -sf ../vendor/bin/behat behat

Or (especially if you're not on Windows) you could also do it on the host with either a pre-start or post-start hook:

hooks:
  pre-start:
  - exec-host: ln -sf ../vendor/bin/behat behat

Beware that the default directory for exec in the web container is not necessarily the project root, it may be the docroot (as it is with Drupal).


问:
How does malloc() know you want to use the block of memory it supplies as an array?
If malloc() returns a pointer to a single block of memory, how can it be used to store multiple values contiguously and allow access to each one using the subscript operator, acting as a pointer to an array?

If I were to try and change the "second element" of an integer by subscripting its address, it would cause undefined behaviour. As malloc() returns the pointer to a single block of memory, shouldn't the pointer it returns refer to the entire block, and thus subscripting it should access the garbage value next to it in memory?

Furthermore, the allocated memory can also be used to store a single value, but only up to the size of the type the pointer is cast to, not to that of the allocated block of memory.

Is all this something to do with the type the pointer is cast to after being returned? Could someone point me in the right direction?

答: But be careful, if you use malloc several times it will return memory allocated in different parts of heap. So you can't move around from one array to another. </p>


问:
Specifying a lambda function as default argument
How do I assign a lambda as default argument? I would like to do this:

```<code>int foo(int i, std::function<int(int)> f = [](int x) -> int { return x / 2; })
{
    return f(i);
}
</code>```

but my compiler (g++ 4.6 on Mac OS X) complains:

```<code>error: local variable 'x' may not appear in this context
</code>```

EDIT:
Indeed, this was a compiler bug. The above code works fine with a recent version of gcc (4.7-20120225).

答:
You could use overloading:</p>

```<code>int foo(int i)
{
    return foo(i, [](int x) -> int { return x / 2; });
}

int foo(int i, std::function<int(int)> f)
{
    return f(i);
}
</code>```

Body:
How do I assign a lambda as default argument? I would like to do this:

int foo(int i, std::function<int(int)> f = [](int x) -> int { return x / 2; })
{
    return f(i);
}

but my compiler (g++ 4.6 on Mac OS X) complains:

error: local variable 'x' may not appear in this context

EDIT:
Indeed, this was a compiler bug. The above code works fine with a recent version of gcc (4.7-20120225).

Body:
You could use overloading:

int foo(int i)
{
    return foo(i, [](int x) -> int { return x / 2; });
}

int foo(int i, std::function<int(int)> f)
{
    return f(i);
}


问:
Binding derived class method in C++ to be called from separated std::function variable, outside the scope of the instance
Consider having a base class that is inherited by multiple sub-classes.

Is it possible to bind some of its methods to create function that can be called directly and not from the inherited class instance.

The following example should emphasis the case :

```<code>
class A {
    virtual void method(int a, int b) { ... }
};

class B : public A {
    virtual void method(int a, int b) { ... }
};
class C : public A {
    virtual void method(int a, int b) { ... }
};

void main () {

    A * a = new B();
    A * aa= new C();

    std::function<void(int,int)> f1 = std::bind(&A::method, &a);
    std::function<void(int,int)> f2 = std::bind(&A::method, &aa);

    f(1,2);
    f(2,3);
    ...
}

</code>```

however, it doesn't compile due to the following error :

No viable conversion from '__bind<void (A::*)(int, int), A **>' to 'std::function<void (int, int)>'

Perhaps anybody can help me fix it ?

答:
There are a few issues with your code.

You need to make the methods public

void main() comes from a time of pre-standardization, it's not valid C++ code. You need int main()

don't use raw pointers that have ownership. use smart pointers.

don't use std::bind. Use lambdas. They are superior in every way.

In order to not overload you with all the changes, lets do this with lambdas and keep the raw pointers:

```<code>int main ()
{
    A * a = new B();
    A * aa= new C();

    std::function<void(int,int)> f1 = [=](int p1, int p2) { return a->method(p1, p2); };
    std::function<void(int,int)> f2 = [=](int p1, int p2) { return aa->method(p1, p2); };

    f1(1, 2);
    f2(2, 3);
}
</code>```

And now a variant with smart pointers. If your f1 and f2 don't live beyond a and aa you can do this:

```<code>void test()
{
    std::unique_ptr<A> a = std::make_unique<B>();
    std::unique_ptr<A> aa = std::make_unique<C>();

    std::function<void(int,int)> f1 = [ptr = a.get()](int p1, int p2) { return ptr->method(p1, p2); };
    std::function<void(int,int)> f2 = [ptr = aa.get()](int p1, int p2) { return ptr->method(p1, p2); };

    f1(1, 2);
    f2(2, 3);
}
</code>```

Else you need to use shared_ptr:

```<code>void test_shared()
{
    std::shared_ptr<A> a = std::make_shared<B>();
    std::shared_ptr<A> aa = std::make_shared<C>();

    std::function<void(int,int)> f1 = [=](int p1, int p2) { return a->method(p1, p2); };
    std::function<void(int,int)> f2 = [=](int p1, int p2) { return aa->method(p1, p2); };

    f1(1, 2);
    f2(2, 3);
}
</code>```

Also if you don't need the type erasure of std::function you should make f1 and f2 lambdas. E.g. auto f1 = [=] ...

Body:
Consider having a base class that is inherited by multiple sub-classes.

Is it possible to bind some of its methods to create function that can be called directly and not from the inherited class instance.

The following example should emphasis the case :

class A {
    virtual void method(int a, int b) { ... }
};

class B : public A {
    virtual void method(int a, int b) { ... }
};
class C : public A {
    virtual void method(int a, int b) { ... }
};

void main () {

    A * a = new B();
    A * aa= new C();

    std::function<void(int,int)> f1 = std::bind(&A::method, &a);
    std::function<void(int,int)> f2 = std::bind(&A::method, &aa);

    f(1,2);
    f(2,3);
    ...
}

however, it doesn't compile due to the following error :

No viable conversion from '__bind<void (A::*)(int, int), A **>' to 'std::function<void (int, int)>'

Perhaps anybody can help me fix it ?

Body:
There are a few issues with your code.

You need to make the methods public

void main() comes from a time of pre-standardization, it's not valid C++ code. You need int main()

don't use raw pointers that have ownership. use smart pointers.

don't use std::bind. Use lambdas. They are superior in every way.

In order to not overload you with all the changes, lets do this with lambdas and keep the raw pointers:

int main ()
{
    A * a = new B();
    A * aa= new C();

    std::function<void(int,int)> f1 = [=](int p1, int p2) { return a->method(p1, p2); };
    std::function<void(int,int)> f2 = [=](int p1, int p2) { return aa->method(p1, p2); };

    f1(1, 2);
    f2(2, 3);
}

And now a variant with smart pointers. If your f1 and f2 don't live beyond a and aa you can do this:

void test()
{
    std::unique_ptr<A> a = std::make_unique<B>();
    std::unique_ptr<A> aa = std::make_unique<C>();

    std::function<void(int,int)> f1 = [ptr = a.get()](int p1, int p2) { return ptr->method(p1, p2); };
    std::function<void(int,int)> f2 = [ptr = aa.get()](int p1, int p2) { return ptr->method(p1, p2); };

    f1(1, 2);
    f2(2, 3);
}

Else you need to use shared_ptr:

void test_shared()
{
    std::shared_ptr<A> a = std::make_shared<B>();
    std::shared_ptr<A> aa = std::make_shared<C>();

    std::function<void(int,int)> f1 = [=](int p1, int p2) { return a->method(p1, p2); };
    std::function<void(int,int)> f2 = [=](int p1, int p2) { return aa->method(p1, p2); };

    f1(1, 2);
    f2(2, 3);
}

Also if you don't need the type erasure of std::function you should make f1 and f2 lambdas. E.g. auto f1 = [=] ...


问:
java streams: easiest way to find adjacent value match
How would it be possible to convert this iterative block of code to streams?</p>

```<code>Integer prev = -1;
boolean adjacentPair = false;

for(Integer num : numberList) {
    if (num.equals(prev)) {
        adjacentNumberSame = true;
        break;
    }
    prev = num;
}
return adjacentNumberSame
</code>```

答:
You don't need to do all of that. Implement this for the body of your method:

```<code>return numberList.contains(prev);
</code>```

For example, you could have:

```<code>public boolean adjacentNumberIsSame(int currentValue, ArrayList<Integer> numberList){
    return numberList.contains(currentValue);
}
</code>```

Body:
How would it be possible to convert this iterative block of code to streams?

Integer prev = -1;
boolean adjacentPair = false;

for(Integer num : numberList) {
    if (num.equals(prev)) {
        adjacentNumberSame = true;
        break;
    }
    prev = num;
}
return adjacentNumberSame

Body:
You don't need to do all of that. Implement this for the body of your method:

return numberList.contains(prev);

For example, you could have:

public boolean adjacentNumberIsSame(int currentValue, ArrayList<Integer> numberList){
    return numberList.contains(currentValue);
}


问:
How can I add alarm type and sound in swift
I want to add alarm, and I want to add custom sound and add alarm type to audio. I tried but not getting the answer. Can any one help me out please ?</p>

```<code>func createReminder() {
    let calander = Calendar.current
    let warmane = calander.date(byAdding: .minute, value: 1, to: Date())

    let reminder = EKReminder(eventStore: self.eventStore)
    reminder.title = "Go to the store and buy milk"
    reminder.calendar = eventStore.defaultCalendarForNewReminders()

    let date = warmane
    let alarm = EKAlarm(absoluteDate: date!)

    reminder.addAlarm(alarm)

    do {
        try eventStore.save(reminder,
            commit: true)

    } catch let error {
            print("Reminder failed with error \(error.localizedDescription)")
    }
}
</code>```

答:
```<code>Try this
let content = UNMutableNotificationContent()
    content.title = "Notification Tutorial"
    content.subtitle = "from ioscreator.com"
    content.body = " Notification triggered"
    //Default sound
    content.sound = UNNotificationSound.default
    //Play custom sound
    content.sound = UNNotificationSound.init(named:UNNotificationSoundName(rawValue: "123.mp3"))

------
</code>```

Body:
I want to add alarm, and I want to add custom sound and add alarm type to audio. I tried but not getting the answer. Can any one help me out please ?

func createReminder() {
    let calander = Calendar.current
    let warmane = calander.date(byAdding: .minute, value: 1, to: Date())

    let reminder = EKReminder(eventStore: self.eventStore)
    reminder.title = "Go to the store and buy milk"
    reminder.calendar = eventStore.defaultCalendarForNewReminders()

    let date = warmane
    let alarm = EKAlarm(absoluteDate: date!)

    reminder.addAlarm(alarm)

    do {
        try eventStore.save(reminder,
            commit: true)

    } catch let error {
            print("Reminder failed with error \(error.localizedDescription)")
    }
}


问:
How to automatically scale down a 100% div without showing browser vertical scrollbars?
I have a table with three rows. I have 1 main #container div (height 100%) and inside it is a table with 3 rows. The first and last row have fixed size content. In the second row is a #content div with 100% height and overflow:auto. (actually the table has a lot more rows and the page has more divs, but for the sake of clarity i scalled it down for this question).

If there is more content in #content than fits, a vertical scrollbar should appear next to that div's content. However, a vertical scrollbar appears at the browser window itself. When i set the #content div to a fixed size however, that vertical scrollbar does appear in the correct place.

I must be doing something wrong, or maybe misinterpreting something :) Any ideas? Maybe there's jquery/javascript out there that can monitor the page and when loading/resizing the browser, scales down that particular div?

EDIT: I just created a small example: http://wierdaonline.com/softest.html

In the ideal situation, the whole thing (table) should always be visible in the browser window, without any window scrollbar other than in the #content div.

答:
It's much easier to create a fixed header and footer without using tables and using fixed position:</p>

```<code>#header
{
    position: fixed;
    top: 0;
    height: 20px;
}

#middle
{
    position: fixed;
    top: 20px;
    bottom: 20px;
    overflow: auto;
}

#footer
{
    position: fixed;
    bottom: 0;
    height: 20px;
}
</code>```

Body:
It's much easier to create a fixed header and footer without using tables and using fixed position:

#header
{
    position: fixed;
    top: 0;
    height: 20px;
}

#middle
{
    position: fixed;
    top: 20px;
    bottom: 20px;
    overflow: auto;
}

#footer
{
    position: fixed;
    bottom: 0;
    height: 20px;
}


问:
How to animate height to 100% in react-native?
I have been trying to do:

```<code>        <Animated.View
          style={[{
            height: this.collapse.interpolate({
              inputRange: [0, 1],
              outputRange: ['0%', '100%'],
            }),
          }]}
        >
          {children}
        </Animated.View>
</code>```

But the one item from the list take the FlatList total height.

I have tried to use minHeight, but same problem.

How can I make my animated height on 100%?

Reproduction

Snack : https://snack.expo.io/@kopax/petrified-cookies

With a browser, the height is not of the height of the <FlatList />, but on native, it looks like this:

How can I use a dynamic height for this animation?

答:
If your items are of different height then one solution would be to calculate this height using the onLayout function when the Swipeable items are rendered and then use this value for your animation.

```<code>class GmailStyleSwipeableRow extends Component {
  static animationDeleteDuration = 200; // eslint-disable-line react/sort-comp

  constructor(props) {
    super(props);
    this.collapse = new Animated.Value(1);
    this.height = 75;
  }

  render () {
  return (<Swipeable>
    <Animated.View
        onLayout={event => {
            const { height } = event.nativeEvent.layout;
            this.height = height;
        }}
        style={[
            {
            minHeight: 75, //give it a default minHeight
            height: this.collapse.interpolate({
                inputRange: [0, 1],
                outputRange: [0, this.height], //base your animation on the calculated height
            }),
            },
        ]}
        >
      {children}
    </Animated.View>
  </Swipeable>)
  }
}
</code>```

But if your items are like your example then you can save all these calculations and just give the items the same height.

Body:
I have been trying to do:

        <Animated.View
          style={[{
            height: this.collapse.interpolate({
              inputRange: [0, 1],
              outputRange: ['0%', '100%'],
            }),
          }]}
        >
          {children}
        </Animated.View>

But the one item from the list take the FlatList total height.

I have tried to use minHeight, but same problem.

How can I make my animated height on 100%?

Reproduction

Snack : https://snack.expo.io/@kopax/petrified-cookies

With a browser, the height is not of the height of the <FlatList />, but on native, it looks like this:

How can I use a dynamic height for this animation?

Body:
If your items are of different height then one solution would be to calculate this height using the onLayout function when the Swipeable items are rendered and then use this value for your animation.

class GmailStyleSwipeableRow extends Component {
  static animationDeleteDuration = 200; // eslint-disable-line react/sort-comp

  constructor(props) {
    super(props);
    this.collapse = new Animated.Value(1);
    this.height = 75;
  }

  render () {
  return (<Swipeable>
    <Animated.View
        onLayout={event => {
            const { height } = event.nativeEvent.layout;
            this.height = height;
        }}
        style={[
            {
            minHeight: 75, //give it a default minHeight
            height: this.collapse.interpolate({
                inputRange: [0, 1],
                outputRange: [0, this.height], //base your animation on the calculated height
            }),
            },
        ]}
        >
      {children}
    </Animated.View>
  </Swipeable>)
  }
}

But if your items are like your example then you can save all these calculations and just give the items the same height.


问:
Bar plot with polar axis
I want to make my plot similar to this-

Currently, what I am able to get is this:

I am not able to do the following things:

Get the time labels inside the inner circle

Get the ticks inside the circle. This question - How to create minor ticks for polar plot matplotlib, had an idea which I tried but it was messing up with other parts of the plot.

Time labels only work properly when the step size is 3. For other steps, it does not align with the bars.

Below is the reproducible code to produce the plot

```<code>arr = np.random.randint(0, 24, size = 50000)
df = pd.DataFrame({"COL": arr}).COL.value_counts().sort_index()

N = 24
bottom = 1000
theta, width = np.linspace(0.0, 2 * np.pi, N, endpoint=False, retstep=True)

plt.figure(figsize = (10, 6))
ax = plt.subplot(111, polar=True)

bars = ax.bar(
    theta, df,
    width=width-0.03,
    bottom=bottom,
    color="#f39c12", edgecolor="black"
)
bars = ax.bar(
    theta, [3000]*24,
    width=width-0.03,
    bottom=bottom,
    color="#f39c12", alpha=0.2
)

ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.grid(False)
ax.spines['polar'].set_visible(False)
ax.set_rticks([])

ticks = [f"{i}:00" for i in range(0, 24, 3)]
ax.set_xticklabels(ticks)

_ = ax
</code>```

答:
Also if you wanna add the numbers inside of the circle do this:

```<code>#00, 06, 12, 18 labels for clockface
plt.text(0, bottom*.80, "00", transform=ax.transData._b, ha='center', va='center', color='black', fontsize=2.5, fontweight='bold')
plt.text(bottom*.80, 0, "06", transform=ax.transData._b, ha='center', va='center', color='black', fontsize=2.5, fontweight='bold')
plt.text(0, -bottom*.80, "12", transform=ax.transData._b, ha='center', va='center', color='black', fontsize=2.5, fontweight='bold')
plt.text(-bottom*.80, 0, "18", transform=ax.transData._b, ha='center', va='center', color='black', fontsize=2.5, fontweight='bold')
</code>```

I know it's not the best or fanciest way to do this but it works OK! Please @ me if you have a cleaner way to write this code haha..

Also some other notes:

-For the code i posted above change the sizes of the hour and minute hand to make it look even better (multiply bottom variable by  different values below 1)

-I had to change the fontsize, and linewidths as I changed the size and dpi of the image to make it look right but its not too hard to figure out how to make it look right.

-I ended up not drawing the tick marks as it didn't seem worth my time to figure out how to do it. would love to know from anyone else if there's some way to space out dashes or something around there. But i really just didn't wanna mess with the rotation

Title: Bar plot with polar axis

Body:
I want to make my plot similar to this-

Currently, what I am able to get is this:

I am not able to do the following things:

Get the time labels inside the inner circle

Get the ticks inside the circle. This question - How to create minor ticks for polar plot matplotlib, had an idea which I tried but it was messing up with other parts of the plot.

Time labels only work properly when the step size is 3. For other steps, it does not align with the bars.

Below is the reproducible code to produce the plot

arr = np.random.randint(0, 24, size = 50000)
df = pd.DataFrame({"COL": arr}).COL.value_counts().sort_index()

N = 24
bottom = 1000
theta, width = np.linspace(0.0, 2 * np.pi, N, endpoint=False, retstep=True)

plt.figure(figsize = (10, 6))
ax = plt.subplot(111, polar=True)

bars = ax.bar(
    theta, df,
    width=width-0.03,
    bottom=bottom,
    color="#f39c12", edgecolor="black"
)
bars = ax.bar(
    theta, [3000]*24,
    width=width-0.03,
    bottom=bottom,
    color="#f39c12", alpha=0.2
)

ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.grid(False)
ax.spines['polar'].set_visible(False)
ax.set_rticks([])

ticks = [f"{i}:00" for i in range(0, 24, 3)]
ax.set_xticklabels(ticks)

_ = ax

Body:
Also if you wanna add the numbers inside of the circle do this:

#00, 06, 12, 18 labels for clockface
plt.text(0, bottom*.80, "00", transform=ax.transData._b, ha='center', va='center', color='black', fontsize=2.5, fontweight='bold')
plt.text(bottom*.80, 0, "06", transform=ax.transData._b, ha='center', va='center', color='black', fontsize=2.5, fontweight='bold')
plt.text(0, -bottom*.80, "12", transform=ax.transData._b, ha='center', va='center', color='black', fontsize=2.5, fontweight='bold')
plt.text(-bottom*.80, 0, "18", transform=ax.transData._b, ha='center', va='center', color='black', fontsize=2.5, fontweight='bold')

I know it's not the best or fanciest way to do this but it works OK! Please @ me if you have a cleaner way to write this code haha..

Also some other notes:

-For the code i posted above change the sizes of the hour and minute hand to make it look even better (multiply bottom variable by  different values below 1)

-I had to change the fontsize, and linewidths as I changed the size and dpi of the image to make it look right but its not too hard to figure out how to make it look right.

-I ended up not drawing the tick marks as it didn't seem worth my time to figure out how to do it. would love to know from anyone else if there's some way to space out dashes or something around there. But i really just didn't wanna mess with the rotation


问:
Why is my "X" not showing through the transparent rectangle?
This code shows 2 rectangles with "X"s behind a transparent rectangle.  The top one has a reddish background -- the "X" show through the front rectangle as it should.  The bottom rectangle has the default transparent background -- the "X" doesn't show through the front rectangle as I would like.  Maybe there is an "alpha.." parameter I'm missing?  TIA.

```<code><!doctype html>
<html>
  <head>
    <title> threejs texture transparency </title>
    <style type="text/css">
canvas { outline:1px dotted black; }
    </style>
    <script src="http://threejs.org/build/three.js"></script>
    <script type="text/javascript">
  "use strict";
  var renderer, camera, world, geometry, material, mesh;
  var js3canvas, js3w, js3h, canvas, ctx, texture;
window.onload = function() {
  "use strict";
  // the basic 3js
  js3canvas = document.getElementById("js3canvas");
  renderer = new THREE.WebGLRenderer( { canvas:js3canvas } );
  js3w = js3canvas.width;
  js3h = js3canvas.height;
  camera = new THREE.PerspectiveCamera(50, js3w/js3h, 1, 200);
  camera.position.z = 75;
  camera.lookAt(0,0,0);
  world = new THREE.Scene();
  world.background = new THREE.Color(0xaaaaaa);

  // a greenish transparent rectangle at z=+1
  geometry = new THREE.PlaneGeometry(20, 50);
  material = new THREE.MeshBasicMaterial( { color:0x55aa55, transparent:true, opacity:0.5 } );
  world.add(new THREE.Mesh(geometry, material));

  doRect("top"); // a REDDISH rectangle at z=-1 with a texture of a black "X"
  doRect("bot"); // a TRANSPARENT rectangle at z=-1 with a texture of a black "X"
  renderer.render( world, camera );
};
function doRect(topbot) { // a rectangle with a texture
  // first, the canvas for the texture
  if (topbot == "top") canvas = document.getElementById("canvas2"); // top rectangle
  else canvas = document.getElementById("canvas3"); // bot rectangle
  ctx = canvas.getContext("2d");
  if (topbot == "top") { // top only, reddish background
    ctx.fillStyle = "#aa5555";
    ctx.fillRect(0,0,250,50);
  } // bot is left default transparent
  ctx.strokeStyle = "#0000000"; // black lines to make "X"
  ctx.moveTo(0,0); ctx.lineTo(250,50);
  ctx.moveTo(0,50); ctx.lineTo(250,0);
  ctx.stroke();
  // second, the texture
  texture = new THREE.Texture(canvas);
  texture.minFilter = THREE.LinearFilter; // eliminates console.log msg
  texture.needsUpdate = true; // needed
  // third, the rectangle with the texture
  geometry = new THREE.PlaneGeometry(50,10);
  if (topbot == "top") { // top rectangle with "X" texture, reddish background
    geometry.translate(0,10,-1); // move up
    material = new THREE.MeshBasicMaterial( { map:texture, transparent:false } );
    // If this material is transparent(true) then the "X" doesn't show through.
  } else {               // bottom rectangle with "X" texture, default(transparent) background
    geometry.translate(0,-10,-1); // move down
    material = new THREE.MeshBasicMaterial( { map:texture, transparent:true, opacity:1.0 } );
    // This material has to be transparent to get a transparent background for the texture.
    // But then the "X" doesn't show through.
  }
  mesh = new THREE.Mesh(geometry, material); // and finally the mesh
  world.add(mesh);
}
    </script>
  </head>
  <body>
    <canvas id="js3canvas" width="600" height="600"></canvas><br />
    <canvas id="canvas2" width="250" height="50"></canvas><br />
    <canvas id="canvas3" width="250" height="50"></canvas>
  </body>
</html>
</code>```

EDIT for Mugen87:

  add "side:THREE.DoubleSide, " to all materials,

  add these 2 statements in the appropriate places:

```<code>  mesh.renderOrder = 1;
  animate();
</code>```

and add this function:

```<code>function animate() {
  renderer.render( world, camera );
  world.rotation.y += .01;
  if (world.rotation.y < 3.1416) requestAnimationFrame(animate);
}
</code>```

Now the bottom rectangle is not transparent?
I'll be looking at this.

答:
What you see is a depth sorting issue. Both transparent objects (the green plane mesh and the transparent X) are placed at the same position in 3D space. Hence, they are rendered according to their order in the scene graph. For the correct result, you have to ensure that the green plane is rendered last. You can influence the default sorting of the renderer by defining Object3D.renderOrder.

var renderer, camera, world, geometry, material, mesh;
var js3canvas, js3w, js3h, canvas, ctx, texture;

// the basic 3js
js3canvas = document.getElementById("js3canvas");
renderer = new THREE.WebGLRenderer( { canvas:js3canvas } );
js3w = js3canvas.width;
js3h = js3canvas.height;
camera = new THREE.PerspectiveCamera(50, js3w/js3h, 1, 200);
camera.position.z = 75;
camera.lookAt(0,0,0);
world = new THREE.Scene();
world.background = new THREE.Color(0xaaaaaa);

// a greenish transparent rectangle at z=+1
geometry = new THREE.PlaneGeometry(20, 50);
material = new THREE.MeshBasicMaterial( { color:0x55aa55, transparent:true, opacity:0.5 } );
var mesh = new THREE.Mesh(geometry, material);
mesh.renderOrder = 1;
world.add(mesh);

doRect("top"); // a REDDISH rectangle at z=-1 with a texture of a black "X"
doRect("bot"); // a TRANSPARENT rectangle at z=-1 with a texture of a black "X"

renderer.render( world, camera );

function doRect(topbot) { // a rectangle with a texture
  // first, the canvas for the texture
  if (topbot == "top") canvas = document.getElementById("canvas2"); // top rectangle
  else canvas = document.getElementById("canvas3"); // bot rectangle
  ctx = canvas.getContext("2d");
  if (topbot == "top") { // top only, reddish background
    ctx.fillStyle = "#aa5555";
    ctx.fillRect(0,0,250,50);
  } // bot is left default transparent
  ctx.strokeStyle = "#0000000"; // black lines to make "X"
  ctx.moveTo(0,0); ctx.lineTo(250,50);
  ctx.moveTo(0,50); ctx.lineTo(250,0);
  ctx.stroke();
  // second, the texture
  texture = new THREE.Texture(canvas);
  texture.minFilter = THREE.LinearFilter; // eliminates console.log msg
  texture.needsUpdate = true; // needed
  // third, the rectangle with the texture
  geometry = new THREE.PlaneGeometry(50,10);
  if (topbot == "top") { // top rectangle with "X" texture, reddish background
    geometry.translate(0,10,-1); // move up
    material = new THREE.MeshBasicMaterial( { map:texture } );
    // If this material is transparent(true) then the "X" doesn't show through.
  } else {               // bottom rectangle with "X" texture, default(transparent) background
    geometry.translate(0,-10,-1); // move down
    material = new THREE.MeshBasicMaterial( { map:texture, transparent:true, opacity:1.0 } );
    // This material has to be transparent to get a transparent background for the texture.
    // But then the "X" doesn't show through.
  }
  mesh = new THREE.Mesh(geometry, material); // and finally the mesh
  world.add(mesh);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
   margin: 0;
}
canvas {
 outline: 1px dotted black;
 }</code>```

<canvas id="js3canvas" width="600" height="600"></canvas>

<canvas id="canvas2" width="250" height="50"></canvas>

<canvas id="canvas3" width="250" height="50"></canvas>```

Body:
This code shows 2 rectangles with "X"s behind a transparent rectangle.  The top one has a reddish background -- the "X" show through the front rectangle as it should.  The bottom rectangle has the default transparent background -- the "X" doesn't show through the front rectangle as I would like.  Maybe there is an "alpha.." parameter I'm missing?  TIA.

<!doctype html>

    <title> threejs texture transparency </title>

    <canvas id="js3canvas" width="600" height="600"></canvas>

    <canvas id="canvas2" width="250" height="50"></canvas>

    <canvas id="canvas3" width="250" height="50"></canvas>

EDIT for Mugen87:

  add "side:THREE.DoubleSide, " to all materials,

  add these 2 statements in the appropriate places:

  mesh.renderOrder = 1;
  animate();

and add this function:

function animate() {
  renderer.render( world, camera );
  world.rotation.y += .01;
  if (world.rotation.y < 3.1416) requestAnimationFrame(animate);
}

Now the bottom rectangle is not transparent?
I'll be looking at this.

Body:
What you see is a depth sorting issue. Both transparent objects (the green plane mesh and the transparent X) are placed at the same position in 3D space. Hence, they are rendered according to their order in the scene graph. For the correct result, you have to ensure that the green plane is rendered last. You can influence the default sorting of the renderer by defining Object3D.renderOrder.

var renderer, camera, world, geometry, material, mesh;
var js3canvas, js3w, js3h, canvas, ctx, texture;

// the basic 3js
js3canvas = document.getElementById("js3canvas");
renderer = new THREE.WebGLRenderer( { canvas:js3canvas } );
js3w = js3canvas.width;
js3h = js3canvas.height;
camera = new THREE.PerspectiveCamera(50, js3w/js3h, 1, 200);
camera.position.z = 75;
camera.lookAt(0,0,0);
world = new THREE.Scene();
world.background = new THREE.Color(0xaaaaaa);

// a greenish transparent rectangle at z=+1
geometry = new THREE.PlaneGeometry(20, 50);
material = new THREE.MeshBasicMaterial( { color:0x55aa55, transparent:true, opacity:0.5 } );
var mesh = new THREE.Mesh(geometry, material);
mesh.renderOrder = 1;
world.add(mesh);

doRect("top"); // a REDDISH rectangle at z=-1 with a texture of a black "X"
doRect("bot"); // a TRANSPARENT rectangle at z=-1 with a texture of a black "X"

renderer.render( world, camera );

function doRect(topbot) { // a rectangle with a texture
  // first, the canvas for the texture
  if (topbot == "top") canvas = document.getElementById("canvas2"); // top rectangle
  else canvas = document.getElementById("canvas3"); // bot rectangle
  ctx = canvas.getContext("2d");
  if (topbot == "top") { // top only, reddish background
    ctx.fillStyle = "#aa5555";
    ctx.fillRect(0,0,250,50);
  } // bot is left default transparent
  ctx.strokeStyle = "#0000000"; // black lines to make "X"
  ctx.moveTo(0,0); ctx.lineTo(250,50);
  ctx.moveTo(0,50); ctx.lineTo(250,0);
  ctx.stroke();
  // second, the texture
  texture = new THREE.Texture(canvas);
  texture.minFilter = THREE.LinearFilter; // eliminates console.log msg
  texture.needsUpdate = true; // needed
  // third, the rectangle with the texture
  geometry = new THREE.PlaneGeometry(50,10);
  if (topbot == "top") { // top rectangle with "X" texture, reddish background
    geometry.translate(0,10,-1); // move up
    material = new THREE.MeshBasicMaterial( { map:texture } );
    // If this material is transparent(true) then the "X" doesn't show through.
  } else {               // bottom rectangle with "X" texture, default(transparent) background
    geometry.translate(0,-10,-1); // move down
    material = new THREE.MeshBasicMaterial( { map:texture, transparent:true, opacity:1.0 } );
    // This material has to be transparent to get a transparent background for the texture.
    // But then the "X" doesn't show through.
  }
  mesh = new THREE.Mesh(geometry, material); // and finally the mesh
  world.add(mesh);
}

body {
   margin: 0;
}
canvas {
 outline: 1px dotted black;
 }

<script src="https://rawcdn.githack.com/mrdoob/three.js/r113/build/three.js"></script>

<canvas id="js3canvas" width="600" height="600"></canvas><br />
<canvas id="canvas2" width="250" height="50"></canvas><br />
<canvas id="canvas3" width="250" height="50"></canvas>


问:
Nativescript-Vue devtools Not updating The Page
When I navigate from one page to another, the devtools from Vue js in nativescript-vue simply does not update.

It only shows the current page, and not the following where I navigate.

As you can see in the image, it stacks on UserCreation and I am navigating to VerifyCode Page.

I am using nativescript-vue

答:
You can force a refresh in devtools with the refresh icon.

I have improved this in the v2.5.0-alpha.0 version, please try the latest alpha (v2.5.0-alpha.3 at the time of writing) and see if it improves the developer experience for you.


问:
GCC add further binary in linkerscript
I got two applications one is a bootloader and second one is an application. This application shall be kept.

How can I embed the bootloader binary to the linker script of the application (this is only for debugging purposes)?

What are the steps?

I have defined a new section called .bootloader but I don't know how to get further and which kind of format the bootloader should have to succeed with this. I use the, currently latest ARM GNU embedded toolchain.

答:
If you want to do this in the linker script you can use the INPUT command. Like INPUT(bootloader.o). Or maybe even STARTUP if the order is important for you.

Otherwise you can use arm-none-eabi-objcopy.

Here's similar question from Electrical Engineering https://electronics.stackexchange.com/q/368926/95998

Title: GCC add further binary in linkerscript


问:
Class PHPUnitLogger cannot extend from interface PHPUnit\TextUI\ResultPrinter
I was installing Eclipse and PHPUnit on Windows and tried to run a test provided with PHPUnit but i got this error:

PHP Fatal error:  Class PHPUnitLogger cannot extend from interface PHPUnit\TextUI\ResultPrinter in C:\Users\lmarques\AppData\Local\Temp\phpunit_printer\PHPUnitLogger.php(424) : eval()'d code on line 1

In parallel, i need to force termination of execution and get this message at that moment:

Cannot launch PHPUnit tests (port address 7478): Accept timed out

I used composer to install PHPunit and also put configuration for phpunit.phar in Preferences/PHP/Tools/PHPUnit (https://phpunit.readthedocs.io/fr/latest/installation.html)

Can anyone help?

答:
PHPUnit 9 has been released 7 Feb 2020 and is not supported by current stable Eclipse PHP Development Tools.

Support for this version will be part of upcoming PDT 7.1.

Bug report: https://bugs.eclipse.org/bugs/show_bug.cgi?id=559932


问:
Any way to get a specific entry by key in a Java hashmap(having inserted multiple values)?
I have a Java hashmap, to which multiple variables were added(ex.):

```<code>class client {
    public static int clientIdentifier;
    public static String clientName;
    public static String clientFamilyname;
    public static String clientBirthdate;
}

</code>```

Inside the main method:

```<code>client newclient = new client();
HashMap<Integer, String> clients = new HashMap<>();

clients.put(newclient.clientIdentifier,
newclient.clientName +
newclient.clientFamilyname +
 newclient.clientBirthdate

</code>```

Where new client.clientIdentifier is the key and newClient.clientName/Familyname/Birthdate are already defined. They belong to an object newclient, it belonging to the class client

Is there any way to get only the value clientName from that hashmap, to compare later?

Looking for something like:
String requiredName = clients.get(scannedID, newclient.clientName);

(I know that it is totally wrong, but just to have an idea)

Thank you very much!

答:
I would put the value in the hashmap something like this:

```<code>map.put(clientID,name+"+"+familyname+"+"+bithdate);
</code>```

This way when I get the value from Map using the key, I would get a string like John+Wood+1994.
Now I can easily get the name by using substring.
Does this help ?

Body:
I have a Java hashmap, to which multiple variables were added(ex.):

class client {
    public static int clientIdentifier;
    public static String clientName;
    public static String clientFamilyname;
    public static String clientBirthdate;
}

Inside the main method:

client newclient = new client();
HashMap<Integer, String> clients = new HashMap<>();

clients.put(newclient.clientIdentifier,
newclient.clientName +
newclient.clientFamilyname +
 newclient.clientBirthdate

Where new client.clientIdentifier is the key and newClient.clientName/Familyname/Birthdate are already defined. They belong to an object newclient, it belonging to the class client

Is there any way to get only the value clientName from that hashmap, to compare later?

Looking for something like:
String requiredName = clients.get(scannedID, newclient.clientName);

(I know that it is totally wrong, but just to have an idea)

Thank you very much!

Body:
I would put the value in the hashmap something like this:

map.put(clientID,name+"+"+familyname+"+"+bithdate);

This way when I get the value from Map using the key, I would get a string like John+Wood+1994.
Now I can easily get the name by using substring.
Does this help ?


问:
Streaming Video to Web Browser
I would like to display a live video stream in a web browser. (Compatibility with IE, Firefox, and Chrome would be awesome, if possible.) Someone else will be taking care of streaming the video, but I have to be able to receive and display it. I will be receiving the video over UDP, but for now I am just using VLC to stream it to myself for testing purposes. Is there an open source library that might help me accomplish this using HTML and/or JavaScript? Or a good website that would help me figure out how to do this on my own?

I've read a bit about RTSP, which seems like the traditional option for something like this. That might be what I have to fall back on if I can't accomplish this using UDP, but if that is the case I still am unsure of how to go about this using RTSP/RTMP/RTP, or what the differences between all those acronyms are, if any.

I thought HTTP adaptive streaming might be the best option for a while, but it seemed like all the solutions using that were proprietary (Microsoft IIS Smooth Streaming, Apple HTTP Live Streaming, or Adobe HTTP Dynamic Streaming), and I wasn't having much luck figuring out how to accomplish it on my own. MPEG-DASH sounded like an awesome solution as well, but it doesn't seem to be in use yet since it is still so new. But now I am told that I should expect to receive the video over UDP anyways, so those solutions probably don't matter for me anymore.

I've been Googling this stuff for several days without much luck on finding anything to help me implement it. All I can find are articles explaining what the technologies are (e.g. RTSP, HTTP Adaptive Streaming, etc.) or tools that you can buy to stream your own videos over the web. Your guidance would be greatly appreciated!

答:
If you don't need sound, you can send JPEGs with header like this:

Content-Type: multipart/x-mixed-replace

This is a simple demo with nodejs, it uses library opencv4nodejs to generate images. You can use any other HTTP server which allows to append data to the socket while keeping connection opened. Tested on Chrome and FF on Ubuntu Linux.

To run the sample you will need to install this library with npm install opencv4nodejs, it might take while, then start the server like this: node app.js, here is app.js itself

```<code>var http = require('http')
const cv = require('opencv4nodejs');

var m=new cv.Mat(300, 300, cv.CV_8UC3);
var cnt = 0;
const blue = new cv.Vec3(255, 220, 120);
const yellow = new cv.Vec3(255, 220, 0);
var lastTs = Date.now();
http.createServer((req, res) => {
    if (req.url=='/'){
        res.end("<!DOCTYPE html><style>iframe {transform: scale(.67)}</style><html>This is a streaming video:<br>" +
            "<img  src='/frame'></img></html>")
    } else if (req.url=='/frame') {
        res.writeHead(200, { 'Content-Type': 'multipart/x-mixed-replace;boundary=myboundary' });
        var x =0;
        var fps=0,fcnt=0;
        var next = function () {
            var ts = Date.now();
            var m1=m.copy();
            fcnt++;
            if (ts-lastTs > 1000){
                lastTs = ts;
                fps = fcnt;
                fcnt=0;
            }
            m1.putText(`frame ${cnt}  FPS=${fps}`, new cv.Point2(20,30),1,1,blue);
            m1.drawCircle(new cv.Point2(x,50),10,yellow,-1);
            x+=1;
            if (x>m.cols) x=0;
            cnt++;
            var buf = cv.imencode(".jpg",m1);
            res.write("--myboundary\r\nContent-type:image/jpeg\r\nDaemonId:0x00258009\r\n\r\n");
            res.write(buf,function () {
                next();
            });
        };
        next();
    }
}).listen(80);
</code>```

A bit later I've found this example with some more details in python: https://blog.miguelgrinberg.com/post/video-streaming-with-flask

UPDATE: it also works, if you stream this into html img tag.

Title: Streaming Video to Web Browser

Body:
If you don't need sound, you can send JPEGs with header like this:

Content-Type: multipart/x-mixed-replace

This is a simple demo with nodejs, it uses library opencv4nodejs to generate images. You can use any other HTTP server which allows to append data to the socket while keeping connection opened. Tested on Chrome and FF on Ubuntu Linux.

To run the sample you will need to install this library with npm install opencv4nodejs, it might take while, then start the server like this: node app.js, here is app.js itself

var http = require('http')
const cv = require('opencv4nodejs');

var m=new cv.Mat(300, 300, cv.CV_8UC3);
var cnt = 0;
const blue = new cv.Vec3(255, 220, 120);
const yellow = new cv.Vec3(255, 220, 0);
var lastTs = Date.now();
http.createServer((req, res) => {
    if (req.url=='/'){
        res.end("<!DOCTYPE html><style>iframe {transform: scale(.67)}</style><html>This is a streaming video:<br>" +
            "<img  src='/frame'></img></html>")
    } else if (req.url=='/frame') {
        res.writeHead(200, { 'Content-Type': 'multipart/x-mixed-replace;boundary=myboundary' });
        var x =0;
        var fps=0,fcnt=0;
        var next = function () {
            var ts = Date.now();
            var m1=m.copy();
            fcnt++;
            if (ts-lastTs > 1000){
                lastTs = ts;
                fps = fcnt;
                fcnt=0;
            }
            m1.putText(`frame ${cnt}  FPS=${fps}`, new cv.Point2(20,30),1,1,blue);
            m1.drawCircle(new cv.Point2(x,50),10,yellow,-1);
            x+=1;
            if (x>m.cols) x=0;
            cnt++;
            var buf = cv.imencode(".jpg",m1);
            res.write("--myboundary\r\nContent-type:image/jpeg\r\nDaemonId:0x00258009\r\n\r\n");
            res.write(buf,function () {
                next();
            });
        };
        next();
    }
}).listen(80);

A bit later I've found this example with some more details in python: https://blog.miguelgrinberg.com/post/video-streaming-with-flask

UPDATE: it also works, if you stream this into html img tag.


问:
How to convert the header as a new column
I'm working with pandas, and I'm trying to convert the header row of the dataframe to a column, i have tried the stack() function, but it looks not working for me.

I have a file which contains data as the follow, it has double header - date and temperature (min & Max)

```<code>      2/16/2020  2/16/2020   2/17/2020   2/17/2020   2/18/2020  2/18/2020   ......
         Min        Max         Min         Max         Min        Max
Paris    44         61          41          52          39         47
Berlin   47         59          42          52          41         45
Milan    46         64          40          46          37         44
.
.
.
</code>```

Expected output:

```<code>City    MIN MAX Date
Paris   44  61  2/16/2020
Paris   41  52  2/17/2020
Paris   39  47  2/18/2020
Berlin  47  59  2/16/2020
Berlin  42  52  2/17/2020
Berlin  41  45  2/18/2020
Milan   46  64  2/16/2020
Milan   40  46  2/17/2020
Milan   37  44  2/18/2020
</code>```

I tried to use df= pd.read_csv(StringIO(csv.text), header=[1]) to select the second row as the header but how to set only City, Min, Max, and create 'Date' which the new column?

I'm grateful if you can help me.

Cheers,

答:
You could do:

Read in your data as shown and transform. suppose your data is named as my_data.csv

```<code>df = pd.read_csv('my_data.csv',sep = '\\s+',header = [0,1])
df.stack(0).rename_axis(['City','Date']).reset_index()
Out:
     City       Date  Max  Min
0   Paris  2/16/2020   61   44
1   Paris  2/17/2020   52   41
2   Paris  2/18/2020   47   39
3  Berlin  2/16/2020   59   47
4  Berlin  2/17/2020   52   42
5  Berlin  2/18/2020   45   41
6   Milan  2/16/2020   64   46
7   Milan  2/17/2020   46   40
8   Milan  2/18/2020   44   37
</code>```

Body:
I'm working with pandas, and I'm trying to convert the header row of the dataframe to a column, i have tried the stack() function, but it looks not working for me.

I have a file which contains data as the follow, it has double header - date and temperature (min & Max)

      2/16/2020  2/16/2020   2/17/2020   2/17/2020   2/18/2020  2/18/2020   ......
         Min        Max         Min         Max         Min        Max
Paris    44         61          41          52          39         47
Berlin   47         59          42          52          41         45
Milan    46         64          40          46          37         44
.
.
.

Expected output:

City    MIN MAX Date
Paris   44  61  2/16/2020
Paris   41  52  2/17/2020
Paris   39  47  2/18/2020
Berlin  47  59  2/16/2020
Berlin  42  52  2/17/2020
Berlin  41  45  2/18/2020
Milan   46  64  2/16/2020
Milan   40  46  2/17/2020
Milan   37  44  2/18/2020

I tried to use df= pd.read_csv(StringIO(csv.text), header=[1]) to select the second row as the header but how to set only City, Min, Max, and create 'Date' which the new column?

I'm grateful if you can help me.

Cheers,

Body:
You could do:

Read in your data as shown and transform. suppose your data is named as my_data.csv

df = pd.read_csv('my_data.csv',sep = '\\s+',header = [0,1])
df.stack(0).rename_axis(['City','Date']).reset_index()
Out:
     City       Date  Max  Min
0   Paris  2/16/2020   61   44
1   Paris  2/17/2020   52   41
2   Paris  2/18/2020   47   39
3  Berlin  2/16/2020   59   47
4  Berlin  2/17/2020   52   42
5  Berlin  2/18/2020   45   41
6   Milan  2/16/2020   64   46
7   Milan  2/17/2020   46   40
8   Milan  2/18/2020   44   37


问:
Dot separated value is inserted instead of comma in asp
I'm kinda "fresh" in classic ASP and I have the following insert SQL query in classic ASP and i can't make it insert comma separated value from a CSV file in MS Access database, but instead it will convert it in dot separated thousand value.

E.g.:
price = "49,55"

```<code>insert_sql = "INSERT INTO table (price) VALUES ('" & price & "')
DataConn.execute(insert_sql)
</code>```

I tried to convert it like:

```<code>CDbl(price) or FormatNumber(price)
</code>```

but what i get after all is 4.955,00.

I've tried changing localization, but i still have the same problem.

P.S.: I am aware of the fact that the above code is SQL Injection vulnerable, but for now i'm trying to understand what's wrong, or what do i forget.

Thanks.

答:
Use Str to force a dot as the decimal separator:

```<code>insert_sql = "INSERT INTO table (price) VALUES (" & Str(price) & ")"
</code>```

Then, for display of the price, apply any format you prefer.

Body:
I'm kinda "fresh" in classic ASP and I have the following insert SQL query in classic ASP and i can't make it insert comma separated value from a CSV file in MS Access database, but instead it will convert it in dot separated thousand value.

E.g.:
price = "49,55"

insert_sql = "INSERT INTO table (price) VALUES ('" & price & "')
DataConn.execute(insert_sql)

I tried to convert it like:

CDbl(price) or FormatNumber(price)

but what i get after all is 4.955,00.

I've tried changing localization, but i still have the same problem.

P.S.: I am aware of the fact that the above code is SQL Injection vulnerable, but for now i'm trying to understand what's wrong, or what do i forget.

Thanks.

Body:
Use Str to force a dot as the decimal separator:

insert_sql = "INSERT INTO table (price) VALUES (" & Str(price) & ")"

Then, for display of the price, apply any format you prefer.


问:
Bootstrap 4 Alpha 6 navbar-toggler-right and left create strange behavior
I have a simple navbar:

```<code><nav class="navbar navbar-inverse navbar-toggleable-md fixed-top custom-navbar" style="background-color: #321048;">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
            <ul class="navbar-nav d-flex justify-content-end" style="width:100%">
              <li class="nav-item">
                <a class="nav-link" href="#home">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#rolfing">Rolfing</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#packages">Packages</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#about">About</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#footer">Contact</a>
              </li>
            </ul>
        </div>
</nav>
</code>```

And everything works as expected for all screen sizes.

I wanted to right justify the toggler because the menu is right justified. So per Bootstrap 4 alpha 6, I added

```<code>navbar-toggler-right
</code>```

to the button, and it indeed does right justify the button, but the navbar itself no longer expands to fill the button. So the toggle button looks to be just floating. I am content to leave navbar-toggler-right out let it work, but I am just curious why it would do that. something to do with navbar-toggler-right having an absolute position perhaps. navbar-toggler-left does the same thing as well.

EDIT
To offer more detail, it does not matter that the toggle button be on the left or on the right. Adding the class navbar-toggler-left causes the same problem. My question is not how to move the toggle button to the right (I can do that by adding float:right to the button), but why the
navbar-toggler-left and right classes have that strange behavior.

答:
I had the same problem. Both the brand name and the toggler were left aligned. I solved the problem with
. It worked.

So, you may try

 instead of  ul class="navbar-nav d-flex justify-content-end" style="width:100%"

Body:
I have a simple navbar:

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                Home

                Rolfing

                Packages

                About

                Contact

And everything works as expected for all screen sizes.

I wanted to right justify the toggler because the menu is right justified. So per Bootstrap 4 alpha 6, I added

navbar-toggler-right

to the button, and it indeed does right justify the button, but the navbar itself no longer expands to fill the button. So the toggle button looks to be just floating. I am content to leave navbar-toggler-right out let it work, but I am just curious why it would do that. something to do with navbar-toggler-right having an absolute position perhaps. navbar-toggler-left does the same thing as well.

EDIT
To offer more detail, it does not matter that the toggle button be on the left or on the right. Adding the class navbar-toggler-left causes the same problem. My question is not how to move the toggle button to the right (I can do that by adding float:right to the button), but why the
navbar-toggler-left and right classes have that strange behavior.

Body:
I had the same problem. Both the brand name and the toggler were left aligned. I solved the problem with <ul class="navbar-nav ml-auto  ">. It worked.

So, you may try <ul class="navbar-nav ml-auto  ">
 instead of  ul class="navbar-nav d-flex justify-content-end" style="width:100%"


问:
settingsChangedNotification sent only when Preferences.app is open (Swift - OSX)
I have the following code in my app:
DistributedNotificationCenter.default.addObserver(self, selector: #selector(volumeChangeEvent(_:)), name: NSNotification.Name(rawValue: "com.apple.sound.settingsChangedNotification"), object: nil)

As expected volumeChangeEvent(_:) is called when I change or mute the volume output. But only if the Preferences app is open...

Any suggestion is welcome.

Alex

答:
After trying countless ways I found a nice workaround: instead of searching for a probably non-existent notification that should tell when the volume had changed, I tried getting the physical key-press event.
As the media keys are not sending a normal CGEvent I came up with this solution: Capture OSX media control buttons in Swift

Note that the TouchBar simulates such a key event, so any app that you'll write using this method will also work for those MacBook models which have the TouchBar.

It's probably not the ideal solution, but it works. If anyone knows a better way please let me know.


问:
saving background color on localstorage
I got the data stored on my localStorage and display them in table format with each row having a button. What I want to do now is, when the button is clicked I want it to change the background color to another color and when the page refreshes the button persists its color state.

Here is my code

// here i will be the data in form of table
// my algorithm comes here
// this function will get data from the localstorage
const get_todos = ()=>{
  let todos = new Array();
  let todos_str = localStorage.getItem("todo");
  if(todos_str !== null){
    todos = JSON.parse(todos_str);
  }
  return todos;
}
//this function will show the data in the localstorage in table format
const show = ()=>{
  let todos = get_todos();
  let text = "";
  for(let i = 0; i < todos.length; i++){
      let allData = todos[i];
      let eventName = allData.Eventname;
      let location = allData.Location;
      let date = allData.Date;
      text += "
";
      text += "" + eventName + "	";
      text += "" + location + "	";
      text += "" + date + "	";
      text += "" + "<button class='buttons' type='button'>Pending</button>" + "	";
      text += "" + "" + "
";

  }
  //the data gotten from the localstorage will be here
  let table = document.querySelector("#table > tbody");
  table.innerHTML = text;
  //this is where the button background color will change
window.addEventListener("load", ()=>{
    let thead = document.querySelector("#thead");
    let buttons = Array.from(document.querySelectorAll(".buttons"));
    thead.addEventListener("click", (e)=>{
      if(e.target.className === "buttons"){
        let index = buttons.indexOf(e.target);
        changeBackground(e, index);
      }
    });
    buttons.forEach(btn, index =>{
      btn.className = sessionStorage.getItem('background${index}') || 'buttons';

    });
  });
  const changeBackground = (e, index)=>{
    e.target.className += "change";
    sessionStorage.setItem(background${index}, e.target.className);

  }

}
window.addEventListener("DOMContentLoaded", ()=>{
  show();
});
```

答:
There is few errors in your code:

First:

```<code>btn.className = sessionStorage.getItem('background${index}') || 'buttons';
</code>```

Should be:

```<code>btn.className = sessionStorage.getItem(`background${index}`) || 'buttons';
</code>```

because you are create a string using Template literals (Template strings)

Second:

```<code>e.target.className += "change";
</code>```

Should be:

```<code>e.target.className += " change";
</code>```

You have to add space when concatenate strings, or else in your case it will not provide the intended behavior, since your code will add change class name to the previous class as one word.

Third:

```<code>sessionStorage.setItem(background${index}, e.target.className);
</code>```

Should be:

```<code>sessionStorage.setItem(`background${index}`, e.target.className);
</code>```

In your question you are talking about localStorage but you are
using sessionStorage, Still not sure if this what you want, so if you want it to be localStorage just replace sessionStorage with localStorage

```<code>// here i will be the data in form of table
// my algorithm comes here
// this function will get data from the localstorage
const get_todos = ()=>{
  let todos = new Array();
  let todos_str = localStorage.getItem("todo");
  if(todos_str !== null){
    todos = JSON.parse(todos_str);
  }
  return todos;
}
//this function will show the data in the localstorage in table format
const show = ()=>{
  let todos = get_todos();
  let text = "";
  for(let i = 0; i < todos.length; i++){
      let allData = todos[i];
      let eventName = allData.Eventname;
      let location = allData.Location;
      let date = allData.Date;
      text += "<tr>";
      text += "<td>" + eventName + "</td>";
      text += "<td>" + location + "</td>";
      text += "<td>" + date + "</td>";
      text += "<td>" + "<button class='buttons' type='button'>Pending</button>" + "</td>";
      text += "<td>" + "<i id='remove' class='fas fa-trash-alt btndelete'></i>" + "</td></tr>";

  }
  //the data gotten from the localstorage will be here
  let table = document.querySelector("#table > tbody");
  table.innerHTML = text;
  //this is where the button background color will change
window.addEventListener("load", ()=>{
    let thead = document.querySelector("#thead");
    let buttons = Array.from(document.querySelectorAll(".buttons"));
    thead.addEventListener("click", (e)=>{
      if(e.target.className === "buttons"){
        let index = buttons.indexOf(e.target);
        changeBackground(e, index);
      }
    });
    buttons.forEach(btn, index =>{
      btn.className = localStorage.getItem(`background${index}`) || 'buttons';

    });
  });
  const changeBackground = (e, index)=>{
    e.target.className += " change";
    localStorage.setItem(`background${index}`, e.target.className);
  }

}
window.addEventListener("DOMContentLoaded", ()=>{
  show();
});
</code>```

Title: saving background color on localstorage

Body:
There is few errors in your code:

First:

btn.className = sessionStorage.getItem('background${index}') || 'buttons';

Should be:

btn.className = sessionStorage.getItem(`background${index}`) || 'buttons';

because you are create a string using Template literals (Template strings)

Second:

e.target.className += "change";

Should be:

e.target.className += " change";

You have to add space when concatenate strings, or else in your case it will not provide the intended behavior, since your code will add change class name to the previous class as one word.

Third:

sessionStorage.setItem(background${index}, e.target.className);

Should be:

sessionStorage.setItem(`background${index}`, e.target.className);

In your question you are talking about localStorage but you are
using sessionStorage, Still not sure if this what you want, so if you want it to be localStorage just replace sessionStorage with localStorage

// here i will be the data in form of table
// my algorithm comes here
// this function will get data from the localstorage
const get_todos = ()=>{
  let todos = new Array();
  let todos_str = localStorage.getItem("todo");
  if(todos_str !== null){
    todos = JSON.parse(todos_str);
  }
  return todos;
}
//this function will show the data in the localstorage in table format
const show = ()=>{
  let todos = get_todos();
  let text = "";
  for(let i = 0; i < todos.length; i++){
      let allData = todos[i];
      let eventName = allData.Eventname;
      let location = allData.Location;
      let date = allData.Date;
      text += "<tr>";
      text += "<td>" + eventName + "</td>";
      text += "<td>" + location + "</td>";
      text += "<td>" + date + "</td>";
      text += "<td>" + "<button class='buttons' type='button'>Pending</button>" + "</td>";
      text += "<td>" + "<i id='remove' class='fas fa-trash-alt btndelete'></i>" + "</td></tr>";

  }
  //the data gotten from the localstorage will be here
  let table = document.querySelector("#table > tbody");
  table.innerHTML = text;
  //this is where the button background color will change
window.addEventListener("load", ()=>{
    let thead = document.querySelector("#thead");
    let buttons = Array.from(document.querySelectorAll(".buttons"));
    thead.addEventListener("click", (e)=>{
      if(e.target.className === "buttons"){
        let index = buttons.indexOf(e.target);
        changeBackground(e, index);
      }
    });
    buttons.forEach(btn, index =>{
      btn.className = localStorage.getItem(`background${index}`) || 'buttons';

    });
  });
  const changeBackground = (e, index)=>{
    e.target.className += " change";
    localStorage.setItem(`background${index}`, e.target.className);
  }

}
window.addEventListener("DOMContentLoaded", ()=>{
  show();
});


问:
Same class in multiple files
Just for some practice, I'm looking at the different ways classes can be used within C++.

I've created the following project, which all I want to do is simply just ensure the same 'instance' of a class is being used across the project.

For example, I have main.cpp which has basic functionality which allows the user to set their health value. In path_one.cpp, I want to call the same class and display the same value as it does in main.cpp.

Here is the code for each file;

main.cpp

```<code>#include <iostream>
#include "player_class.h"
#include "path_one.h"
using namespace std;

int main()
{
    int set_health;
    Player player;
    cout << "Your Health is: " << player.health;

    cout << "\nSet your health:  ";
    cin >> set_health;
    player.health = set_health;
    cout << "Your Health is now: " << player.health;

    path_one();

    return 0;
}

</code>```

player_class.h

```<code>#pragma once

class Player
{
public:
    int health;
    int attack;
    int strength;
    int defence;

    Player()
    {
        health = 0;
        attack = 0;
        strength = 0;
        defence = 0;
    }
};
</code>```

path_one.cpp

```<code>#include <iostream>
#include "player_class.h"
#include "path_one.h"
using namespace std;

void path_one()
{
    Player player;

    printf("\n\nYour Health is: %d", player.health);
}
</code>```

path_one.h

```<code>#pragma once
#include "player_class.h"
#include "player_class.h"

void path_one();
</code>```

Once the 'Health' is set, and then goes into the path_one();, is to have it display the same value for health, rather than 'redefine' the class and display 0.

答:
The instance of player on path_one.cpp is local and it will be seen only in this function.

To all path_one calls see the same Player instance, you need to pass it by reference:

```<code>void path_one(Player& player) {
    printf("\n\nYour Health is: %d", player.health);
}
</code>```

You can create a singleton that is nothing more than a static instance of Player, but it is not recommended because in the end of day, singleton create unnecessarily structure to global variables and functions that you can better replace with namespaces definitions. Will get a more clear, simple and better code.

Title: Same class in multiple files

Body:
Just for some practice, I'm looking at the different ways classes can be used within C++.

I've created the following project, which all I want to do is simply just ensure the same 'instance' of a class is being used across the project.

For example, I have main.cpp which has basic functionality which allows the user to set their health value. In path_one.cpp, I want to call the same class and display the same value as it does in main.cpp.

Here is the code for each file;

main.cpp

#include <iostream>
#include "player_class.h"
#include "path_one.h"
using namespace std;

int main()
{
    int set_health;
    Player player;
    cout << "Your Health is: " << player.health;

    cout << "\nSet your health:  ";
    cin >> set_health;
    player.health = set_health;
    cout << "Your Health is now: " << player.health;

    path_one();

    return 0;
}

player_class.h

#pragma once

class Player
{
public:
    int health;
    int attack;
    int strength;
    int defence;

    Player()
    {
        health = 0;
        attack = 0;
        strength = 0;
        defence = 0;
    }
};

path_one.cpp

#include <iostream>
#include "player_class.h"
#include "path_one.h"
using namespace std;

void path_one()
{
    Player player;

    printf("\n\nYour Health is: %d", player.health);
}

path_one.h

#pragma once
#include "player_class.h"
#include "player_class.h"

void path_one();

Once the 'Health' is set, and then goes into the path_one();, is to have it display the same value for health, rather than 'redefine' the class and display 0.

Body:
The instance of player on path_one.cpp is local and it will be seen only in this function.

To all path_one calls see the same Player instance, you need to pass it by reference:

void path_one(Player& player) {
    printf("\n\nYour Health is: %d", player.health);
}

You can create a singleton that is nothing more than a static instance of Player, but it is not recommended because in the end of day, singleton create unnecessarily structure to global variables and functions that you can better replace with namespaces definitions. Will get a more clear, simple and better code.