问:
alternative to Google maps
My client wants some of the functionality of Google maps namely:
- geocoding
- generating maps with points based on postal code or long.lat
- optimal trip mapping

Their issues with Google maps
- cannot control outages
- postal codes are sometimes inaccurate or not updated frequently for Canada/UK
- they have no way to correct inaccurate information

They would prefer to host the mapping application themselves, but will require postal code updates.

Can anyone suggest such a product?

thanks

答:
"cannot control outages - postal codes are sometimes inaccurate or not updated frequently for Canada/UK - they have no way to correct inaccurate information"

Outages

hosting your own mapping is the only way to control this, but you would be very very hard pushed to beat Google Maps / Bing Maps uptime over the last 5 years. Take a look at the following:

OpenStreetMap for the road imagery data, this is open source data very good in the UK (Im not sure about canada) and you can make your own changes and submit them (or just change the data you have downloaded)

Geoserver, Mapnik or MapServer will read openstreetmapdata and create the image tiles needed to create your own maps in whatever style you wish. Depending on if you dont want all countries and all zoom levels these products can create all the tiles you will need in advance, but usually they have to be created in real time and cached. You need a BIG fast server to manage tile crunching

Openlayers or Leaflet are open source javascript mapping platforms that will display your tiles for you

Obviously this is just for road maps, aerial imagery would cost you an absolute fortune.

Post Code Data

Many people do not realize that UK postcode data for latitude and longitude is now completely free and available to download every quarter from the official source (ordinance survey) http://www.ordnancesurvey.co.uk/oswebsite/products/code-point-open/index.html.

This is the same data source Google will use and there is none better but it will always contain inaccuracies and always be a few months out of date.

Finally

Hopefully that answer the question you asked and gives you information to inform your client. Now for the question you didn't ask "Is this approach good value to my client?".

I won't presume to know your business or client, however what I described above is possible but with one to many months of work involved to get it all working together and even then it wont have any where near the performance or uptime of something like google /bing maps and only offers a small subset of their features.

Title: alternative to Google maps


来源: stackexchange

问:
TypeError: only size-1 arrays can be converted to Python scalars (matplotlib)
```<code>#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from random import random

#Show Images
image_show = True

#Parameters ( mm )
square_size = 50
room_width = 5000
room_length = 10000
n_guess = 50 # number of random points generated
max_cell_value = 255 # highest number in a cell.

#Handy functions for conversions
def mm2grid( mm):
    return int(mm/square_size)
def grid2mm( grid):
    return int(grid*square_size)
def rotation( theta):
    return np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])

# Build a simple empty map
map_floor = np.zeros((mm2grid(room_width), mm2grid(room_length)),)
# NOTE: Any cell >0 is considered occupied

print("Map size= {} cells".format( map_floor.shape))

# Set border walls
map_floor[ 0, :] = 255
map_floor[-1, :] = 255
map_floor[ :, 0] = 255
map_floor[ :,-1] = 255

#Draw something in the centre
map_floor[20:80,100:120] = 100

### Target Position ###
target = np.array([2500,0])

### Robot Position ###
x = np.array([1000,1000, np.pi*0])

# Randomly generate n_number of positions #
x_rand = np.zeros(( 3, n_guess))
for k in range( n_guess):
    x_rand[:,k] = np.array([ random()*room_width, random()* room_length, random()*3.14159])
    #remove any points inside a solid object
    if map_floor[ int(mm2grid( x_rand[0,k])), int(mm2grid( x_rand[1,k]))] > 0:
        x_rand[:,k] = 0

### TODO ###
#for n_number calculate angle to target#
#for n_number calculate distance measurement to nearest wall.

#### Display Map ####
# Remember: images are printed y inverted and x first.
if image_show:
    # Draw Map
    plt.matshow( max_cell_value-map_floor, cmap=plt.cm.gray) # max_cell_value is just to correct color scheme
    # Draw randomly positioned squares on the map
    plt.plot( [mm2grid( x_rand[1,:])], [mm2grid(x_rand[0,:])],'rx')
    # Draw Robot position
    plt.plot( [mm2grid( x[1])], [mm2grid(x[0])], 'b8', markersize=12)
    plt.plot( [mm2grid( x[1]), mm2grid( x[1]+ 300*np.cos(x[2]))],\
              [mm2grid( x[0]), mm2grid( x[0]+ 300*np.sin(x[2]))], 'b-', linewidth=2.5)
    plt.text( mm2grid( x[1]), mm2grid( x[0]+300), 'Robot', color='b')
    # Draw target
    plt.plot( [mm2grid( target[1])],[mm2grid( target[0])], 'g>', markersize=30)
    plt.text( mm2grid( target[1]), mm2grid( target[0] - 250), 'Target', color='g')
    # Draw line from robot to target
    plt.plot( [mm2grid( x[1]), mm2grid(target[1])],\
              [mm2grid( x[0]), mm2grid(target[0])], 'k--')
    # Show everything.
    plt.show()
</code>```

I am not sure how to fix the error.
in line 48 I changed xrange to range I also did some other things to some other places to fix and error I was getting in line 26 and it was saying

```<code>TypeError: 'float' object cannot be interpreted as an index
</code>```

But it looks like I have fixed those problems but I am not sure if I have messed something up somewhere and now it is giving me this error:

```<code>Map size= (100, 200) cells
Traceback (most recent call last):
  File "/Users/oscarwallace/Downloads/Map.py", line 64, in <module>
    plt.plot( [mm2grid( x_rand[1,:])], [mm2grid(x_rand[0,:])],'rx')
  File "/Users/oscarwallace/Downloads/Map.py", line 19, in mm2grid
    return int(mm/square_size)
TypeError: only size-1 arrays can be converted to Python scalars
</code>```

I was wondering if anyone knew what I have to do to sop this from happening. Thanks in advance.

答:
This error occurs when you're trying to cast into an integer something that isn't just one scalar. For instance, a ndarray with two elements. This is an example of this error:

```<code>import numpy as np

int(np.array([1, 3]))
</code>```

TypeError: only size-1 arrays can be converted to Python scalars

What you can do is use .astype(int)

```<code>(mm/square_size).astype(int)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from random import random

#Show Images
image_show = True

#Parameters ( mm )
square_size = 50
room_width = 5000
room_length = 10000
n_guess = 50 # number of random points generated
max_cell_value = 255 # highest number in a cell.

#Handy functions for conversions
def mm2grid( mm):
    return int(mm/square_size)
def grid2mm( grid):
    return int(grid*square_size)
def rotation( theta):
    return np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])

# Build a simple empty map
map_floor = np.zeros((mm2grid(room_width), mm2grid(room_length)),)
# NOTE: Any cell >0 is considered occupied

print("Map size= {} cells".format( map_floor.shape))

# Set border walls
map_floor[ 0, :] = 255
map_floor[-1, :] = 255
map_floor[ :, 0] = 255
map_floor[ :,-1] = 255

#Draw something in the centre
map_floor[20:80,100:120] = 100

### Target Position ###
target = np.array([2500,0])

### Robot Position ###
x = np.array([1000,1000, np.pi*0])

# Randomly generate n_number of positions #
x_rand = np.zeros(( 3, n_guess))
for k in range( n_guess):
    x_rand[:,k] = np.array([ random()*room_width, random()* room_length, random()*3.14159])
    #remove any points inside a solid object
    if map_floor[ int(mm2grid( x_rand[0,k])), int(mm2grid( x_rand[1,k]))] > 0:
        x_rand[:,k] = 0

### TODO ###
#for n_number calculate angle to target#
#for n_number calculate distance measurement to nearest wall.

#### Display Map ####
# Remember: images are printed y inverted and x first.
if image_show:
    # Draw Map
    plt.matshow( max_cell_value-map_floor, cmap=plt.cm.gray) # max_cell_value is just to correct color scheme
    # Draw randomly positioned squares on the map
    plt.plot( [mm2grid( x_rand[1,:])], [mm2grid(x_rand[0,:])],'rx')
    # Draw Robot position
    plt.plot( [mm2grid( x[1])], [mm2grid(x[0])], 'b8', markersize=12)
    plt.plot( [mm2grid( x[1]), mm2grid( x[1]+ 300*np.cos(x[2]))],\
              [mm2grid( x[0]), mm2grid( x[0]+ 300*np.sin(x[2]))], 'b-', linewidth=2.5)
    plt.text( mm2grid( x[1]), mm2grid( x[0]+300), 'Robot', color='b')
    # Draw target
    plt.plot( [mm2grid( target[1])],[mm2grid( target[0])], 'g>', markersize=30)
    plt.text( mm2grid( target[1]), mm2grid( target[0] - 250), 'Target', color='g')
    # Draw line from robot to target
    plt.plot( [mm2grid( x[1]), mm2grid(target[1])],\
              [mm2grid( x[0]), mm2grid(target[0])], 'k--')
    # Show everything.
    plt.show()

I am not sure how to fix the error.
in line 48 I changed xrange to range I also did some other things to some other places to fix and error I was getting in line 26 and it was saying

TypeError: 'float' object cannot be interpreted as an index

But it looks like I have fixed those problems but I am not sure if I have messed something up somewhere and now it is giving me this error:

Map size= (100, 200) cells
Traceback (most recent call last):
  File "/Users/oscarwallace/Downloads/Map.py", line 64, in <module>
    plt.plot( [mm2grid( x_rand[1,:])], [mm2grid(x_rand[0,:])],'rx')
  File "/Users/oscarwallace/Downloads/Map.py", line 19, in mm2grid
    return int(mm/square_size)
TypeError: only size-1 arrays can be converted to Python scalars

I was wondering if anyone knew what I have to do to sop this from happening. Thanks in advance.

Body:
This error occurs when you're trying to cast into an integer something that isn't just one scalar. For instance, a ndarray with two elements. This is an example of this error:

import numpy as np

int(np.array([1, 3]))

TypeError: only size-1 arrays can be converted to Python scalars

What you can do is use .astype(int)

(mm/square_size).astype(int)


问:
Does using a different linker produce different machine code?
If I write a complex program and build it, will the machine code generated at the end of the day be different if I use, say, ld vs lld vs gold?

答:
Yes and no. Linker will not, for example, change the optimization level after a compiler. It very slightly affects the code itself (mostly while it resolves symbol references). But speaking about the structure of the final executable, it may be very different. The same chunks of code and other resources can be rearranged different ways (most obvous is "removing vs keeping dead code").

So binary comparsion of files will find lots of differences, but in terms of machine code (it's structure and behavior) they'll be almost same.


问:
Building GCC-Ada, Syntax error compiling s-excmac.adb with very old gnatmake
I'm trying to update our 20-year old Ada compiler, however you need an Ada-compiler to build some parts of GCC+Ada (9.2.0).

The gnatmake is circa 2000, and it's possibly sub-calling GCC 2.8.1.  Sigh.

I have already successfully built several Ada parts of GCC, but this libgnat/ file eludes me:

Compiling libgnat/s-excmac.adb:

```<code>$ gnatmake s-excmac.adb
gcc -c -gnatpg s-excmac.adb
s-excmac.ads:134:44: identifier expected
gnatmake: "s-excmac.adb" compilation error
</code>```

So the problematic line in s-excmac.ads is:

```<code>   type GCC_Exception_Access is access all Unwind_Exception;
   --  Pointer to a GCC exception

   procedure Unwind_DeleteException (Excp : not null GCC_Exception_Access );  -- <-- THIS ONE!

   pragma Import (C, Unwind_DeleteException, "_Unwind_DeleteException");

   --  Procedure to free any GCC exception
</code>```

I don't understand what is wrong with this code.  Is there some turn-of-the-century Ada syntax replacement I can use to get this part of GCC-Ada compiled?

I'm a bit of an Ada NOOB, so please be gentle.

EDIT: Seems like trying to "repair" the s-excmac.adb / s-excmac.ads is a fool's errand.  The path of lesser resistance is to download a pre-built compiler, and start building the later GCC from that.

答:
Brian is right about the not null. But there are likely to be a lot more 2005-isms in the code ...

I believe the maintainers will only guarantee the ability to build a compiler using the previous release, which would imply building GCC 3, using that to build GCC 4, and so on; you might be able to skip a release or two. Long days ahead!

Body:
I'm trying to update our 20-year old Ada compiler, however you need an Ada-compiler to build some parts of GCC+Ada (9.2.0).

The gnatmake is circa 2000, and it's possibly sub-calling GCC 2.8.1.  Sigh.

I have already successfully built several Ada parts of GCC, but this libgnat/ file eludes me:

Compiling libgnat/s-excmac.adb:

$ gnatmake s-excmac.adb
gcc -c -gnatpg s-excmac.adb
s-excmac.ads:134:44: identifier expected
gnatmake: "s-excmac.adb" compilation error

So the problematic line in s-excmac.ads is:

   type GCC_Exception_Access is access all Unwind_Exception;
   --  Pointer to a GCC exception

   procedure Unwind_DeleteException (Excp : not null GCC_Exception_Access );  -- <-- THIS ONE!

   pragma Import (C, Unwind_DeleteException, "_Unwind_DeleteException");

   --  Procedure to free any GCC exception

I don't understand what is wrong with this code.  Is there some turn-of-the-century Ada syntax replacement I can use to get this part of GCC-Ada compiled?

I'm a bit of an Ada NOOB, so please be gentle.

EDIT: Seems like trying to "repair" the s-excmac.adb / s-excmac.ads is a fool's errand.  The path of lesser resistance is to download a pre-built compiler, and start building the later GCC from that.


问:
Django save() not sending to database
my from is not sending data to database
here is my view.py and form.py
And yet they are no error reported on my console

views.py

```<code>def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        return redirect('../login/')
    else:
        form = RegistrationForm()

        args = {'form': form}
        return render(request, 'account/register.html', args)
</code>```

forms.py

```<code>
class RegistrationForm(UserCreationForm):
    # first_name forms.CharField(... that i cut here to win some space
    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        if commit:
            user.save()

        return user
</code>```

答:
You forgot to call form.save() in your view. That's why your form is never saved.

Fix:

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        form.save()  # <- ATTENTION.
        return redirect('../login/')
    else:
        form = RegistrationForm()

    return render(request, 'account/register.html', {
        'form': form,
    })
```

Side notes

Don't hardcode the redirect path (i.e. ../login). In your urls.py file, give the url a name (e.g. path('login/', views.my_login, name='my_login')), and use the name to do the redirect (e.g. return redirect('my_login').

Title: Django save() not sending to database

Body:
my from is not sending data to database
here is my view.py and form.py
And yet they are no error reported on my console

views.py

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        return redirect('../login/')
    else:
        form = RegistrationForm()

        args = {'form': form}
        return render(request, 'account/register.html', args)

forms.py

class RegistrationForm(UserCreationForm):
    # first_name forms.CharField(... that i cut here to win some space
    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        if commit:
            user.save()

        return user

Body:
You forgot to call form.save() in your view. That's why your form is never saved.

Fix:

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        form.save()  # <- ATTENTION.
        return redirect('../login/')
    else:
        form = RegistrationForm()

    return render(request, 'account/register.html', {
        'form': form,
    })

Side notes

Don't hardcode the redirect path (i.e. ../login). In your urls.py file, give the url a name (e.g. path('login/', views.my_login, name='my_login')), and use the name to do the redirect (e.g. return redirect('my_login').


问:
How to change character encoding in php?
i m developing one site using wordpress deepfocus theme in that i want to show header in hebrew text but if i change name of header links in hebrew then it can not show any thing (e.g if i change Home to " לשוב " then it dont display on front end.</p>

答:
Be aware that you're dealing with encoding on both the server side and client side.

The php manual has tons of character encoding functions. It's always useful working in UTF-8:
http://php.net/manual/en/function.utf8-encode.php

Also, if you've never seen this, it's worth a read.
http://www.joelonsoftware.com/articles/Unicode.html

ContentLicense: CC BY-SA 3.0


问:
How to Scrape All posts of hashtag in instagram
I want to Scrape All the Post Containing some #hashtag from Instagram

I tried it from :
https://www.instagram.com/explore/tags/perfume/?__a=1

But It's only giving some posts not every post.

答:
You can use this library https://github.com/postaddictme/instagram-php-scraper/blob/master/examples/getMediasByTag.php

The function require a number of media as a parameter so if you want to recover all the media of a hashtags you will have to get the value of "graphql->hashtag->edge_hashtag_to_media->count" on the JSON feed https://www.instagram.com/explore/tags/perfume/?__a=1


问:
create tuple of nth element in the cartesian product of input vectors
I have a python function which returns the nth-element in the cartesian product of a number of input arrays

def prod(n, arrs):
    out = []

    for i,arr in enumerate(arrs):
        denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
        idx = n // denom % len(arr)
        out.append( arr[idx] )

    return out
```

<p>This works great:</p>

<pre class="lang-py prettyprint-override"><code>a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]

for n in range(20, 30):
    i = prod(n, [a, b, c])
    print(n, i)
</code>```

```<code>[1000, 3.0, -2]
[1000, 3.0, -1]
[1000, 3.0, 0]
[1000, 3.0, 1]
[1000, 3.0, 2]
[1000, 3.5, -2]
[1000, 3.5, -1]
[1000, 3.5, 0]
[1000, 3.5, 1]
[1000, 3.5, 2]
</code>```

Now I would like to translate this to C++ (max standard C++-17)

template<typename... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    // template magic here
}
```

Can someone help me with the template magic required to construct the tuple using the above formula?

答:
The other answers have already mentioned the indices trick. Here is my attempt at it, converted as directly as possible from your python code:

```<code>template <typename T, std::size_t... I>
auto prod_impl(std::size_t n, T tuple, std::index_sequence<I...>) {
    std::array sizes{ std::size(std::get<I>(tuple))... };
    auto enumerator = [&sizes,n](std::size_t i, auto&& arr) -> decltype(auto) {
        auto denom = std::accumulate(std::begin(sizes) + i + 1, std::end(sizes), 1, std::multiplies<>{});
        auto idx = (n / denom) % std::size(arr);
        return arr[idx];
    };

    return std::forward_as_tuple(enumerator(I, std::get<I>(tuple))...);
}

template<typename... Ts, typename Is = std::index_sequence_for<Ts...>>
auto prod(std::size_t n, const std::vector<Ts>&... vs) {
    return prod_impl(n, std::forward_as_tuple(vs...), Is{});
}
</code>```

(Live example: http://coliru.stacked-crooked.com/a/a8b975c29d429054)

Body:
I have a python function which returns the nth-element in the cartesian product of a number of input arrays

def prod(n, arrs):
    out = []

    for i,arr in enumerate(arrs):
        denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
        idx = n // denom % len(arr)
        out.append( arr[idx] )

    return out

This works great:

a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]

for n in range(20, 30):
    i = prod(n, [a, b, c])
    print(n, i)

[1000, 3.0, -2]
[1000, 3.0, -1]
[1000, 3.0, 0]
[1000, 3.0, 1]
[1000, 3.0, 2]
[1000, 3.5, -2]
[1000, 3.5, -1]
[1000, 3.5, 0]
[1000, 3.5, 1]
[1000, 3.5, 2]

Now I would like to translate this to C++ (max standard C++-17)

template<typename... Ts>
auto prod(std::size_t n, const std::vector<Ts>&... vs)
    -> std::tuple<const std::decay_t<typename std::vector<Ts>::value_type>&...>
{
    // template magic here
}

Can someone help me with the template magic required to construct the tuple using the above formula?

Body:
The other answers have already mentioned the indices trick. Here is my attempt at it, converted as directly as possible from your python code:

template <typename T, std::size_t... I>
auto prod_impl(std::size_t n, T tuple, std::index_sequence<I...>) {
    std::array sizes{ std::size(std::get<I>(tuple))... };
    auto enumerator = [&sizes,n](std::size_t i, auto&& arr) -> decltype(auto) {
        auto denom = std::accumulate(std::begin(sizes) + i + 1, std::end(sizes), 1, std::multiplies<>{});
        auto idx = (n / denom) % std::size(arr);
        return arr[idx];
    };

    return std::forward_as_tuple(enumerator(I, std::get<I>(tuple))...);
}

template<typename... Ts, typename Is = std::index_sequence_for<Ts...>>
auto prod(std::size_t n, const std::vector<Ts>&... vs) {
    return prod_impl(n, std::forward_as_tuple(vs...), Is{});
}

(Live example: http://coliru.stacked-crooked.com/a/a8b975c29d429054)


问:
Python: How to remove $ character from list after CSV import
I am attempting to import a CSV file into Python. After importing the CSV, I want to take an every of every ['Spent Past 6 Months'] value, however the "$" symbol that the CSV includes in front of that value is causing me problems. I've tried a number of things to get rid of that symbol and I'm honestly lost at this point!

I'm really new to Python, so I apologize if there is something very simple here that I am missing.

What I have coded is listed below. My output is listed first:

```<code>
      File "customer_regex2.py", line 24, in <module>
        top20Cust = top20P(data)
      File "customer_regex2.py", line 15, in top20P
        data1 += data1 + int(a[i]['Spent Past 6 Months'])
    ValueError: invalid literal for int() with base 10: '$2099.83'

</code>```

error screenshot

```<code>
    import csv
    import re
    data = []

    with open('customerData.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
          data.append(row)

    def top20P(a):
      outputList=[]
      data1=0

      for i in range(0,len(a)):
        data1 += data1 + int(a[i]['Spent Past 6 Months'])
      top20val= int(data1*0.8)

      for j in range(0,len(a)):
        if data[j]['Spent Past 6 Months'] >= top20val:
          outputList.append('a[j]')

      return outputList

    top20Cust = top20P(data)
    print(outputList)

</code>```

答:
It looks like a datatype issue.

You could strip the $ characters like so:

someString = '$2099.83'
someString = someString.strip('$')
print(someString)
2099.83
```

<p>Now the last step is to wrap in float() since you have decimal values.</p>

<pre class="lang-py prettyprint-override"><code>print(type(someString))
<class 'str'>

someFloat = float(someString)

print(type(someFloat))
<class 'float'>
</code>```

Hope that helps.

Body:
I am attempting to import a CSV file into Python. After importing the CSV, I want to take an every of every ['Spent Past 6 Months'] value, however the "$" symbol that the CSV includes in front of that value is causing me problems. I've tried a number of things to get rid of that symbol and I'm honestly lost at this point!

I'm really new to Python, so I apologize if there is something very simple here that I am missing.

What I have coded is listed below. My output is listed first:

      File "customer_regex2.py", line 24, in <module>
        top20Cust = top20P(data)
      File "customer_regex2.py", line 15, in top20P
        data1 += data1 + int(a[i]['Spent Past 6 Months'])
    ValueError: invalid literal for int() with base 10: '$2099.83'

error screenshot

    import csv
    import re
    data = []

    with open('customerData.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
          data.append(row)

    def top20P(a):
      outputList=[]
      data1=0

      for i in range(0,len(a)):
        data1 += data1 + int(a[i]['Spent Past 6 Months'])
      top20val= int(data1*0.8)

      for j in range(0,len(a)):
        if data[j]['Spent Past 6 Months'] >= top20val:
          outputList.append('a[j]')

      return outputList

    top20Cust = top20P(data)
    print(outputList)

Body:
It looks like a datatype issue.

You could strip the $ characters like so:

someString = '$2099.83'
someString = someString.strip('$')
print(someString)
2099.83

Now the last step is to wrap in float() since you have decimal values.

print(type(someString))
<class 'str'>

someFloat = float(someString)

print(type(someFloat))
<class 'float'>

Hope that helps.


问:
Cannot start a service instance in Virtuoso-opensource
I'm trying to create and start the service instance. But it doesn't start.
Here is the command I ran:

```<code>virtuoso-t +service start +instance MyService
</code>```

Here my output:

```<code>The Virtuoso_MyService service is being started
</code>```

But the localhost:8890 cannot be loaded.

Details:

Opened CMD as administrator.

Ran the same commands 3 days back and the services were running fine till I restarted the system.

Commands followed.

```<code>C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\bin>virtuoso-t +service create +instance MyService +configfile ..\database\virtuoso.ini

[Using virtuoso.ini in C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\database]
The Virtuoso_MyService service has been registered
  and is associated with the executable

C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\bin\virtuoso-t.exe

C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\bin>virtuoso-t +service start +instance MyService
The Virtuoso_MyService service is being started

C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\bin>virtuoso-t +service list +instance MyService
MyService            Stopped
</code>```

As suggested by @TallTed, I have added the log:

```<code>            Wed Mar 01 2017
16:27:37 { Loading plugin 1: Type `plain', file `wikiv' in `../hosting'
16:27:37   WikiV version 0.6 from OpenLink Software
16:27:37   Support functions for WikiV collaboration tool
16:27:37   SUCCESS plugin 1: loaded from ..\hosting\wikiv.dll }
16:27:37 { Loading plugin 2: Type `plain', file `mediawiki' in `../hosting'
16:27:37   MediaWiki version 0.1 from OpenLink Software
16:27:37   Support functions for MediaWiki collaboration tool
16:27:37   SUCCESS plugin 2: loaded from ..\hosting\mediawiki.dll }
16:27:37 { Loading plugin 3: Type `plain', file `creolewiki' in `../hosting'
16:27:37   CreoleWiki version 0.1 from OpenLink Software
16:27:37   Support functions for CreoleWiki collaboration tool
16:27:37   SUCCESS plugin 3: loaded from ..\hosting\creolewiki.dll }
16:27:37 { Loading plugin 4: Type `plain', file `im' in `../hosting'
16:27:37   IM version 0.6 from OpenLink Software
16:27:37   Support functions for Image Magick 6.6.7
16:27:37   SUCCESS plugin 4: loaded from ..\hosting\im.dll }
16:27:37 { Loading plugin 5: Type `plain', file `wbxml2' in `../hosting'
16:27:37   WBXML2 version 0.9 from OpenLink Software
16:27:37   Support functions for WBXML2 0.10.7 Library
16:27:37   SUCCESS plugin 5: loaded from ..\hosting\wbxml2.dll }
16:27:37 Unable to create file virtuoso.lck (File exists).
16:27:37 This probably means you either do not have permission to start
16:27:37 this server, or that virtuoso-t is already running.
16:27:37 If you are absolutely sure that this is not the case, please try
16:27:37 to remove the file virtuoso.lck and start again.
</code>```

答:
I was having the same issues on windows 10. I fixed by going to my

```<code>C:\Program Files\OpenLink Software\Virtuoso OpenSource 7.2\database
</code>```

and manually delete virtuoso.lck file

The restart my server and everything now started working fine!

Body:
I'm trying to create and start the service instance. But it doesn't start.
Here is the command I ran:

virtuoso-t +service start +instance MyService

Here my output:

The Virtuoso_MyService service is being started

But the localhost:8890 cannot be loaded.

Details:

Opened CMD as administrator.

Ran the same commands 3 days back and the services were running fine till I restarted the system.

Commands followed.

C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\bin>virtuoso-t +service create +instance MyService +configfile ..\database\virtuoso.ini

[Using virtuoso.ini in C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\database]
The Virtuoso_MyService service has been registered
  and is associated with the executable

C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\bin\virtuoso-t.exe

C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\bin>virtuoso-t +service start +instance MyService
The Virtuoso_MyService service is being started

C:\Users\username\Desktop\foldername\MyWork\virtuoso-opensource\bin>virtuoso-t +service list +instance MyService
MyService            Stopped

As suggested by @TallTed, I have added the log:

            Wed Mar 01 2017
16:27:37 { Loading plugin 1: Type `plain', file `wikiv' in `../hosting'
16:27:37   WikiV version 0.6 from OpenLink Software
16:27:37   Support functions for WikiV collaboration tool
16:27:37   SUCCESS plugin 1: loaded from ..\hosting\wikiv.dll }
16:27:37 { Loading plugin 2: Type `plain', file `mediawiki' in `../hosting'
16:27:37   MediaWiki version 0.1 from OpenLink Software
16:27:37   Support functions for MediaWiki collaboration tool
16:27:37   SUCCESS plugin 2: loaded from ..\hosting\mediawiki.dll }
16:27:37 { Loading plugin 3: Type `plain', file `creolewiki' in `../hosting'
16:27:37   CreoleWiki version 0.1 from OpenLink Software
16:27:37   Support functions for CreoleWiki collaboration tool
16:27:37   SUCCESS plugin 3: loaded from ..\hosting\creolewiki.dll }
16:27:37 { Loading plugin 4: Type `plain', file `im' in `../hosting'
16:27:37   IM version 0.6 from OpenLink Software
16:27:37   Support functions for Image Magick 6.6.7
16:27:37   SUCCESS plugin 4: loaded from ..\hosting\im.dll }
16:27:37 { Loading plugin 5: Type `plain', file `wbxml2' in `../hosting'
16:27:37   WBXML2 version 0.9 from OpenLink Software
16:27:37   Support functions for WBXML2 0.10.7 Library
16:27:37   SUCCESS plugin 5: loaded from ..\hosting\wbxml2.dll }
16:27:37 Unable to create file virtuoso.lck (File exists).
16:27:37 This probably means you either do not have permission to start
16:27:37 this server, or that virtuoso-t is already running.
16:27:37 If you are absolutely sure that this is not the case, please try
16:27:37 to remove the file virtuoso.lck and start again.

Body:
I was having the same issues on windows 10. I fixed by going to my

C:\Program Files\OpenLink Software\Virtuoso OpenSource 7.2\database

and manually delete virtuoso.lck file

The restart my server and everything now started working fine!


问:
re.findall with negative numbers, my code only works on positive numbers
I am trying to get a number from a program on my screen using OpenCV.
I have the exact spot on the screen that the value is at and I am able to use image to text recognition to turn the live updating image into text.
the text I get is a string as follows (profit: 12.34, whatever it is at the time)
I am for some reason unable to just get the number so I am using re.findall to get the number in the string. it works like a hot damn as long as the value is >= 0 . I get a returned value as a float. works perfect. but the second the number goes negative I get this error message

```<code>  File "C:/Users/austi/.spyder-py3/OpenCV_Files/Closest_workingCV.py", line 55, in <module>
    price = re.findall("\d+", text)[0]

IndexError: list index out of range
</code>```

here is my code thus far

```<code>

import numpy as np
from PIL import ImageGrab
import cv2
import time
import pytesseract
import re

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

while True:
    def process_img(original_image):
        processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
        return processed_img

    def process_img1(original_image1):
        processed_img1 = cv2.cvtColor(original_image1, cv2.COLOR_BGR2GRAY)
        processed_img1 = cv2.Canny(processed_img1, threshold1=200, threshold2=300)
        return processed_img1

    coor1 = (20, 150, 950, 950)
    coor2 = (60, 550, 250, 590)
#    coor3 = (20, 150, 950, 950)

    #last_time = time.time()
    for i in range(2):
        if i == 0:
            x = coor1
            screen = np.array(ImageGrab.grab(bbox=(x)))
            new_screen = process_img(screen)
            #screen('Loop took {} seconds'.format(time.time()-last_time))
            #last_time = time.time()
            cv2.imshow('window', new_screen)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
        elif  i == 1:
            x = coor2
            screen1 = np.array(ImageGrab.grab(bbox=(x)))
            new_screen1 = process_img(screen1)
            cv2.imshow('window1', new_screen1)
            text = pytesseract.image_to_string(new_screen1)
            #price = text.split(":")[1]
            price = re.findall("\d+", text)[0]
            #rint(repr(text))
            #price = re.findall("\d+","Foo -111 Bar 55", text)
            price = float(price)
            #text = [float(s) for s in re.findall(r'-?\d+\.?\d*', text)]
            #print(text)
            print(price)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break

</code>```

like I said it updates that number multiple times a second flawlessly so long as its not a negative number.
anyone have any suggestions on how to fix this? or any better ways to get to my end goal.
I've searched and found similar issues but when I implement any proposed solutions that I have found it either flat out does not work for any number or I have the same issue of only numbers 0 or greater. not sure what to do please help. i included the snippet of my screen that the code is looking at
Thanks

答:
I don't think the problem is with the regex itself, except that it can be expanded to catch the negative sign. I've reworked your code to deal with error cases:</p>

```<code>        screen1 = np.array(ImageGrab.grab(bbox=(x)))
        new_screen1 = process_img(screen1)
        cv2.imshow('window1', new_screen1)
        text = pytesseract.image_to_string(new_screen1)

        if text:
            # test code to show the text to scan
            print("text to scan:", repr(text))
            try:
                price = re.findall("-?\d+", text)[0]
                print(price)
                if cv2.waitKey(25) & 0xFF == ord('q'):
                    cv2.destroyAllWindows()
                    break
                else:
                    pass
            except IndexError:
                print("No price found")
        else:
            print("No text to scan")
</code>```

Body:
I am trying to get a number from a program on my screen using OpenCV.
I have the exact spot on the screen that the value is at and I am able to use image to text recognition to turn the live updating image into text.
the text I get is a string as follows (profit: 12.34, whatever it is at the time)
I am for some reason unable to just get the number so I am using re.findall to get the number in the string. it works like a hot damn as long as the value is >= 0 . I get a returned value as a float. works perfect. but the second the number goes negative I get this error message

  File "C:/Users/austi/.spyder-py3/OpenCV_Files/Closest_workingCV.py", line 55, in <module>
    price = re.findall("\d+", text)[0]

IndexError: list index out of range

here is my code thus far

import numpy as np
from PIL import ImageGrab
import cv2
import time
import pytesseract
import re

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

while True:
    def process_img(original_image):
        processed_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
        return processed_img

    def process_img1(original_image1):
        processed_img1 = cv2.cvtColor(original_image1, cv2.COLOR_BGR2GRAY)
        processed_img1 = cv2.Canny(processed_img1, threshold1=200, threshold2=300)
        return processed_img1

    coor1 = (20, 150, 950, 950)
    coor2 = (60, 550, 250, 590)
#    coor3 = (20, 150, 950, 950)

    #last_time = time.time()
    for i in range(2):
        if i == 0:
            x = coor1
            screen = np.array(ImageGrab.grab(bbox=(x)))
            new_screen = process_img(screen)
            #screen('Loop took {} seconds'.format(time.time()-last_time))
            #last_time = time.time()
            cv2.imshow('window', new_screen)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
        elif  i == 1:
            x = coor2
            screen1 = np.array(ImageGrab.grab(bbox=(x)))
            new_screen1 = process_img(screen1)
            cv2.imshow('window1', new_screen1)
            text = pytesseract.image_to_string(new_screen1)
            #price = text.split(":")[1]
            price = re.findall("\d+", text)[0]
            #rint(repr(text))
            #price = re.findall("\d+","Foo -111 Bar 55", text)
            price = float(price)
            #text = [float(s) for s in re.findall(r'-?\d+\.?\d*', text)]
            #print(text)
            print(price)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break

like I said it updates that number multiple times a second flawlessly so long as its not a negative number.
anyone have any suggestions on how to fix this? or any better ways to get to my end goal.
I've searched and found similar issues but when I implement any proposed solutions that I have found it either flat out does not work for any number or I have the same issue of only numbers 0 or greater. not sure what to do please help. i included the snippet of my screen that the code is looking at
Thanks

Body:
I don't think the problem is with the regex itself, except that it can be expanded to catch the negative sign. I've reworked your code to deal with error cases:

        screen1 = np.array(ImageGrab.grab(bbox=(x)))
        new_screen1 = process_img(screen1)
        cv2.imshow('window1', new_screen1)
        text = pytesseract.image_to_string(new_screen1)

        if text:
            # test code to show the text to scan
            print("text to scan:", repr(text))
            try:
                price = re.findall("-?\d+", text)[0]
                print(price)
                if cv2.waitKey(25) & 0xFF == ord('q'):
                    cv2.destroyAllWindows()
                    break
                else:
                    pass
            except IndexError:
                print("No price found")
        else:
            print("No text to scan")


问:
Bad interpreter file not found error when running flask commands
Whenever I run a flask command in my project, I get an error of the form zsh: (correct file path)/venv/bin/flask: bad interpreter: (incorrect, old file path)/venv/bin/python3. I believe the error is due to the file paths not matching, and the second file path no longer existing. I changed the name of the directory for my project when I changed the name of the project, but I don't know how to change the path that flask searches for the interpreter in.

Thanks in advance.

Edit: I just tried going into the flask file at (correct file path)/venv/bin. I saw that it still had #!(incorrect, old file path)/venv/bin/python3 at the top. I tried changing this to #!(correct file path)/venv/bin/python3, but the same error as before persisted, as well as the flask app not being able to find the flask_login module, which it was not having issues with before.

答: Ok, I figured out how to fix it. I had to go into my (correct file path)/venv/bin/flask file and change the file path after the #! to the correct file path. I had to do the same for pip, pip3, and pip3.7 which were all in the same location as the flask file. Then I had to reinstall the flask_login package. This fixed everything.</p>


问:
How to link MemCached server together?
I'm looking into using MemCached for a web application I am developing and after researching MemCached over the past few days, I have come across a question I could not find the answer to.

How do you link Memcached server together or how do you replicate data between MemCached server?

Additionally: Is this functionality controlled by the servers or the clients and how?

答:
http://repcached.lab.klab.org/

Also, the PHP PECL memcache client can replicate data to multiple servers, see memcache.redundancy.

OwnerDisplayName: GateKiller

ContentLicense: CC BY-SA 2.5

Title: How to link MemCached server together?

LastEditorDisplayName: GateKiller

OwnerDisplayName: Daniel Von Fange


问:
Help with Exception handlin in finally block
I am trying to catch an exception using a try-catch-finally block. i have caught the exception in the catch block and passed it to the finally block using a global exception variable. Doing so, i have handled the exception scenario in the finally block. I know this sounds wierd, but theres a need to do so. Please let me know if there is any coding standard issue with the same. Also if you can suggest something on the same, i will be really obliged.

Thanks.

答:
The try-catch-finally pattern is a very useful and powerful pattern, if used as intended. Handling exceptions in the finally block is not recommended and does not make much (any?) sense.

Try to reorganize your code to fit the pattern, not the other way around.

Small example:

```<code>var reader = new StreamReader(path);
try
{
   // Do your work here
   reader.ReadToEnd();
}
catch (IOException ex)
{
    // Handle specific error here
    ShowUserError(ex.Message);
}
catch (Exception ex)
{
    // Handle general error here
    LogError(ex);
}
finally
{
   // Perform clean up here
   // This code will run regardless if there was an error or not
   reader.Close();
}
</code>```

Also, have a look at the MSDN documentation for Try...Catch...Finally Statements.

Body:
The try-catch-finally pattern is a very useful and powerful pattern, if used as intended. Handling exceptions in the finally block is not recommended and does not make much (any?) sense.

Try to reorganize your code to fit the pattern, not the other way around.

Small example:

var reader = new StreamReader(path);
try
{
   // Do your work here
   reader.ReadToEnd();
}
catch (IOException ex)
{
    // Handle specific error here
    ShowUserError(ex.Message);
}
catch (Exception ex)
{
    // Handle general error here
    LogError(ex);
}
finally
{
   // Perform clean up here
   // This code will run regardless if there was an error or not
   reader.Close();
}

Also, have a look at the MSDN documentation for Try...Catch...Finally Statements.


问:
Train deep classification model with different color features
I have a simple sequential deep model as below, which performs a binary classification. I pass the 3 color channels of my dataset images to the model for training. How can I add grayscale as the 4th channel to my model? What changes do I need to make?</p>

```<code>from keras.models import Sequential, load_model, Model
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from PIL import Image
from random import shuffle, choice
import numpy as np
import os
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras import optimizers

IMAGE_SIZE = 300
epochs_num = 100
batch_size = 64
IMAGE_DIRECTORY = './data'

def label_img(name):
    if name == 'fire': return np.array([1, 0])
    elif name == 'none' : return np.array([0, 1])

def load_data():
    print("Loading images...")
    train_data = []
    directories = next(os.walk(IMAGE_DIRECTORY))[1]

    for dirname in directories:
        print("Loading {0}".format(dirname))
        file_names = next(os.walk(os.path.join(IMAGE_DIRECTORY, dirname)))[2]
        for i in range(len(file_names)):
            image_name = choice(file_names)
            image_path = os.path.join(IMAGE_DIRECTORY, dirname, image_name)
            label = label_img(dirname)
            if "DS_Store" not in image_path:
                img = Image.open(image_path)
                img = img.resize((IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS)
                train_data.append([np.array(img), label])
    shuffle(train_data)
    return train_data

def create_model():
    model = Sequential()
    model.add(Conv2D(32, kernel_size = (5, 5), activation='relu', input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(BatchNormalization())
    model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(BatchNormalization())
    model.add(Conv2D(128, kernel_size=(3,3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(BatchNormalization())
    model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(BatchNormalization())
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(256, activation='relu'))
    model.add(Dropout(0.2))
    model.add(Dense(128, activation='relu'))
    model.add(Dense(2, activation = 'softmax'))

    return model

training_data = load_data()
training_images = np.array([i[0] for i in training_data])
training_labels = np.array([i[1] for i in training_data])

print(str(len(training_images)))
# Split the data
training_images, validation_images, training_labels, validation_labels = train_test_split(training_images, training_labels, test_size=0.2, shuffle= True)
print(str(len(training_images)))

print('creating model')
#========================
model = create_model()
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

filepath="./checkpoints/model_{epoch:03d}_{accuracy:.4f}_{val_accuracy:.4f}_{val_loss:.7f}.h5"
checkpoint = ModelCheckpoint(filepath, monitor=["accuracy"], verbose=1, mode='max', save_weights_only=False)
callbacks_list = [checkpoint]

datagen = ImageDataGenerator(zoom_range=0.2, horizontal_flip=True)
datagen.fit(training_images)
train_gen=datagen.flow(training_images, training_labels, batch_size=batch_size)
#validation
val_datagen = ImageDataGenerator(horizontal_flip=True)
val_datagen.fit(training_images)
val_gen=datagen.flow(validation_images, validation_labels, batch_size=batch_size)
model.fit(train_gen, validation_data=val_gen, epochs=epochs_num, verbose=1, callbacks=callbacks_list)
</code>```

答: i dont't think that you need to add gray scale and i 'm not sure if you can "add" it as an extra channel. Gray scale image is an image that RGB values are the same on the same pixel. You can train your classifier to classify gray scale images or coloured ones or both (not recommended). But if your raw data is coloured images keep them as they are and use data augmentation if you need more.  </p>

Body:
I have a simple sequential deep model as below, which performs a binary classification. I pass the 3 color channels of my dataset images to the model for training. How can I add grayscale as the 4th channel to my model? What changes do I need to make?

from keras.models import Sequential, load_model, Model
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from PIL import Image
from random import shuffle, choice
import numpy as np
import os
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras import optimizers

IMAGE_SIZE = 300
epochs_num = 100
batch_size = 64
IMAGE_DIRECTORY = './data'

def label_img(name):
    if name == 'fire': return np.array([1, 0])
    elif name == 'none' : return np.array([0, 1])

def load_data():
    print("Loading images...")
    train_data = []
    directories = next(os.walk(IMAGE_DIRECTORY))[1]

    for dirname in directories:
        print("Loading {0}".format(dirname))
        file_names = next(os.walk(os.path.join(IMAGE_DIRECTORY, dirname)))[2]
        for i in range(len(file_names)):
            image_name = choice(file_names)
            image_path = os.path.join(IMAGE_DIRECTORY, dirname, image_name)
            label = label_img(dirname)
            if "DS_Store" not in image_path:
                img = Image.open(image_path)
                img = img.resize((IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS)
                train_data.append([np.array(img), label])
    shuffle(train_data)
    return train_data

def create_model():
    model = Sequential()
    model.add(Conv2D(32, kernel_size = (5, 5), activation='relu', input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(BatchNormalization())
    model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(BatchNormalization())
    model.add(Conv2D(128, kernel_size=(3,3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(BatchNormalization())
    model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(BatchNormalization())
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(256, activation='relu'))
    model.add(Dropout(0.2))
    model.add(Dense(128, activation='relu'))
    model.add(Dense(2, activation = 'softmax'))

    return model

training_data = load_data()
training_images = np.array([i[0] for i in training_data])
training_labels = np.array([i[1] for i in training_data])

print(str(len(training_images)))
# Split the data
training_images, validation_images, training_labels, validation_labels = train_test_split(training_images, training_labels, test_size=0.2, shuffle= True)
print(str(len(training_images)))

print('creating model')
#========================
model = create_model()
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

filepath="./checkpoints/model_{epoch:03d}_{accuracy:.4f}_{val_accuracy:.4f}_{val_loss:.7f}.h5"
checkpoint = ModelCheckpoint(filepath, monitor=["accuracy"], verbose=1, mode='max', save_weights_only=False)
callbacks_list = [checkpoint]

datagen = ImageDataGenerator(zoom_range=0.2, horizontal_flip=True)
datagen.fit(training_images)
train_gen=datagen.flow(training_images, training_labels, batch_size=batch_size)
#validation
val_datagen = ImageDataGenerator(horizontal_flip=True)
val_datagen.fit(training_images)
val_gen=datagen.flow(validation_images, validation_labels, batch_size=batch_size)
model.fit(train_gen, validation_data=val_gen, epochs=epochs_num, verbose=1, callbacks=callbacks_list)


问:
Swift: Is it possible to use delegation when both views aren't in direct connection with each other?
I have three ViewController: ViewController1, ViewController2 and ViewController3.

ViewController1 pushes ViewController2 on the screen and both views can interact with each other through delegation.

ViewController2 pushes ViewController3 on the screen.

Now is it possible to establish a delegation between ViewController1 and ViewController3? I want ViewController3 to be able to manipulate a label of ViewController1.

答:
Best way in this scenario would be Notification Pattern

```<code>  // Notification posting
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "fromViewController3"), object: nil, userInfo: myDict)

 // Register in ViewController1 to receive notification in your class ViewController1
 NotificationCenter.default.addObserver(self, selector: #selector(self.manipulateMyLabel(_:)), name: NSNotification.Name(rawValue: "fromViewController3"), object: nil)

 // handle notification
 func manipulateMyLabel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let newString = dict["labelValue"] as? String {
               // user newString to update the label text or something.
            }
        }
 }
</code>```

Body:
Best way in this scenario would be Notification Pattern

  // Notification posting
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "fromViewController3"), object: nil, userInfo: myDict)

 // Register in ViewController1 to receive notification in your class ViewController1
 NotificationCenter.default.addObserver(self, selector: #selector(self.manipulateMyLabel(_:)), name: NSNotification.Name(rawValue: "fromViewController3"), object: nil)

 // handle notification
 func manipulateMyLabel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let newString = dict["labelValue"] as? String {
               // user newString to update the label text or something.
            }
        }
 }


问:
Numpy matrix flattens to a matrix
I am having issues flatting the following matrix into an array

```<code>np.matrix([[1],
        [2],
        [3]])
</code>```

More generally this matrix will be n,1 shape

The goal is to get it to be in a 3, form like [1, 2, 3] however I am finding that difficult. Every operation I can find returns a matrix or does not work.

```<code>x = np.matrix([[1],
        [2],
        [3]])
x.flatten()
>>>matrix([[1, 2, 3]])
x.ravel()
>>>matrix([[1, 2, 3]])
x.ravel()[0,:]
>>>matrix([[1, 2, 3]])
np.reshape(x, 3)
>>>matrix([[1, 2, 3]])
x.flatten()[0]
>>>matrix([[1, 2, 3]])
</code>```

How can I get this one row-ed matrix into a vector?

答:
You need to convert it to an array. Matrix objects are 2-dimensional by definition.

```<code>np.array(x).flatten()
</code>```

Alternatively, as mentioned by @hpaulj, matrix objects have A and A1 defined that will return the array object (flattened for A1)

```<code>x.A1
</code>```

Title: Numpy matrix flattens to a matrix

Body:
I am having issues flatting the following matrix into an array

np.matrix([[1],
        [2],
        [3]])

More generally this matrix will be n,1 shape

The goal is to get it to be in a 3, form like [1, 2, 3] however I am finding that difficult. Every operation I can find returns a matrix or does not work.

x = np.matrix([[1],
        [2],
        [3]])
x.flatten()
>>>matrix([[1, 2, 3]])
x.ravel()
>>>matrix([[1, 2, 3]])
x.ravel()[0,:]
>>>matrix([[1, 2, 3]])
np.reshape(x, 3)
>>>matrix([[1, 2, 3]])
x.flatten()[0]
>>>matrix([[1, 2, 3]])

How can I get this one row-ed matrix into a vector?

Body:
You need to convert it to an array. Matrix objects are 2-dimensional by definition.

np.array(x).flatten()

Alternatively, as mentioned by @hpaulj, matrix objects have A and A1 defined that will return the array object (flattened for A1)

x.A1


问:
Test null hypothesis that regression coefficient equals a nonzero value in statsmodels OLS
In Python statsmodels, calling summary() on an OLS model gives the p value for coefficients equaling zero. Is there a way to test that the coefficient equals some nonzero value?

This CrossValidated question shows that offset() can be used for this in R.

答:
You can use a trick repametrizing y~x into y - T*x ~ x where T is the tested value.

If you want to be more formal you can take the coefficient and its standard error and compute

and then the d.f for the t are the same as they would be for a test with for .

Moreover you can get the p-value from the t-value using the function pt().


问:
Use Regex to find pattern that includes special characters and reject if they follow other patterns
I want to find one of this patterns within a text:

```<code>space or line start + 4 digits + space or line end

space or line start + 4 digits + "-" (optional) + 1 character (digit or letter "x") + space or line end
</code>```

It would look like any of this:

```<code>8638-x
86381
8638-1
8638
</code>```

I tried to use the below but, according to regex101.com, the "-x" is not being selected

```<code>(\d{4})|((\d{4}\-\d{1})|(\d{4}\-(?i)[x]))
</code>```

It is important that the below pattern is rejected if found (in case my OCR fails to structure properly):

```<code>"\d{3}\.?\d{3}?\d{3}\-?\d{2}"
</code>```

答:
You could match 4 digits followed by an optional group that would match an optional hyphen and either a digits or a x

```<code>\b\d{4}(?:-?[\dx])?\b
</code>```

\b Word boundary

\d{4} Match 4 digits

(?: Non capture group

-?[\dx] Match optional - and either a digit or x

)? Close group and make it optional

\b Word boundary

Regex demo

If lookarounds are supported, you might use:

```<code>(?<!\S)\d{4}(?:-?[\dx])?(?!\S)
</code>```

Regex demo

Body:
I want to find one of this patterns within a text:

space or line start + 4 digits + space or line end

space or line start + 4 digits + "-" (optional) + 1 character (digit or letter "x") + space or line end

It would look like any of this:

8638-x
86381
8638-1
8638

I tried to use the below but, according to regex101.com, the "-x" is not being selected

(\d{4})|((\d{4}\-\d{1})|(\d{4}\-(?i)[x]))

It is important that the below pattern is rejected if found (in case my OCR fails to structure properly):

"\d{3}\.?\d{3}?\d{3}\-?\d{2}"

Body:
You could match 4 digits followed by an optional group that would match an optional hyphen and either a digits or a x

\b\d{4}(?:-?[\dx])?\b

\b Word boundary

\d{4} Match 4 digits

(?: Non capture group

-?[\dx] Match optional - and either a digit or x

)? Close group and make it optional

\b Word boundary

Regex demo

If lookarounds are supported, you might use:

(?<!\S)\d{4}(?:-?[\dx])?(?!\S)

Regex demo


问:
Getting User Media with Instagram Basic Display API
I would like to retrieve photos from an account with the Instagram Display API but I can't find anything on the documentation.

The closest thing to that is this https://developers.facebook.com/docs/instagram-basic-display-api/guides/getting-profiles-and-media?locale=en_US but it only allows you to recover photos of the person connected to the API. However, I would like to be able to recover photos of anyone from their username, or from a hashtag.

```<code>GET /me?fields={media}&access_token={access-token}
</code>```

I also found this https://developers.facebook.com/docs/instagram-basic-display-api/reference/user/media but it is nowhere explained how to get someone's user-id from a username.

```<code>GET https://graph.instagram.com/{user-id}/media?access_token={access-token}
</code>```

I find a way to do it without Instagram API (Sources https://stackoverflow.com/a/33783840/12739212) but I'm afraid they will change their code and therefore this solution will no longer work so I would like to do it with the Instagram API

```<code>        $html = file_get_contents('https://instagram.com/' . $username . '/');
        preg_match('/_sharedData = ({.*);<\/script>/', $html, $matches);
        $profil_data = json_decode($matches[1])->entry_data->ProfilePage[0]->graphql->user;
        $data_edges = $profil_data->edge_owner_to_timeline_media->edges;

        foreach ($data_edges as $key => $value) {
            $img_url = $value->node->display_url;
            echo "<img src=" . $img_url . ">";
        }
</code>```

Thanks in advance.

答: So I finally gave up using the API and used this library instead https://github.com/postaddictme/instagram-php-scraper</p>

Body:
I would like to retrieve photos from an account with the Instagram Display API but I can't find anything on the documentation.

The closest thing to that is this https://developers.facebook.com/docs/instagram-basic-display-api/guides/getting-profiles-and-media?locale=en_US but it only allows you to recover photos of the person connected to the API. However, I would like to be able to recover photos of anyone from their username, or from a hashtag.

GET /me?fields={media}&access_token={access-token}

I also found this https://developers.facebook.com/docs/instagram-basic-display-api/reference/user/media but it is nowhere explained how to get someone's user-id from a username.

GET https://graph.instagram.com/{user-id}/media?access_token={access-token}

I find a way to do it without Instagram API (Sources https://stackoverflow.com/a/33783840/12739212) but I'm afraid they will change their code and therefore this solution will no longer work so I would like to do it with the Instagram API

        $html = file_get_contents('https://instagram.com/' . $username . '/');
        preg_match('/_sharedData = ({.*);<\/script>/', $html, $matches);
        $profil_data = json_decode($matches[1])->entry_data->ProfilePage[0]->graphql->user;
        $data_edges = $profil_data->edge_owner_to_timeline_media->edges;

        foreach ($data_edges as $key => $value) {
            $img_url = $value->node->display_url;
            echo "";
        }

Thanks in advance.


问:
Does using a different linker produce different machine code?
If I write a complex program and build it, will the machine code generated at the end of the day be different if I use, say, ld vs lld vs gold?

答:
Yes, it most likely will. It's not correct to assume that linking with different linkers will produce the same machine code.

The simplest thing that can happen is that the order of functions in the final executable can vary arbitrarily from linker to linker, and therefore the machine code used to make relative calls can vary. One linker may decide to put func_a at address 0x1000 therefore translating calls to that function to something like call 0x1000, while another linker could place the same function at a different address generating for example call 0x2000. The final machine code will therefore differ.

On top of that, at least for ELF executables, there really is no rule about how external symbol references should be ordered in the binary or about what machine code should be used for runtime symbol resolution. PLT (Procedure Linkage Table) stubs could be very different from one linker to another.


问:
Concatenation in Haskell and confusion with AList ([a] -> [a])
I have a project where we are improving the speed of concatenating a list in Haskell.
I'm new to Haskell and confused about  AList ([a] -> [a]) Specifically how to convert my AppendedList to a regular List. Any help would be appreciated.

```<code>newtype AppendedList a = AList ([a] -> [a])

-- List[5] is represented as AList (\x -> 5:x)
-- This function takes an argument and returns the AppendedList for that
single :: a -> AppendedList a
single m = AList (\x -> m : x)

-- converts AppendedList to regular List
toList :: AppendedList a -> [a]
toList = ???
</code>```

答:
AppendedList a is a type.

AList f is a datum of that type, with some function f :: [a] -> [a] "inside it".

f is a function from lists to lists with the same type of elements.

We can call it with some_list :: [a] to get resulting_list :: [a]:

```<code>f           :: [a] -> [a]
  some_list :: [a]
-------------------------
f some_list ::        [a]

resulting_list ::     [a]
resulting_list = f some_list
</code>```

We can use resulting_list as some_list, too, i.e..

```<code>resulting_list = f resulting_list
</code>```

because it has the same type, that fits f's expectations (and because of Haskell's laziness). Thus

```<code>toList (...) = let { ... = ... }
               in ...
</code>```

is one possible definition. With it,

```<code>take 2 (toList (single 5))
</code>```

would return [5,5].

edit: Certainly [5,5] is not the list containing a single 5. Moreover, take 4 ... would return [5,5,5,5], so our representation contains any amount of fives, not just one of them. But, it contains only one distinct number, 5.

This is reminiscent of two Applicative Functor instances for lists, the [] and the ZipList. pure 5 :: [] Int indeed contains just one five, but pure 5 :: ZipList Int contains any amount of fives, but only fives. Of course it's hard to append infinite lists, so it's mainly just a curiosity here. A food for thought.

In any case it shows that there's more than just one way to write a code that typechecks here. There's more than just one list at our disposal here. The simplest one is indeed [], but the other one is .... our list itself!

Body:
I have a project where we are improving the speed of concatenating a list in Haskell.
I'm new to Haskell and confused about  AList ([a] -> [a]) Specifically how to convert my AppendedList to a regular List. Any help would be appreciated.

newtype AppendedList a = AList ([a] -> [a])

-- List[5] is represented as AList (\x -> 5:x)
-- This function takes an argument and returns the AppendedList for that
single :: a -> AppendedList a
single m = AList (\x -> m : x)

-- converts AppendedList to regular List
toList :: AppendedList a -> [a]
toList = ???

Body:
AppendedList a is a type.

AList f is a datum of that type, with some function f :: [a] -> [a] "inside it".

f is a function from lists to lists with the same type of elements.

We can call it with some_list :: [a] to get resulting_list :: [a]:

f           :: [a] -> [a]
  some_list :: [a]
-------------------------
f some_list ::        [a]

resulting_list ::     [a]
resulting_list = f some_list

We can use resulting_list as some_list, too, i.e..

resulting_list = f resulting_list

because it has the same type, that fits f's expectations (and because of Haskell's laziness). Thus

toList (...) = let { ... = ... }
               in ...

is one possible definition. With it,

take 2 (toList (single 5))

would return [5,5].

edit: Certainly [5,5] is not the list containing a single 5. Moreover, take 4 ... would return [5,5,5,5], so our representation contains any amount of fives, not just one of them. But, it contains only one distinct number, 5.

This is reminiscent of two Applicative Functor instances for lists, the [] and the ZipList. pure 5 :: [] Int indeed contains just one five, but pure 5 :: ZipList Int contains any amount of fives, but only fives. Of course it's hard to append infinite lists, so it's mainly just a curiosity here. A food for thought.

In any case it shows that there's more than just one way to write a code that typechecks here. There's more than just one list at our disposal here. The simplest one is indeed [], but the other one is .... our list itself!


问:
why cerr flushes the buffer of cout
```<code>#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
#include <cstdio>

int   main( )
{
    char pbuffer[BUFSIZ];
    setbuf(stdout, pbuffer);
    cout << "hello cout" ;
    sleep(5);
    cerr << "hello cerr";
    sleep(5);
    cout << "\nAll   done " << endl;
    sleep(5);
    return 0;
}
</code>```

after I compile and run the program above, it's output is :

```<code>hello couthello cerr
All   done
</code>```

but I think it should be:

```<code>hello cerrhello cout
All   done
</code>```

I want to know, why cerr flushes the buffer of cout ?

答:
This is by design.

Both cin and cerr are tied to cout, and calls cout.flush() before any of their own operations.

The idea is probably that input and output should occur in a proper order.

Title: why cerr flushes the buffer of cout

Body:
#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
#include <cstdio>

int   main( )
{
    char pbuffer[BUFSIZ];
    setbuf(stdout, pbuffer);
    cout << "hello cout" ;
    sleep(5);
    cerr << "hello cerr";
    sleep(5);
    cout << "\nAll   done " << endl;
    sleep(5);
    return 0;
}

after I compile and run the program above, it's output is :

hello couthello cerr
All   done

but I think it should be:

hello cerrhello cout
All   done

I want to know, why cerr flushes the buffer of cout ?


问:
Tableau calculation to disregard filters
My data looks like this:

```<code>endtimestamp|account|volume|pk|var1

jan-1, conosco, 123, 13231, a
jan-1, conosco, 123, 13231, b
jan-1, conosco, 123, 13231, c
jan-1, acme, 1323, 2123123, a
jan-1, acme, 1323, 2123123, b
jan-1, acme, 1323, 2123123, c
jan-2, conosco, 128, 131231, a
jan-2, conosco, 128, 131231, b
jan-2, conosco, 128, 131231, c
jan-2, acme, 1329, 31323, a
jan-2, acme, 1329, 31323, b
jan-2, acme, 1329, 31323, c
...
</code>```

I have a calculation to get the sum based upon filter

Call it fixed_sum_volume

sum({FIXED [pk], [account]: max([volume])})

I have two filters

endtimestamp

account

When the date range Jan 1 is selected and the account ACME is selected

fixed_sum_of_volume will give me the sum of the date range - 1323

I need to divide this by the average of all time and i cannot figure out how to do this or if it is even possible with tableau.

Seems like it would be easy but i have been grappling with this for a while.

All in all, i am looking for:

avg(filtered volume)/avg(non filtered volume)

答:
Well I'm not sure what sum(x)/avg(y) gives you but the below accomplishes it. BTW your value "fixed_sum_of_volume" given above is incorrect. You have 3 rows for 'acme' account for date 'Jan-1' each for 1323, the sum therefore is 3969.</p>

```<code>with mytbl (endtimestamp,account,volume,pk,var1)  as
   ( values   (to_date('jan-1','mon-dd'), 'conosco', 123, 13231, 'a')
            , (to_date('jan-1','mon-dd'), 'conosco', 123, 13231, 'b')
            , (to_date('jan-1','mon-dd'), 'conosco', 123, 13231, 'c')
            , (to_date('jan-1','mon-dd'), 'acme', 1323, 2123123, 'a')
            , (to_date('jan-1','mon-dd'), 'acme', 1323, 2123123, 'b')
            , (to_date('jan-1','mon-dd'), 'acme', 1323, 2123123, 'c')
            , (to_date('jan-2','mon-dd'), 'conosco', 128, 131231, 'a')
            , (to_date('jan-2','mon-dd'), 'conosco', 128, 131231, 'b')
            , (to_date('jan-2','mon-dd'), 'conosco', 128, 131231, 'c')
            , (to_date('jan-2','mon-dd'), 'acme', 1329, 31323, 'a')
            , (to_date('jan-2','mon-dd'), 'acme', 1329, 31323, 'b')
            , (to_date('jan-2','mon-dd'), 'acme', 1329, 31323, 'c')
     )
select account, fixed_sum_of_volume, average_of_all_time, fixed_sum_of_volume/average_of_all_time "sum(filtered volume)/avg(non filtered volume)?"
  from
       ( select m.account
              , sum(m.volume) filter (where to_date('jan-1','mon-dd') = m.endtimestamp) over() fixed_sum_of_volume
              , (select avg(m2.volume) from mytbl m2 where m2.account = 'acme' group by m2.account) average_of_all_time
           from mytbl m
          where m.account = 'acme'
       ) a;
</code>```

Body:
My data looks like this:

endtimestamp|account|volume|pk|var1

jan-1, conosco, 123, 13231, a
jan-1, conosco, 123, 13231, b
jan-1, conosco, 123, 13231, c
jan-1, acme, 1323, 2123123, a
jan-1, acme, 1323, 2123123, b
jan-1, acme, 1323, 2123123, c
jan-2, conosco, 128, 131231, a
jan-2, conosco, 128, 131231, b
jan-2, conosco, 128, 131231, c
jan-2, acme, 1329, 31323, a
jan-2, acme, 1329, 31323, b
jan-2, acme, 1329, 31323, c
...

I have a calculation to get the sum based upon filter

Call it fixed_sum_volume

sum({FIXED [pk], [account]: max([volume])})

I have two filters

endtimestamp

account

When the date range Jan 1 is selected and the account ACME is selected

fixed_sum_of_volume will give me the sum of the date range - 1323

I need to divide this by the average of all time and i cannot figure out how to do this or if it is even possible with tableau.

Seems like it would be easy but i have been grappling with this for a while.

All in all, i am looking for:

avg(filtered volume)/avg(non filtered volume)

Body:
Well I'm not sure what sum(x)/avg(y) gives you but the below accomplishes it. BTW your value "fixed_sum_of_volume" given above is incorrect. You have 3 rows for 'acme' account for date 'Jan-1' each for 1323, the sum therefore is 3969.

with mytbl (endtimestamp,account,volume,pk,var1)  as
   ( values   (to_date('jan-1','mon-dd'), 'conosco', 123, 13231, 'a')
            , (to_date('jan-1','mon-dd'), 'conosco', 123, 13231, 'b')
            , (to_date('jan-1','mon-dd'), 'conosco', 123, 13231, 'c')
            , (to_date('jan-1','mon-dd'), 'acme', 1323, 2123123, 'a')
            , (to_date('jan-1','mon-dd'), 'acme', 1323, 2123123, 'b')
            , (to_date('jan-1','mon-dd'), 'acme', 1323, 2123123, 'c')
            , (to_date('jan-2','mon-dd'), 'conosco', 128, 131231, 'a')
            , (to_date('jan-2','mon-dd'), 'conosco', 128, 131231, 'b')
            , (to_date('jan-2','mon-dd'), 'conosco', 128, 131231, 'c')
            , (to_date('jan-2','mon-dd'), 'acme', 1329, 31323, 'a')
            , (to_date('jan-2','mon-dd'), 'acme', 1329, 31323, 'b')
            , (to_date('jan-2','mon-dd'), 'acme', 1329, 31323, 'c')
     )
select account, fixed_sum_of_volume, average_of_all_time, fixed_sum_of_volume/average_of_all_time "sum(filtered volume)/avg(non filtered volume)?"
  from
       ( select m.account
              , sum(m.volume) filter (where to_date('jan-1','mon-dd') = m.endtimestamp) over() fixed_sum_of_volume
              , (select avg(m2.volume) from mytbl m2 where m2.account = 'acme' group by m2.account) average_of_all_time
           from mytbl m
          where m.account = 'acme'
       ) a;


问:
How can i configure local by flywheel v5.0.7 site.config.hbs file for roots bedrock
I am a windows 10 user

i have installed local by flywheel v5.0.7 & i want to configure roots bedrock into the app folder. now how can i change the default configure (nginx > site.conf.hbs) public folder to bedrock/web folder

enter image description here

答:
I had a similar issue and found this article which outlines using the full path to the location of the install.

Local 5 and newer utilizes a native stack, so paths such as /app won’t work anymore. You will need to provide the entire path.

https://localwp.com/community/t/adding-bedrock-to-local-version-5/15542/3


问:
redeclaring a struct instance to same variable name is returning old object in golang
I am trying to create a bunch of struct instance and append to a list after setting some values. This was reusing the variable. This was not working as it turns out golang was returning the same object. This is against what I expect. Is there any rationale for the behavior? What is the solution. Below is the code snippet from goplayground.

```<code>package main

import (
    "fmt"
)

type a struct {
I int
}

func main() {
b := new(a)

b.I = 10
fmt.Printf("Hello, playground %v p: %p", b, &b)

b = new(a)
b.I = 12
fmt.Printf(" Hello, playground %v p: %p", b, &b)

}
</code>```

here is the output :

```<code>Hello, playground &{10} **p: 0x40c138** Hello, playground &{12} **p: 0x40c138**
</code>```

答:
On your example, you're printing the address of variable b, not the value

try this:

```<code>package main

import (
    "fmt"
)

type a struct {
    I int
}

func main() {
    b := &a{}

    b.I = 10
    fmt.Printf("Hello, playground %v p: %p", b, b)

    b = &a{}
    b.I = 12
    fmt.Printf(" Hello, playground %v p: %p", b, b)

}
</code>```

Hello, playground &{10} p: 0x40e020 Hello, playground &{12} p: 0x40e02c

https://play.golang.org/p/58qP6ggV5K8

Body:
I am trying to create a bunch of struct instance and append to a list after setting some values. This was reusing the variable. This was not working as it turns out golang was returning the same object. This is against what I expect. Is there any rationale for the behavior? What is the solution. Below is the code snippet from goplayground.

package main

import (
    "fmt"
)

type a struct {
I int
}

func main() {
b := new(a)

b.I = 10
fmt.Printf("Hello, playground %v p: %p", b, &b)

b = new(a)
b.I = 12
fmt.Printf(" Hello, playground %v p: %p", b, &b)

}

here is the output :

Hello, playground &{10} **p: 0x40c138** Hello, playground &{12} **p: 0x40c138**

Body:
On your example, you're printing the address of variable b, not the value

try this:

package main

import (
    "fmt"
)

type a struct {
    I int
}

func main() {
    b := &a{}

    b.I = 10
    fmt.Printf("Hello, playground %v p: %p", b, b)

    b = &a{}
    b.I = 12
    fmt.Printf(" Hello, playground %v p: %p", b, b)

}

Hello, playground &{10} p: 0x40e020 Hello, playground &{12} p: 0x40e02c

https://play.golang.org/p/58qP6ggV5K8


问:
Why does intializing array with structs requires specifying the struct name
Why does this code produce compile time error?

```<code>#include <array>
#include <cstdint>
#include <string_view>

using namespace std::string_view_literals;

enum class my_enum : std::size_t {
    first = 0,
    second,
    third,

    COUNT,
};

struct my_enum_str_pair {
    std::string_view str;
    my_enum command;
};

constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
    { "first"sv, my_enum::first },
    { "second"sv, my_enum::second }, // error: excess elements in struct initializer
    { "third"sv, my_enum::third },
};
</code>```

But if we change it to

```<code>...

constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
    my_enum_str_pair{ "first"sv, my_enum::first },
    { "second"sv, my_enum::second },
    { "third"sv, my_enum::third },
};
</code>```

Is compiles just fine?

https://godbolt.org/z/pi2j8a

答:
The behavior is explained by the following quote from the C++ 17 Standard (11.6.1 Aggregates)

12 Braces can be elided in an initializer-list as follows. If the
  initializer-list begins with a left brace, then the succeeding
  comma-separated list of initializer-clauses initializes the elements
  of a subaggregate; it is erroneous  for there to be more
  initializer-clauses than elements. If, however, the initializer-list
  for a subaggregate does not begin with a left brace, then only enough
  initializer-clauses from the list are taken to initialize the elements
  of the subaggregate; any remaining initializer-clauses are left to
  initialize the next element of the aggregate of which the current
  subaggregate is an element.

The std::array is an aggregate that includes another aggregate.

```<code>constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
    { "first"sv, my_enum::first },
    { "second"sv, my_enum::second }, // error: excess elements in struct initializer
    { "third"sv, my_enum::third },
};
</code>```

So the compiler considers the first left brace in the first initializer

```<code>{ "first"sv, my_enum::first },
</code>```

^^^

As the initializer of the internal sub-aggregate (that is usually an array) of the aggregate std::array. After this list it encounters the second list

```<code>{ "second"sv, my_enum::second }
</code>```

but does not found another sub-object of the std::array. So the compiler issues an error.

If you enclose these lists in braces

```<code>constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
{
    { "first"sv, my_enum::first },
    { "second"sv, my_enum::second }, // error: excess elements in struct initializer
    { "third"sv, my_enum::third },
}
};
</code>```

then the compiler considers all sub-list as elements of the internal sub-aggregate and uses this sub-list as initializers of the constructor of the class std::pair.

In the second case the left braces

```<code>constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
                   ^^^^
    my_enum_str_pair{ "first"sv, my_enum::first },
    { "second"sv, my_enum::second },
    { "third"sv, my_enum::third },
};
</code>```

starts the initializer list of the internal sub-aggregate eliding one more braces for it.

To make it more clear consider three examples of the same program with different approaches to initializations.

The first program

```<code>#include <iostream>

struct Int
{
    Int( int x ) : x( x ) {}
    int x;
};

template <size_t N>
struct Array
{
    Int a[N];
};

int main()
{
    Array<3> a = { { 1 }, { 2 }, { 3 } };

    return 0;
}
</code>```

The compiler will issue an error because the first open brace before 1

```<code>    Array<3> a = { { 1 }, { 2 }, { 3 } };
                  ^^^
</code>```

is considered by the compiler as an initializer list of the internal aggregate Int a[N].

If to add one more pair of braces like

```<code>#include <iostream>

struct Int
{
    Int( int x ) : x( x ) {}
    int x;
};

template <size_t N>
struct Array
{
    Int a[N];
};

int main()
{
    Array<3> a = { { { 1 }, { 2 }, { 3 } } };

    return 0;
}
</code>```

Then in this case the first open braces will be the following

```<code>    Array<3> a = { { { 1 }, { 2 }, { 3 } } };
                  ^^^
</code>```

and the elements inside these braces will be considered as initializers of the internal aggregate Int a[N].

In the third program

```<code>#include <iostream>

struct Int
{
    Int( int x ) : x( x ) {}
    int x;
};

template <size_t N>
struct Array
{
    Int a[N];
};

int main()
{
    Array<3> a = { Int{ 1 }, { 2 }, { 3 } };

    return 0;
}
</code>```

the initializer list does not start with an open brace for the internal aggregate Int a[N]. It starts from the casting expression

```<code>Int{ 1 }
</code>```

So all other elements are considered by the compiler as initializers of the internal aggregate Int a[N]. So according to the quote the braces may be elided.

Body:
Why does this code produce compile time error?

#include <array>
#include <cstdint>
#include <string_view>

using namespace std::string_view_literals;

enum class my_enum : std::size_t {
    first = 0,
    second,
    third,

    COUNT,
};

struct my_enum_str_pair {
    std::string_view str;
    my_enum command;
};

constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
    { "first"sv, my_enum::first },
    { "second"sv, my_enum::second }, // error: excess elements in struct initializer
    { "third"sv, my_enum::third },
};

But if we change it to

...

constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
    my_enum_str_pair{ "first"sv, my_enum::first },
    { "second"sv, my_enum::second },
    { "third"sv, my_enum::third },
};

Is compiles just fine?

https://godbolt.org/z/pi2j8a

Body:
The behavior is explained by the following quote from the C++ 17 Standard (11.6.1 Aggregates)

12 Braces can be elided in an initializer-list as follows. If the
  initializer-list begins with a left brace, then the succeeding
  comma-separated list of initializer-clauses initializes the elements
  of a subaggregate; it is erroneous  for there to be more
  initializer-clauses than elements. If, however, the initializer-list
  for a subaggregate does not begin with a left brace, then only enough
  initializer-clauses from the list are taken to initialize the elements
  of the subaggregate; any remaining initializer-clauses are left to
  initialize the next element of the aggregate of which the current
  subaggregate is an element.

The std::array is an aggregate that includes another aggregate.

constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
    { "first"sv, my_enum::first },
    { "second"sv, my_enum::second }, // error: excess elements in struct initializer
    { "third"sv, my_enum::third },
};

So the compiler considers the first left brace in the first initializer

{ "first"sv, my_enum::first },

^^^

As the initializer of the internal sub-aggregate (that is usually an array) of the aggregate std::array. After this list it encounters the second list

{ "second"sv, my_enum::second }

but does not found another sub-object of the std::array. So the compiler issues an error.

If you enclose these lists in braces

constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
{
    { "first"sv, my_enum::first },
    { "second"sv, my_enum::second }, // error: excess elements in struct initializer
    { "third"sv, my_enum::third },
}
};

then the compiler considers all sub-list as elements of the internal sub-aggregate and uses this sub-list as initializers of the constructor of the class std::pair.

In the second case the left braces

constexpr
std::array<my_enum_str_pair, static_cast<std::size_t>(my_enum::COUNT)>
my_enum_str_pairs = {
                   ^^^^
    my_enum_str_pair{ "first"sv, my_enum::first },
    { "second"sv, my_enum::second },
    { "third"sv, my_enum::third },
};

starts the initializer list of the internal sub-aggregate eliding one more braces for it.

To make it more clear consider three examples of the same program with different approaches to initializations.

The first program

#include <iostream>

struct Int
{
    Int( int x ) : x( x ) {}
    int x;
};

template <size_t N>
struct Array
{
    Int a[N];
};

int main()
{
    Array<3> a = { { 1 }, { 2 }, { 3 } };

    return 0;
}

The compiler will issue an error because the first open brace before 1

    Array<3> a = { { 1 }, { 2 }, { 3 } };
                  ^^^

is considered by the compiler as an initializer list of the internal aggregate Int a[N].

If to add one more pair of braces like

#include <iostream>

struct Int
{
    Int( int x ) : x( x ) {}
    int x;
};

template <size_t N>
struct Array
{
    Int a[N];
};

int main()
{
    Array<3> a = { { { 1 }, { 2 }, { 3 } } };

    return 0;
}

Then in this case the first open braces will be the following

    Array<3> a = { { { 1 }, { 2 }, { 3 } } };
                  ^^^

and the elements inside these braces will be considered as initializers of the internal aggregate Int a[N].

In the third program

#include <iostream>

struct Int
{
    Int( int x ) : x( x ) {}
    int x;
};

template <size_t N>
struct Array
{
    Int a[N];
};

int main()
{
    Array<3> a = { Int{ 1 }, { 2 }, { 3 } };

    return 0;
}

the initializer list does not start with an open brace for the internal aggregate Int a[N]. It starts from the casting expression

Int{ 1 }

So all other elements are considered by the compiler as initializers of the internal aggregate Int a[N]. So according to the quote the braces may be elided.


问:
How to uniquely identify a java process after multiple restart
I have number of java process running on my machine. I need to track how many times each process is getting restarted.

For Example:
Let us consider two java process
Process 1 - Its restarted for 5 times.
Process 2 - Its restarted for 2 times.

I'm able to get the PID, java command of the running processes. But I could not able to differentiate once the process got restarted. Because the PID changed after the restart. Also I can't consider the java command because two instance of same application which has same command.

So what are the other ways to track the java process restart ?

答:
You want your processes to keep the same identity after a restart. Ideally, you would have a parameter, system property or environment variable telling the process its identity.

As you state in the question, this identity cannot be passed on the command line. Thus, the process has to "find" its identity by acquiring an exclusive resource.

This resource could be a shared system implementing locks but it is probably to complex.

As exclusive resources, we have network sockets. So you could make your processes artificially opening a socket in the sole objective to make it acquire an identity.

You can use the code from https://stackoverflow.com/a/116113/2242270 in order to open a socket in a range. The identity of the process is then the port that could be opened.


问:
React Router: need
I have this code I have been trying to get to work. Cannot figure out whats wrong with it! There are no errors and I have tried several ways of importing/exporting, and changing the functions to const.</p>

```<code> import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Home } from "./Home";
import { Contact } from "./Contact";

class App extends Component {
  render() {
    return (
      <React.Fragment>
        <Router>
          <Switch>
            <Route path="/" component={Home} />
            <Route path="/contact">
              <Contact />
            </Route>
          </Switch>
        </Router>
      </React.Fragment>
    );
  }
}
export default App;

Then I have two separate functions

    import React from "react";

export function Home() {
  return (
    <div>
      <h2>Whats up!</h2>
      <p>This is sample text. </p>
    </div>
  );
}
    import React from "react";

export function Contact() {
  return (
    <div>
      <h2>Contact page!</h2>
      <p>This is different text. </p>
    </div>
  );
}
export default Contact;
</code>```

答:
Based on your last comment - "The above code actually displays whatever is in the first Route no matter the url", the issue is that you're not providing the Route components with an exact prop of true.

Switch will render the first matching Route and skip all the other ones. Since / "matches" all routes, you're only seeing the Home component.

Title: React Router: need

Body:
I have this code I have been trying to get to work. Cannot figure out whats wrong with it! There are no errors and I have tried several ways of importing/exporting, and changing the functions to const.

 import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Home } from "./Home";
import { Contact } from "./Contact";

class App extends Component {
  render() {
    return (
      <React.Fragment>
        <Router>
          <Switch>
            <Route path="/" component={Home} />
            <Route path="/contact">
              <Contact />
            </Route>
          </Switch>
        </Router>
      </React.Fragment>
    );
  }
}
export default App;

Then I have two separate functions

    import React from "react";

export function Home() {
  return (

Whats up!

This is sample text.

  );
}
    import React from "react";

export function Contact() {
  return (

Contact page!

This is different text.

  );
}
export default Contact;


问:
Compile selinux in private directory
I'm trying to compile selinux in a private directory as drescribed here:
https://github.com/SELinuxProject/selinux

For the compilation to work I also compiled xmlto and added it's bin-dir to $PATH.

The compilation fails with the following lines.

```<code>xmlto man secilc.8.xml
xmlto: /opt/seafile/Sourcecode/selinux/secilc/secilc.8.xml does not validate (status 3)
xmlto: Fix document syntax or use --skip-validation option
I/O error : Attempt to load network entity http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd
/opt/seafile/Sourcecode/selinux/secilc/secilc.8.xml:3: warning: failed to load external entity "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
               "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
                                                                        ^
I/O error : Attempt to load network entity http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd
warning: failed to load external entity "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
validity error : Could not load the external subset "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
Document /opt/seafile/Sourcecode/selinux/secilc/secilc.8.xml does not validate
make[1]: *** [Makefile:36: secilc.8] Fehler 13
make[1]: Verzeichnis „/opt/seafile/Sourcecode/selinux/secilc“ wird verlassen
make: *** [Makefile:34: install] Fehler 1
</code>```

Any ideas what I'm doing wrong? Can I somehow tell make not to build the documentation? Seem's to be a manpages thing.

Additional info: I actually only need libselinux since It's required by seafile for some reason.

Thanks in advance

Markus

答: Unfortunately you're not mentioning the Linux distribution you're using. Your system is missing the "XML document type definitions for DocBook", often shipped in a package called docbook-dtds (Fedora, RHEL/CentOS) or docbook-xml (Debian). Alternatively you could adapt your packet filter so that your system reaches the mentioned URLs in the error message.

Title: Compile selinux in private directory

Body:
I'm trying to compile selinux in a private directory as drescribed here:
https://github.com/SELinuxProject/selinux

For the compilation to work I also compiled xmlto and added it's bin-dir to $PATH.

The compilation fails with the following lines.

xmlto man secilc.8.xml
xmlto: /opt/seafile/Sourcecode/selinux/secilc/secilc.8.xml does not validate (status 3)
xmlto: Fix document syntax or use --skip-validation option
I/O error : Attempt to load network entity http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd
/opt/seafile/Sourcecode/selinux/secilc/secilc.8.xml:3: warning: failed to load external entity "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
               "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
                                                                        ^
I/O error : Attempt to load network entity http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd
warning: failed to load external entity "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
validity error : Could not load the external subset "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
Document /opt/seafile/Sourcecode/selinux/secilc/secilc.8.xml does not validate
make[1]: *** [Makefile:36: secilc.8] Fehler 13
make[1]: Verzeichnis „/opt/seafile/Sourcecode/selinux/secilc“ wird verlassen
make: *** [Makefile:34: install] Fehler 1

Any ideas what I'm doing wrong? Can I somehow tell make not to build the documentation? Seem's to be a manpages thing.

Additional info: I actually only need libselinux since It's required by seafile for some reason.

Thanks in advance

Markus